1 | // Copyright 2018 Developers of the Rand project. |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
4 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
6 | // option. This file may not be copied, modified, or distributed |
7 | // except according to those terms. |
8 | |
9 | //! Little-Endian utilities |
10 | //! |
11 | //! Little-Endian order has been chosen for internal usage; this makes some |
12 | //! useful functions available. |
13 | |
14 | /// Reads unsigned 32 bit integers from `src` into `dst`. |
15 | /// |
16 | /// # Panics |
17 | /// |
18 | /// If `dst` has insufficient space (`4*dst.len() < src.len()`). |
19 | #[inline ] |
20 | #[track_caller ] |
21 | pub fn read_u32_into(src: &[u8], dst: &mut [u32]) { |
22 | assert!(src.len() >= 4 * dst.len()); |
23 | for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) { |
24 | *out = u32::from_le_bytes(chunk.try_into().unwrap()); |
25 | } |
26 | } |
27 | |
28 | /// Reads unsigned 64 bit integers from `src` into `dst`. |
29 | /// |
30 | /// # Panics |
31 | /// |
32 | /// If `dst` has insufficient space (`8*dst.len() < src.len()`). |
33 | #[inline ] |
34 | #[track_caller ] |
35 | pub fn read_u64_into(src: &[u8], dst: &mut [u64]) { |
36 | assert!(src.len() >= 8 * dst.len()); |
37 | for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) { |
38 | *out = u64::from_le_bytes(chunk.try_into().unwrap()); |
39 | } |
40 | } |
41 | |
42 | #[test] |
43 | fn test_read() { |
44 | let bytes: [i32; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; |
45 | |
46 | let mut buf: [u32; 4] = [0u32; 4]; |
47 | read_u32_into(&bytes, &mut buf); |
48 | assert_eq!(buf[0], 0x04030201); |
49 | assert_eq!(buf[3], 0x100F0E0D); |
50 | |
51 | let mut buf: [u32; _] = [0u32; 3]; |
52 | read_u32_into(&bytes[1..13], &mut buf); // unaligned |
53 | assert_eq!(buf[0], 0x05040302); |
54 | assert_eq!(buf[2], 0x0D0C0B0A); |
55 | |
56 | let mut buf: [u64; _] = [0u64; 2]; |
57 | read_u64_into(&bytes, &mut buf); |
58 | assert_eq!(buf[0], 0x0807060504030201); |
59 | assert_eq!(buf[1], 0x100F0E0D0C0B0A09); |
60 | |
61 | let mut buf: [u64; _] = [0u64; 1]; |
62 | read_u64_into(&bytes[7..15], &mut buf); // unaligned |
63 | assert_eq!(buf[0], 0x0F0E0D0C0B0A0908); |
64 | } |
65 | |