Skip to main content

trillium_static_compiled/
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, Copy, PartialEq, Eq)]
8pub struct File {
9    path: &'static str,
10    contents: &'static [u8],
11    metadata: Option<crate::Metadata>,
12}
13
14impl File {
15    /// Create a new [`File`].
16    pub const fn new(path: &'static str, contents: &'static [u8]) -> Self {
17        File {
18            path,
19            contents,
20            metadata: None,
21        }
22    }
23
24    /// The full path for this [`File`], relative to the directory passed to
25    /// [`crate::include_dir!()`].
26    pub fn path(&self) -> &'static Path {
27        Path::new(self.path)
28    }
29
30    /// The file's raw contents.
31    pub fn contents(&self) -> &'static [u8] {
32        self.contents
33    }
34
35    /// The file's contents interpreted as a string.
36    pub fn contents_utf8(&self) -> Option<&'static str> {
37        std::str::from_utf8(self.contents()).ok()
38    }
39
40    /// Set the [`Metadata`] associated with a [`File`].
41    pub const fn with_metadata(self, metadata: crate::Metadata) -> Self {
42        let File { path, contents, .. } = self;
43
44        File {
45            path,
46            contents,
47            metadata: Some(metadata),
48        }
49    }
50
51    /// Get the [`File`]'s [`Metadata`], if available.
52    pub fn metadata(&self) -> Option<&crate::Metadata> {
53        self.metadata.as_ref()
54    }
55}
56
57impl Debug for File {
58    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59        f.debug_struct("File")
60            .field("path", &self.path)
61            .field("contents", &format_args!("<{} bytes>", self.contents.len()))
62            .field("metadata", &self.metadata)
63            .finish()
64    }
65}