Debian Codegraph @

src/span.rs

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 use proc_macro::Span;
2 use std::option_env;
3
4 use once_cell::race::OnceBox;
5 use tiny_keccak::{Hasher, Shake, Xof};
6
7 static SEED: OnceBox<Vec<u8>> = OnceBox::new();
8
9 fn get_seed() -> &'static [u8] {
10 &SEED.get_or_init(|| {
11 if let Some(value) = option_env!("CONST_RANDOM_SEED") {
12 Box::new(value.as_bytes().to_vec())
13 } else {
14 let mut value = [0u8; 32];
15 getrandom::getrandom(&mut value).unwrap();
16 Box::new(value.to_vec())
17 }
18 })[..]
19 }
20
21 pub(crate) fn gen_random<T: Random>() -> T {
22 Random::random()
23 }
24
25 pub(crate) fn gen_random_bytes(output: &mut [u8]) {
26 hash_stuff().squeeze(output)
27 }
28
29 pub(crate) trait Random {
30 fn random() -> Self;
31 }
32
33 fn hash_stuff() -> impl Xof {
34 let span = Span::call_site();
35 let mut hasher = Shake::v256();
36 hasher.update(get_seed());
37 hasher.update(&format!("{:?}", span).as_bytes());
38 hasher
39 }
40
41 impl Random for u64 {
42 fn random() -> Self {
43 let mut output = [0; 8];
44 hash_stuff().squeeze(&mut output);
45 Self::from_ne_bytes(output)
46 }
47 }
48
49 impl Random for u128 {
50 fn random() -> Self {
51 let mut output = [0; 16];
52 hash_stuff().squeeze(&mut output);
53 Self::from_ne_bytes(output)
54 }
55 }
56
57 impl Random for u8 {
58 fn random() -> Self {
59 u64::random() as u8
60 }
61 }
62
63 impl Random for u16 {
64 fn random() -> Self {
65 u64::random() as u16
66 }
67 }
68
69 impl Random for u32 {
70 fn random() -> Self {
71 u64::random() as u32
72 }
73 }
74
75 impl Random for i8 {
76 fn random() -> Self {
77 i64::random() as i8
78 }
79 }
80
81 impl Random for i16 {
82 fn random() -> Self {
83 i64::random() as i16
84 }
85 }
86
87 impl Random for i32 {
88 fn random() -> Self {
89 i64::random() as i32
90 }
91 }
92
93 impl Random for i64 {
94 fn random() -> Self {
95 u64::random() as i64
96 }
97 }
98
99 impl Random for i128 {
100 fn random() -> Self {
101 u128::random() as i128
102 }
103 }