Skip to content

Commit

Permalink
sort: Add random_ints()
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Jun 28, 2024
1 parent 22932ef commit 6f8098b
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
7 changes: 7 additions & 0 deletions sort/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ publish = false

[dependencies]
rand = "0.8.5"

[dev-dependencies]
criterion = "0.5.1"

[[bench]]
name = "bubble_sort"
harness = false
10 changes: 10 additions & 0 deletions sort/benches/bubble_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) 2024 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use criterion::{Criterion, criterion_group, criterion_main};

fn criterion_benchmark(_c: &mut Criterion) {}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
34 changes: 33 additions & 1 deletion sort/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
// in the LICENSE file.

use std::fmt;
use std::io::{self, BufRead, BufReader};
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};

pub fn is_sorted<T>(list: &[T]) -> bool
where
Expand Down Expand Up @@ -74,3 +75,34 @@ pub fn read_strings() -> Vec<String> {
}
v
}

/// Generate random integers.
///
/// # Errors
/// Returns error if failed to rand system random file.
pub fn random_ints(len: usize) -> Result<Vec<i32>, io::Error> {
let mut file = File::open("/dev/urandom")?;
let mut buf = vec![0; len * 4];
file.read_exact(&mut buf)?;

let mut nums = Vec::with_capacity(len);
for i in 0..len {
let array: [u8; 4] = [buf[4 * i], buf[4 * i + 1], buf[4 * i + 2], buf[4 * i + 3]];
// let mut array: [u8; 4] = [0; 4];
// array.swap_with_slice(&mut buf[(i * 4)..(i * 4 + 4)]);
nums.push(i32::from_le_bytes(array));
}
Ok(nums)
}

#[cfg(test)]
mod tests {
use crate::util::random_ints;

#[test]
fn test_random_ints() {
let len = 100;
let nums: Vec<i32> = random_ints(len).unwrap();
assert_eq!(nums.len(), len);
}
}

0 comments on commit 6f8098b

Please sign in to comment.