]> git.proxmox.com Git - cargo.git/blob - vendor/rand_core/src/le.rs
New upstream version 0.47.0
[cargo.git] / vendor / rand_core / src / 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 use core::ptr;
15
16 macro_rules! read_slice {
17 ($src:expr, $dst:expr, $size:expr, $which:ident) => {{
18 assert_eq!($src.len(), $size * $dst.len());
19
20 unsafe {
21 ptr::copy_nonoverlapping(
22 $src.as_ptr(),
23 $dst.as_mut_ptr() as *mut u8,
24 $src.len());
25 }
26 for v in $dst.iter_mut() {
27 *v = v.$which();
28 }
29 }};
30 }
31
32 /// Reads unsigned 32 bit integers from `src` into `dst`.
33 /// Borrowed from the `byteorder` crate.
34 #[inline]
35 pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
36 read_slice!(src, dst, 4, to_le);
37 }
38
39 /// Reads unsigned 64 bit integers from `src` into `dst`.
40 /// Borrowed from the `byteorder` crate.
41 #[inline]
42 pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
43 read_slice!(src, dst, 8, to_le);
44 }
45
46 #[test]
47 fn test_read() {
48 let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
49
50 let mut buf = [0u32; 4];
51 read_u32_into(&bytes, &mut buf);
52 assert_eq!(buf[0], 0x04030201);
53 assert_eq!(buf[3], 0x100F0E0D);
54
55 let mut buf = [0u32; 3];
56 read_u32_into(&bytes[1..13], &mut buf); // unaligned
57 assert_eq!(buf[0], 0x05040302);
58 assert_eq!(buf[2], 0x0D0C0B0A);
59
60 let mut buf = [0u64; 2];
61 read_u64_into(&bytes, &mut buf);
62 assert_eq!(buf[0], 0x0807060504030201);
63 assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
64
65 let mut buf = [0u64; 1];
66 read_u64_into(&bytes[7..15], &mut buf); // unaligned
67 assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
68 }