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