embed_bytes/
lib.rs

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    // Ensure the storage directory exists.
13    fs::create_dir_all(storage_dir)?;
14
15    // Ensure the directory of the struct output path exists.
16    if let Some(parent_dir) = struct_output_path.parent() {
17        fs::create_dir_all(parent_dir)?;
18    }
19
20    // Open the Rust file for writing.
21    let rs_file = File::create(struct_output_path)?;
22    let mut rs_writer = BufWriter::new(rs_file);
23
24    // Write header comments.
25    writeln!(
26        rs_writer,
27        "// Automatically generated file. Do not edit.\n\
28         // Generated by embed-bytes crate.\n"
29    )?;
30
31    // Write the struct definition.
32    writeln!(rs_writer, "pub struct {};", struct_name)?;
33    writeln!(rs_writer)?;
34
35    // Write the impl block where constants are defined.
36    writeln!(rs_writer, "impl {} {{", struct_name)?;
37    writeln!(rs_writer)?;
38
39    // Process each byte array.
40    for (field, content) in &byte_arrays {
41        let bin_filename = format!("{}.bin", field);
42        let bin_path = storage_dir.join(&bin_filename);
43
44        // Write the binary file to the storage directory.
45        let mut bin_file = File::create(&bin_path)?;
46        bin_file.write_all(content)?;
47
48        // Calculate the relative path from struct output directory to binary file
49        let relative_path = pathdiff::diff_paths(&bin_path, struct_output_path.parent().unwrap())
50            .unwrap_or_else(|| bin_path.clone());
51
52        // Convert the relative path to a string for include_bytes!
53        let relative_str = relative_path.to_str().unwrap();
54
55        // Write the associated constant with the correct relative path
56        writeln!(
57            rs_writer,
58            "    pub const {}: &'static [u8] = include_bytes!(\"{}\");",
59            field,
60            relative_str
61        )?;
62    }
63
64    // Write the closing brace for the impl block.
65    writeln!(rs_writer, "}}")?;
66
67    Ok(())
68}