diff --git a/include_dir/Cargo.toml b/include_dir/Cargo.toml index c4ecd8de60..a684517985 100644 --- a/include_dir/Cargo.toml +++ b/include_dir/Cargo.toml @@ -14,6 +14,7 @@ rust-version = "1.56" [dependencies] glob = { version = "0.3", optional = true } include_dir_macros = { version = "^0.7.0", path = "../macros" } +lz4-compression = "0.7.0" [dev-dependencies] tempfile = "3" @@ -22,6 +23,7 @@ tempfile = "3" default = [] nightly = ["include_dir_macros/nightly"] metadata = ["include_dir_macros/metadata"] +compress = ["include_dir_macros/compress"] [package.metadata.docs.rs] all-features = true diff --git a/include_dir/src/file.rs b/include_dir/src/file.rs index 3ccfc930b9..b15d782d97 100644 --- a/include_dir/src/file.rs +++ b/include_dir/src/file.rs @@ -3,6 +3,9 @@ use std::{ path::Path, }; +#[cfg(feature = "compress")] +use lz4_compression::decompress::decompress; + /// A file with its contents stored in a `&'static [u8]`. #[derive(Clone, PartialEq, Eq)] pub struct File<'a> { @@ -30,14 +33,28 @@ impl<'a> File<'a> { } /// The file's raw contents. + #[cfg(not(feature = "compress"))] pub fn contents(&self) -> &[u8] { self.contents } + /// The file's uncompressed raw contents. + #[cfg(feature = "compress")] + pub fn contents(&self) -> Vec { + decompress(self.contents).expect("Embeded file could not be decompressed") + } + /// The file's contents interpreted as a string. + #[cfg(not(feature = "compress"))] pub fn contents_utf8(&self) -> Option<&str> { std::str::from_utf8(self.contents()).ok() } + + /// The file's uncompressed contents interpreted as a string. + #[cfg(feature = "compress")] + pub fn contents_utf8(&self) -> Option { + String::from_utf8(self.contents()).ok() + } } #[cfg(feature = "metadata")] diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 663a80cea2..f17bc1422b 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -16,7 +16,9 @@ proc-macro = true [dependencies] proc-macro2 = "1" quote = "1" +lz4-compression = "0.7.0" [features] nightly = [] metadata = [] +compress = [] diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 1b36839987..a10d092c77 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -13,6 +13,9 @@ use std::{ time::SystemTime, }; +#[cfg(feature = "compress")] +use lz4_compression::compress::compress; + /// Embed the contents of a directory in your crate. #[proc_macro] pub fn include_dir(input: TokenStream) -> TokenStream { @@ -76,6 +79,10 @@ fn expand_dir(root: &Path, path: &Path) -> proc_macro2::TokenStream { fn expand_file(root: &Path, path: &Path) -> proc_macro2::TokenStream { let contents = read_file(path); + + #[cfg(feature = "compress")] + let contents = compress(&contents); + let literal = Literal::byte_string(&contents); let normalized_path = normalize_path(root, path);