include_dir/
file.rs

1use std::{
2    fmt::{self, Debug, Formatter},
3    path::Path,
4};
5
6/// A file with its contents stored in a `&'static [u8]`.
7#[derive(Clone, PartialEq, Eq)]
8pub struct File<'a> {
9    path: &'a str,
10    contents: &'a [u8],
11    #[cfg(feature = "metadata")]
12    metadata: Option<crate::Metadata>,
13}
14
15impl<'a> File<'a> {
16    /// Create a new [`File`].
17    pub const fn new(path: &'a str, contents: &'a [u8]) -> Self {
18        File {
19            path,
20            contents,
21            #[cfg(feature = "metadata")]
22            metadata: None,
23        }
24    }
25
26    /// The full path for this [`File`], relative to the directory passed to
27    /// [`crate::include_dir!()`].
28    pub fn path(&self) -> &'a Path {
29        Path::new(self.path)
30    }
31
32    /// The file's raw contents.
33    pub fn contents(&self) -> &[u8] {
34        self.contents
35    }
36
37    /// The file's contents interpreted as a string.
38    pub fn contents_utf8(&self) -> Option<&str> {
39        std::str::from_utf8(self.contents()).ok()
40    }
41}
42
43#[cfg(feature = "metadata")]
44impl<'a> File<'a> {
45    /// Set the [`Metadata`] associated with a [`File`].
46    pub const fn with_metadata(self, metadata: crate::Metadata) -> Self {
47        let File { path, contents, .. } = self;
48
49        File {
50            path,
51            contents,
52            metadata: Some(metadata),
53        }
54    }
55
56    /// Get the [`File`]'s [`Metadata`], if available.
57    pub fn metadata(&self) -> Option<&crate::Metadata> {
58        self.metadata.as_ref()
59    }
60}
61
62impl<'a> Debug for File<'a> {
63    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
64        let File {
65            path,
66            contents,
67            #[cfg(feature = "metadata")]
68            metadata,
69        } = self;
70
71        let mut d = f.debug_struct("File");
72
73        d.field("path", path)
74            .field("contents", &format!("<{} bytes>", contents.len()));
75
76        #[cfg(feature = "metadata")]
77        d.field("metadata", metadata);
78
79        d.finish()
80    }
81}