embed-bytes (Work in Progress)
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!.
Usage Example
Writing Byte Arrays to Files and Generating a Rust File
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.
Example
use Bytes;
use Path;
use write_byte_arrays;
Output
If the output directory is specified as embed, the following files will be created:
embed/
├── ARRAY_ONE.bin
├── ARRAY_TWO.bin
embed.rs
Generated Rust File
The embed.rs file will look like this:
// Automatically generated file. Do not edit.
// Generated by embed-bytes crate.
pub static ARRAY_ONE: & = include_bytes!;
pub static ARRAY_TWO: & = include_bytes!;
Notes
- The function will create the
embeddirectory if it does not already exist. - It will sanitize invalid characters in the directory name to ensure the generated
.rsfile is valid in Rust. - To use the generated
.rsfile, include it in your project with amodstatement:use ;
Error Handling
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.
Related
Related Crate: embed-resources
If 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:
- Embedding files from a directory.
- Fetching and embedding content from URLs.
- Compressing the data before embedding it.
Check out the embed-resources crate for more advanced embedding functionality.
Other Related
- https://stackoverflow.com/questions/75676449/how-to-build-and-publish-a-crate-containing-generated-code
- https://github.com/rust-lang/cargo/issues/12456
- https://github.com/rust-lang/cargo/issues/9398
- https://github.com/pyrossh/rust-embed
License
MIT License (c) 2025 Jeremy Harris.