Skip to main content

embed/
embed.rs

1#![forbid(unsafe_code)]
2#[cfg(feature = "compression")]
3#[cfg_attr(feature = "compression", doc(hidden))]
4pub use include_flate::flate;
5
6#[allow(unused_imports)]
7#[macro_use]
8extern crate embed_impl;
9pub use embed_impl::*;
10pub use embed_utils::{EmbeddedFile, Metadata};
11
12#[doc(hidden)]
13pub extern crate embed_utils as utils;
14
15/// A directory of binary assets.
16///
17/// The files in the specified folder will be embedded into the executable in
18/// release builds. Debug builds will read the data from the file system at
19/// runtime.
20///
21/// This trait is meant to be derived like so:
22/// ```
23/// use embed::Embed;
24///
25/// #[derive(Embed)]
26/// #[folder = "examples/public/"]
27/// struct Asset;
28///
29/// fn main() {}
30/// ```
31pub trait RustEmbed {
32    /// Get an embedded file and its metadata.
33    ///
34    /// If the feature `debug-embed` is enabled or the binary was compiled in
35    /// release mode, the file information is embedded in the binary and the file
36    /// data is returned as a `Cow::Borrowed(&'static [u8])`.
37    ///
38    /// Otherwise, the information is read from the file system on each call and
39    /// the file data is returned as a `Cow::Owned(Vec<u8>)`.
40    fn get(file_path: &str) -> Option<EmbeddedFile>;
41
42    /// Iterates over the file paths in the folder.
43    ///
44    /// If the feature `debug-embed` is enabled or the binary is compiled in
45    /// release mode, a static array containing the list of relative file paths
46    /// is used.
47    ///
48    /// Otherwise, the files are listed from the file system on each call.
49    fn iter() -> Filenames;
50}
51
52pub use RustEmbed as Embed;
53
54/// An iterator over filenames.
55///
56/// This enum exists for optimization purposes, to avoid boxing the iterator in
57/// some cases. Do not try and match on it, as different variants will exist
58/// depending on the compilation context.
59pub enum Filenames {
60    /// Release builds use a named iterator type, which can be stack-allocated.
61    #[cfg(any(not(debug_assertions), feature = "debug-embed"))]
62    Embedded(std::slice::Iter<'static, &'static str>),
63
64    /// The debug iterator type is currently unnameable and still needs to be
65    /// boxed.
66    #[cfg(all(debug_assertions, not(feature = "debug-embed")))]
67    Dynamic(Box<dyn Iterator<Item = std::borrow::Cow<'static, str>>>),
68}
69
70impl Iterator for Filenames {
71    type Item = std::borrow::Cow<'static, str>;
72    fn next(&mut self) -> Option<Self::Item> {
73        match self {
74            #[cfg(any(not(debug_assertions), feature = "debug-embed"))]
75            Filenames::Embedded(names) => names.next().map(|x| std::borrow::Cow::from(*x)),
76
77            #[cfg(all(debug_assertions, not(feature = "debug-embed")))]
78            Filenames::Dynamic(boxed) => boxed.next(),
79        }
80    }
81}