-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuild.rs
84 lines (65 loc) · 2.11 KB
/
build.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use {
anyhow::Context,
lazy_static::lazy_static,
rand::{seq::SliceRandom, thread_rng},
std::{
any::type_name, env::var, error::Error, fmt::Display, fs::File, io::Write, path::PathBuf,
},
};
// We want a shuffled array of all u8's but we don't want to generate them at runtime.
// This data is used to load image chunks in a somewhat better looking order than by scan row.
// Also we want to use a number of these arrays so repeated/frequent changes don't appear similar.
const COUNT: usize = 32;
lazy_static! {
static ref OUT_DIR: PathBuf = PathBuf::from(var("OUT_DIR").unwrap());
}
fn main() -> anyhow::Result<()> {
let path = OUT_DIR.join("rand.rs");
let mut file = File::create(&path).with_context(|| format!("Creating {}", path.display()))?;
for idx in 0..COUNT {
let arr = shuffled_array::<u8, 256>()?;
write_slice(&mut file, &arr, format!("SHUFFLED_U8{idx}")).context("Writing data")?;
}
writeln!(&mut file, "static SHUFFLED_U8: &[&[u8]] = &[")?;
for idx in 0..COUNT {
writeln!(&mut file, " &SHUFFLED_U8{idx},")?;
}
writeln!(&mut file, "];")?;
writeln!(
&mut file,
"pub fn shuffled_u8(seed: usize) -> &'static [u8] {{"
)?;
writeln!(&mut file, " SHUFFLED_U8[seed % {COUNT}]")?;
writeln!(&mut file, "}}")?;
Ok(())
}
fn shuffled_array<T, const N: usize>() -> anyhow::Result<[T; N]>
where
T: Copy + Default + TryFrom<usize>,
<T as TryFrom<usize>>::Error: Error + Send + Sync + 'static,
{
let mut res = [Default::default(); N];
for idx in 0..res.len() {
res[idx] = idx
.try_into()
.with_context(|| format!("Converting {idx} to {}", type_name::<T>()))?;
}
res.shuffle(&mut thread_rng());
Ok(res)
}
fn write_slice<T>(writer: &mut impl Write, slice: &[T], name: impl Display) -> anyhow::Result<()>
where
T: Display,
{
write!(
writer,
"const {name}: [{}; {}] = [",
type_name::<T>(),
slice.len()
)?;
for data in slice.iter() {
write!(writer, "{data}, ")?;
}
writeln!(writer, "];")?;
Ok(())
}