From ad567792945dbf6341fb0c3b0a1121332d67528f Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Mon, 27 Oct 2025 19:38:00 +0000 Subject: [PATCH] Align bytes by 8 --- include_dir/src/lib.rs | 26 ++++++++++++++++++++++++++ macros/src/lib.rs | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/include_dir/src/lib.rs b/include_dir/src/lib.rs index b9380b931c..e931431680 100644 --- a/include_dir/src/lib.rs +++ b/include_dir/src/lib.rs @@ -106,6 +106,32 @@ pub use crate::metadata::Metadata; pub use crate::{dir::Dir, dir_entry::DirEntry, file::File}; pub use include_dir_macros::include_dir; +/// A simple macro that embeds the bytes of an external file into the executable and +/// guarantees that they are aligned. +/// +/// # Usage +/// +/// `include_bytes_aligned!(ALIGNMENT, PATH)` +/// +/// Where `ALIGNMENT` is any integer literal (must be a power of 2), and PATH is a string literal path +/// to the file to include, just as in [`include_bytes!`](std::include_bytes). +/// +/// # Efficiency +/// +/// This macro does not copy the bytes or duplicate them. Takes up the same amount of space in memory +/// as the usual [`include_bytes!`](std::include_bytes). +#[macro_export] +macro_rules! include_bytes_aligned { + ($align_to:expr, $path:expr) => {{ + #[repr(C, align($align_to))] + struct __Aligned(T); + + const __DATA: &'static __Aligned<[u8]> = &__Aligned(*include_bytes!($path)); + + &__DATA.0 + }}; +} + #[doc = include_str!("../README.md")] #[allow(dead_code)] fn check_readme_examples() {} diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 4a881f029b..9847f60e59 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -82,7 +82,7 @@ fn expand_file(root: &Path, path: &Path) -> proc_macro2::TokenStream { .canonicalize() .unwrap_or_else(|e| panic!("failed to resolve \"{}\": {}", path.display(), e)); let literal = match abs.to_str() { - Some(abs) => quote!(include_bytes!(#abs)), + Some(abs) => quote!(::include_dir::include_bytes_aligned!(8, #abs)), None => { let contents = read_file(path); let literal = Literal::byte_string(&contents);