Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions include_dir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: ?Sized>(T);

const __DATA: &'static __Aligned<[u8]> = &__Aligned(*include_bytes!($path));

&__DATA.0
}};
}

#[doc = include_str!("../README.md")]
#[allow(dead_code)]
fn check_readme_examples() {}
2 changes: 1 addition & 1 deletion macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down