@@ -1406,6 +1406,14 @@ pub struct BytesHolder<T: MachineWord, const N: usize> {
1406
1406
array : [ T ; N ] ,
1407
1407
}
1408
1408
1409
+ impl < T : MachineWord , const N : usize > Default for BytesHolder < T , N > {
1410
+ fn default ( ) -> Self {
1411
+ Self {
1412
+ array : core:: array:: from_fn ( |_| T :: default ( ) ) ,
1413
+ }
1414
+ }
1415
+ }
1416
+
1409
1417
#[ cfg( feature = "use-unsafe" ) ]
1410
1418
impl < T : MachineWord , const N : usize > BytesHolder < T , N > {
1411
1419
// Converts internal storage to a mutable byte slice
@@ -1480,6 +1488,22 @@ where
1480
1488
}
1481
1489
}
1482
1490
1491
+ #[ cfg( feature = "use-unsafe" ) ]
1492
+ impl < T : MachineWord , const N : usize > num_traits:: FromBytes for FixedUInt < T , N >
1493
+ where
1494
+ T : core:: fmt:: Debug ,
1495
+ {
1496
+ type Bytes = BytesHolder < T , N > ;
1497
+
1498
+ fn from_be_bytes ( bytes : & Self :: Bytes ) -> Self {
1499
+ Self :: from_be_bytes ( bytes. as_ref ( ) )
1500
+ }
1501
+
1502
+ fn from_le_bytes ( bytes : & Self :: Bytes ) -> Self {
1503
+ Self :: from_le_bytes ( bytes. as_ref ( ) )
1504
+ }
1505
+ }
1506
+
1483
1507
#[ cfg( test) ]
1484
1508
mod tests {
1485
1509
use super :: FixedUInt as Bn ;
@@ -1755,4 +1779,38 @@ mod tests {
1755
1779
& [ 0x12 , 0x34 , 0x56 , 0x78 ] ,
1756
1780
) ;
1757
1781
}
1782
+
1783
+ fn from_helper < T > ( input : & [ u8 ] , expected : T )
1784
+ where
1785
+ T : num_traits:: FromBytes + core:: fmt:: Debug + core:: cmp:: PartialEq ,
1786
+ T :: Bytes : num_traits:: ops:: bytes:: NumBytes + Default + core:: fmt:: Debug ,
1787
+ {
1788
+ let mut bytes = T :: Bytes :: default ( ) ;
1789
+ bytes. as_mut ( ) . copy_from_slice ( input) ;
1790
+ let result = T :: from_be_bytes ( & bytes) ;
1791
+ assert_eq ! ( result, expected) ;
1792
+ bytes. as_mut ( ) . reverse ( ) ;
1793
+ let result = T :: from_le_bytes ( & bytes) ;
1794
+ assert_eq ! ( result, expected) ;
1795
+ }
1796
+
1797
+ #[ cfg( feature = "use-unsafe" ) ]
1798
+ #[ test]
1799
+ fn test_from_bytes ( ) {
1800
+ from_helper ( & [ 0xAB_u8 ] , 0xAB_u8 ) ;
1801
+ from_helper ( & [ 0xAB , 0xCD ] , 0xABCD_u16 ) ;
1802
+ from_helper ( & [ 0x12 , 0x34 , 0x56 , 0x78 ] , 0x12345678_u32 ) ;
1803
+ from_helper (
1804
+ & [ 0x12 , 0x34 , 0x56 , 0x78 ] ,
1805
+ FixedUInt :: < u8 , 4 > :: from_u32 ( 0x12345678 ) . unwrap ( ) ,
1806
+ ) ;
1807
+ from_helper (
1808
+ & [ 0x12 , 0x34 , 0x56 , 0x78 ] ,
1809
+ FixedUInt :: < u16 , 2 > :: from_u32 ( 0x12345678 ) . unwrap ( ) ,
1810
+ ) ;
1811
+ from_helper (
1812
+ & [ 0x12 , 0x34 , 0x56 , 0x78 ] ,
1813
+ FixedUInt :: < u32 , 1 > :: from_u32 ( 0x12345678 ) . unwrap ( ) ,
1814
+ ) ;
1815
+ }
1758
1816
}
0 commit comments