rand_core/
le.rs

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/// Fills `dst: &mut [u32]` from `src`
15///
16/// Reads use Little-Endian byte order, allowing portable reproduction of `dst`
17/// from a byte slice.
18///
19/// # Panics
20///
21/// If `src` has insufficient length (if `src.len() < 4*dst.len()`).
22#[inline]
23#[track_caller]
24pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
25    assert!(src.len() >= 4 * dst.len());
26    for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) {
27        *out = u32::from_le_bytes(chunk.try_into().unwrap());
28    }
29}
30
31/// Fills `dst: &mut [u64]` from `src`
32///
33/// # Panics
34///
35/// If `src` has insufficient length (if `src.len() < 8*dst.len()`).
36#[inline]
37#[track_caller]
38pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
39    assert!(src.len() >= 8 * dst.len());
40    for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) {
41        *out = u64::from_le_bytes(chunk.try_into().unwrap());
42    }
43}
44
45#[test]
46fn test_read() {
47    let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
48
49    let mut buf = [0u32; 4];
50    read_u32_into(&bytes, &mut buf);
51    assert_eq!(buf[0], 0x04030201);
52    assert_eq!(buf[3], 0x100F0E0D);
53
54    let mut buf = [0u32; 3];
55    read_u32_into(&bytes[1..13], &mut buf); // unaligned
56    assert_eq!(buf[0], 0x05040302);
57    assert_eq!(buf[2], 0x0D0C0B0A);
58
59    let mut buf = [0u64; 2];
60    read_u64_into(&bytes, &mut buf);
61    assert_eq!(buf[0], 0x0807060504030201);
62    assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
63
64    let mut buf = [0u64; 1];
65    read_u64_into(&bytes[7..15], &mut buf); // unaligned
66    assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
67}