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
14use core::convert::TryInto;
15
16/// Reads unsigned 32 bit integers from `src` into `dst`.
17#[inline]
18pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
19 assert!(src.len() >= 4 * dst.len());
20 for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) {
21 *out = u32::from_le_bytes(chunk.try_into().unwrap());
22 }
23}
24
25/// Reads unsigned 64 bit integers from `src` into `dst`.
26#[inline]
27pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
28 assert!(src.len() >= 8 * dst.len());
29 for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) {
30 *out = u64::from_le_bytes(chunk.try_into().unwrap());
31 }
32}
33
34#[test]
35fn test_read() {
36 let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
37
38 let mut buf = [0u32; 4];
39 read_u32_into(&bytes, &mut buf);
40 assert_eq!(buf[0], 0x04030201);
41 assert_eq!(buf[3], 0x100F0E0D);
42
43 let mut buf = [0u32; 3];
44 read_u32_into(&bytes[1..13], &mut buf); // unaligned
45 assert_eq!(buf[0], 0x05040302);
46 assert_eq!(buf[2], 0x0D0C0B0A);
47
48 let mut buf = [0u64; 2];
49 read_u64_into(&bytes, &mut buf);
50 assert_eq!(buf[0], 0x0807060504030201);
51 assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
52
53 let mut buf = [0u64; 1];
54 read_u64_into(&bytes[7..15], &mut buf); // unaligned
55 assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
56}
57