embed_bytes

Function write_byte_arrays

Source
pub fn write_byte_arrays(
    index_output_path: &Path,
    byte_arrays: Vec<(&str, Bytes)>,
) -> Result<()>
Expand description

Writes byte arrays to separate .bin files in a specified directory and generates a .rs file adjacent to the directory. The .rs file uses include_bytes! to reference the .bin files.

§Arguments

  • index_output_path - The path to the directory where the .bin files will be saved. This directory must exist or will be created by the function.
  • byte_arrays - A vector of tuples (name, content), where:
    • name is the name of the static variable to be generated in the .rs file.
    • content is a Bytes object containing the binary data.

§Behavior

  1. Ensures the index_output_path exists or creates it if it does not.
  2. For each entry in byte_arrays, writes the binary data to a .bin file inside the specified directory.
  3. Generates a .rs file adjacent to the directory. The .rs file includes static variable declarations that use include_bytes! to reference the corresponding .bin files.

§Errors

Returns an io::Error if:

  • The specified index_output_path is not a directory.
  • A file operation (e.g., creating or writing files) fails.

§Example

use bytes::Bytes;
use std::path::Path;
use your_crate::write_byte_arrays;

// Define the output directory
let output_dir = Path::new("embed");

// Define the byte arrays to write
let byte_arrays = vec![
    ("ARRAY_ONE", Bytes::from(vec![1, 2, 3, 4])),
    ("ARRAY_TWO", Bytes::from(vec![5, 6, 7, 8])),
];

// Write the byte arrays and generate the Rust file
write_byte_arrays(output_dir, byte_arrays).unwrap();

§Output

If index_output_path is embed, the following structure will be created:

embed/
├── ARRAY_ONE.bin
├── ARRAY_TWO.bin
embed.rs

The content of embed.rs will look like:

// Automatically generated file. Do not edit.
// Generated by build-resource-byte-arrays crate.

pub static ARRAY_ONE: &[u8] = include_bytes!("embed/ARRAY_ONE.bin");
pub static ARRAY_TWO: &[u8] = include_bytes!("embed/ARRAY_TWO.bin");