@@ -302,6 +302,75 @@ mod allocating {
302
302
IntRef { inner }
303
303
}
304
304
}
305
+
306
+ macro_rules! impl_from_traits {
307
+ ( $( $int: ty) ,+) => {
308
+ $(
309
+ impl TryFrom <$int> for Int {
310
+ type Error = $crate:: Error ;
311
+
312
+ fn try_from( value: $int) -> $crate:: Result <Self > {
313
+ let mut buf = [ 0u8 ; 16 ] ;
314
+ let mut writer = $crate:: SliceWriter :: new( & mut buf[ ..] ) ;
315
+ value. encode_value( & mut writer) ?;
316
+ let buf = writer. finish( ) ?;
317
+ Int :: new( buf)
318
+ }
319
+ }
320
+ ) +
321
+ } ;
322
+ }
323
+
324
+ impl_from_traits ! ( i8 , i16 , i32 , i64 , i128 ) ;
325
+
326
+ #[ cfg( test) ]
327
+ #[ allow( clippy:: unwrap_used) ]
328
+ mod tests {
329
+ use super :: Int ;
330
+
331
+ #[ test]
332
+ fn from_uint ( ) {
333
+ assert_eq ! ( Int :: try_from( i8 :: MIN ) . unwrap( ) . as_bytes( ) , & [ 0x80 ] ) ;
334
+ assert_eq ! ( Int :: try_from( i8 :: MAX ) . unwrap( ) . as_bytes( ) , & [ 0x7F ] ) ;
335
+ assert_eq ! ( Int :: try_from( i16 :: MIN ) . unwrap( ) . as_bytes( ) , & [ 0x80 , 0 ] ) ;
336
+ assert_eq ! ( Int :: try_from( i16 :: MAX ) . unwrap( ) . as_bytes( ) , & [ 0x7F , 0xFF ] ) ;
337
+ assert_eq ! (
338
+ Int :: try_from( i32 :: MIN ) . unwrap( ) . as_bytes( ) ,
339
+ & [ 0x80 , 0 , 0 , 0 ]
340
+ ) ;
341
+ assert_eq ! (
342
+ Int :: try_from( i32 :: MAX ) . unwrap( ) . as_bytes( ) ,
343
+ & [ 0x7F , 0xFF , 0xFF , 0xFF ]
344
+ ) ;
345
+ assert_eq ! (
346
+ Int :: try_from( i64 :: MIN ) . unwrap( ) . as_bytes( ) ,
347
+ & [
348
+ 0x80 , 0 , 0 , 0 , //
349
+ 0 , 0 , 0 , 0
350
+ ]
351
+ ) ;
352
+ assert_eq ! (
353
+ Int :: try_from( i64 :: MAX ) . unwrap( ) . as_bytes( ) ,
354
+ & [
355
+ 0x7F , 0xFF , 0xFF , 0xFF , //
356
+ 0xFF , 0xFF , 0xFF , 0xFF //
357
+ ]
358
+ ) ;
359
+ assert_eq ! (
360
+ Int :: try_from( i128 :: MIN ) . unwrap( ) . as_bytes( ) ,
361
+ & [ 0x80 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ]
362
+ ) ;
363
+ assert_eq ! (
364
+ Int :: try_from( i128 :: MAX ) . unwrap( ) . as_bytes( ) ,
365
+ & [
366
+ 0x7F , 0xFF , 0xFF , 0xFF , //
367
+ 0xFF , 0xFF , 0xFF , 0xFF , //
368
+ 0xFF , 0xFF , 0xFF , 0xFF , //
369
+ 0xFF , 0xFF , 0xFF , 0xFF , //
370
+ ]
371
+ ) ;
372
+ }
373
+ }
305
374
}
306
375
307
376
/// Ensure `INTEGER` is canonically encoded.
0 commit comments