-
-
Save bczhc/2acab14d36395760af04579c3e89e625 to your computer and use it in GitHub Desktop.
桥式LSE打乱生成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use once_cell::sync::Lazy; | |
use ring::rand::{SecureRandom, SystemRandom}; | |
use std::mem; | |
use std::sync::RwLock; | |
const SCRAMBLE_LENGTH: i32 = 15; | |
static RNG: Lazy<RwLock<Option<SystemRandom>>> = Lazy::new(|| RwLock::new(None)); | |
fn main() { | |
let rng = ring::rand::SystemRandom::new(); | |
RNG.write().unwrap().replace(rng); | |
for _ in 0..100 { | |
println!("{}", gen_scramble()); | |
} | |
} | |
fn gen_scramble() -> String { | |
let mut guard = RNG.write().unwrap(); | |
let rng = guard.as_mut().unwrap(); | |
let mut s = String::new(); | |
for i in 0..SCRAMBLE_LENGTH { | |
let random = random(rng); | |
match i % 2 { | |
0 => { | |
if random == 3 { | |
s.push_str("M'"); | |
} else if random == 1 { | |
s.push('M'); | |
} else { | |
s.push('M'); | |
s.push(char::from_u32((b'0' + random as u8) as u32).unwrap()) | |
} | |
} | |
1 => { | |
if random == 3 { | |
s.push_str("U'"); | |
} else if random == 1 { | |
s.push('U'); | |
} else { | |
s.push('U'); | |
s.push(char::from_u32((b'0' + random as u8) as u32).unwrap()) | |
} | |
} | |
_ => { | |
unreachable!(); | |
} | |
}; | |
s.push(' '); | |
} | |
s | |
} | |
fn random(rng: &mut SystemRandom) -> i32 { | |
let mut buf = [0_u8; 16]; | |
rng.fill(&mut buf).unwrap(); | |
let x: u128 = unsafe { mem::transmute(buf) }; | |
(x % 3_u128) as i32 + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment