Skip to content

Commit 3a63497

Browse files
committed
Add le module, to be moved to rand_core later
Copied from dhardy/master, minus single-read functions, with extra tests
1 parent d1e0ab1 commit 3a63497

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/le.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2017-2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// https://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
//! Little-Endian utilities
12+
//!
13+
//! Little-Endian order has been chosen for internal usage; this makes some
14+
//! useful functions available.
15+
16+
// TODO: eventually these should be exported somehow
17+
#![allow(unused)]
18+
19+
use core::{mem, ptr};
20+
21+
macro_rules! read_slice {
22+
($src:expr, $dst:expr, $size:expr, $which:ident) => {{
23+
assert_eq!($src.len(), $size * $dst.len());
24+
25+
unsafe {
26+
ptr::copy_nonoverlapping(
27+
$src.as_ptr(),
28+
$dst.as_mut_ptr() as *mut u8,
29+
$src.len());
30+
}
31+
for v in $dst.iter_mut() {
32+
*v = v.$which();
33+
}
34+
}};
35+
}
36+
37+
/// Reads unsigned 32 bit integers from `src` into `dst`.
38+
/// Borrowed from the `byteorder` crate.
39+
#[inline]
40+
pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
41+
read_slice!(src, dst, 4, to_le);
42+
}
43+
44+
/// Reads unsigned 64 bit integers from `src` into `dst`.
45+
/// Borrowed from the `byteorder` crate.
46+
#[inline]
47+
pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
48+
read_slice!(src, dst, 8, to_le);
49+
}
50+
51+
#[test]
52+
fn test_read() {
53+
let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
54+
55+
let mut buf = [0u32; 4];
56+
read_u32_into(&bytes, &mut buf);
57+
assert_eq!(buf[0], 0x04030201);
58+
assert_eq!(buf[3], 0x100F0E0D);
59+
60+
let mut buf = [0u32; 3];
61+
read_u32_into(&bytes[1..13], &mut buf); // unaligned
62+
assert_eq!(buf[0], 0x05040302);
63+
assert_eq!(buf[2], 0x0D0C0B0A);
64+
65+
let mut buf = [0u64; 2];
66+
read_u64_into(&bytes, &mut buf);
67+
assert_eq!(buf[0], 0x0807060504030201);
68+
assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
69+
70+
let mut buf = [0u64; 1];
71+
read_u64_into(&bytes[7..15], &mut buf); // unaligned
72+
assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
73+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@ pub mod isaac {
298298
}
299299

300300
// private modules
301+
mod le;
301302
mod error;
302303
mod rand_impls;
303304
mod prng;

0 commit comments

Comments
 (0)