File tree Expand file tree Collapse file tree 1 file changed +22
-7
lines changed Expand file tree Collapse file tree 1 file changed +22
-7
lines changed Original file line number Diff line number Diff line change 19
19
20
20
use alloc:: vec:: Vec ;
21
21
22
- /// reads a u16 from an array of bytes
22
+ /// Reads a `u16` from an array of bytes
23
+ ///
24
+ /// # Panics
25
+ ///
26
+ /// Raise a panic when the given buffer is not long enough
27
+ /// from the specified index to accomodate the size of a `u16` value
23
28
#[ must_use]
24
29
pub fn read_u16 ( buffer : & [ u8 ] , index : usize ) -> u16 {
25
- u16:: from ( buffer[ index + 1 ] ) << 8 | u16:: from ( buffer[ index] )
30
+ const SIZE : usize = std:: mem:: size_of :: < u16 > ( ) ;
31
+ let bytes: & [ u8 ; SIZE ] = buffer[ index..( index + SIZE ) ]
32
+ . try_into ( )
33
+ . expect ( "given buffer cannot contain u16 value" ) ;
34
+ u16:: from_le_bytes ( * bytes)
26
35
}
27
36
28
- /// reads a u32 from an array of bytes
37
+ /// Reads a `u32` from an array of bytes
38
+ ///
39
+ /// # Panics
40
+ ///
41
+ /// Raise a panic when the given buffer is not long enough
42
+ /// from the specified index to accomodate the size of a `u32` value
29
43
#[ must_use]
30
44
pub fn read_u32 ( buffer : & [ u8 ] , index : usize ) -> u32 {
31
- u32:: from ( buffer[ index + 3 ] ) << 24
32
- | u32:: from ( buffer[ index + 2 ] ) << 16
33
- | u32:: from ( buffer[ index + 1 ] ) << 8
34
- | u32:: from ( buffer[ index] )
45
+ const SIZE : usize = std:: mem:: size_of :: < u32 > ( ) ;
46
+ let bytes: & [ u8 ; SIZE ] = buffer[ index..( index + SIZE ) ]
47
+ . try_into ( )
48
+ . expect ( "given buffer cannot contain u32 value" ) ;
49
+ u32:: from_le_bytes ( * bytes)
35
50
}
36
51
37
52
/// Reads a table of u16 from a byte buffer
You can’t perform that action at this time.
0 commit comments