| Crates.io | embed-bytes |
| lib.rs | embed-bytes |
| version | 0.1.0-alpha6 |
| created_at | 2025-01-26 05:09:20.412973+00 |
| updated_at | 2025-02-23 03:58:16.564129+00 |
| description | A simple Rust crate to embed assets. |
| homepage | |
| repository | https://github.com/jzombie/rust-embed-bytes |
| max_upload_size | |
| id | 1531057 |
| size | 9,190 |
This is a prototype; the documentation may not be correct, and the API is subject to change.
embed-bytes is a Rust crate that simplifies embedding low-level binary arrays and assets in other Rust programs. It relies only on the bytes crate for efficient handling of these assets.
When used in a build.rs script, embed-bytes operates as a zero-cost abstraction, as all processing occurs at compile-time. The embedding directory is automatically created during the build process, where asset names are converted into .bin files, and a Rust source file is generated to include these assets using include_bytes!.
The write_byte_arrays function makes it easy to embed byte arrays into your Rust project. It generates .bin files for each byte array and creates a corresponding .rs file with include_bytes! references for seamless integration.
use bytes::Bytes;
use std::path::Path;
use build_resource_byte_arrays::write_byte_arrays;
fn main() -> std::io::Result<()> {
// 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)?;
println!("Byte arrays written to 'embed/' and Rust file 'embed.rs' generated.");
Ok(())
}
If the output directory is specified as embed, the following files will be created:
embed/
├── ARRAY_ONE.bin
├── ARRAY_TWO.bin
embed.rs
The embed.rs file will look like this:
// Automatically generated file. Do not edit.
// Generated by embed-bytes crate.
pub static ARRAY_ONE: &[u8] = include_bytes!("embed/ARRAY_ONE.bin");
pub static ARRAY_TWO: &[u8] = include_bytes!("embed/ARRAY_TWO.bin");
embed directory if it does not already exist..rs file is valid in Rust..rs file, include it in your project with a mod statement:
mod embed;
use embed::{ARRAY_ONE, ARRAY_TWO};
fn main() {
println!("ARRAY_ONE: {:?}", ARRAY_ONE);
println!("ARRAY_TWO: {:?}", ARRAY_TWO);
}
The function will return an error if:
The specified directory name is invalid (e.g., starts with a digit).
A file operation (e.g., creating or writing files) fails.
embed-resourcesIf your use case involves embedding files, content from URLs, or arbitrary data with optional compression, consider using the embed-resources crate. It provides a higher-level API for handling such scenarios, building on the functionality offered by this crate.
For example:
Check out the embed-resources crate for more advanced embedding functionality.
MIT License (c) 2025 Jeremy Harris.