1use bytes::Bytes;
2use std::fs::{self, File};
3use std::io::{self, BufWriter, Write};
4use std::path::{Path, PathBuf};
5
6pub fn write_byte_arrays(
7 storage_dir: &Path,
8 struct_output_path: &Path,
9 struct_name: &str,
10 byte_arrays: Vec<(&str, Bytes)>,
11) -> io::Result<()> {
12 fs::create_dir_all(storage_dir)?;
14
15 if let Some(parent_dir) = struct_output_path.parent() {
17 fs::create_dir_all(parent_dir)?;
18 }
19
20 let rs_file = File::create(struct_output_path)?;
22 let mut rs_writer = BufWriter::new(rs_file);
23
24 writeln!(
26 rs_writer,
27 "// Automatically generated file. Do not edit.\n\
28 // Generated by embed-bytes crate.\n"
29 )?;
30
31 writeln!(rs_writer, "pub struct {};", struct_name)?;
33 writeln!(rs_writer)?;
34
35 writeln!(rs_writer, "impl {} {{", struct_name)?;
37 writeln!(rs_writer)?;
38
39 for (field, content) in &byte_arrays {
41 let bin_filename = format!("{}.bin", field);
42 let bin_path = storage_dir.join(&bin_filename);
43
44 let mut bin_file = File::create(&bin_path)?;
46 bin_file.write_all(content)?;
47
48 let relative_path = pathdiff::diff_paths(&bin_path, struct_output_path.parent().unwrap())
50 .unwrap_or_else(|| bin_path.clone());
51
52 let relative_str = relative_path.to_str().unwrap();
54
55 writeln!(
57 rs_writer,
58 " pub const {}: &'static [u8] = include_bytes!(\"{}\");",
59 field,
60 relative_str
61 )?;
62 }
63
64 writeln!(rs_writer, "}}")?;
66
67 Ok(())
68}