rust_rcs_core/util/rand.rs
1// Copyright 2023 宋昊文
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use rand::prelude::*;
16
17pub fn create_raw_alpha_numeric_string(length: usize) -> Vec<u8> {
18 let mut s = Vec::with_capacity(length);
19 let mut rng = rand::thread_rng();
20 for _ in 0..length {
21 let mut c = rng.gen_range(0..62);
22 if c < 10 {
23 c = 48 + c
24 } else if c < 36 {
25 c = 65 + c - 10
26 } else {
27 c = 97 + c - 36
28 }
29 s.push(c);
30 }
31 s
32}
33
34#[cfg(test)]
35mod tests {
36 use super::create_raw_alpha_numeric_string;
37
38 #[test]
39 fn test_create_raw_alpha_numeric_string() {
40 let data = create_raw_alpha_numeric_string(16);
41 let s = String::from_utf8_lossy(&data);
42
43 println!("{}", &s);
44
45 assert_eq!(s.len(), 16)
46 }
47}