rust_embed/
lib.rs

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