Skip to main content

ic_asset_certification/
asset.rs

1use std::borrow::Cow;
2
3/// An asset to be certified and served by an [AssetRouter](crate::AssetRouter).
4///
5/// Use the [new](Asset::new) associated function to create instances of
6/// this struct.
7///
8/// # Examples
9///
10/// ## With owned values
11///
12/// ```
13/// use ic_asset_certification::Asset;
14///
15/// let path = String::from("foo");
16/// let content = vec![1, 2, 3];
17///
18/// let asset = Asset::new(path, content);
19/// ```
20///
21/// ## With borrowed values
22///
23/// ```
24/// use ic_asset_certification::Asset;
25///
26/// let path = "foo";
27/// let content = [1, 2, 3].as_slice();
28///
29/// let asset = Asset::new(path, content);
30/// ```
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Asset<'content, 'path> {
33    pub(crate) path: Cow<'path, str>,
34    pub(crate) url: Cow<'path, str>,
35    pub(crate) content: Cow<'content, [u8]>,
36}
37
38impl<'content, 'path> Asset<'content, 'path> {
39    /// Creates a new asset with the given path and content.
40    /// Both parameters may be owned values, or references so developers are free to
41    /// choose whichever option is best suited for their use case.
42    pub fn new(path: impl Into<Cow<'path, str>>, content: impl Into<Cow<'content, [u8]>>) -> Self {
43        let path = path.into();
44
45        Asset {
46            url: Cow::Owned(path_to_url(path.as_ref())),
47            path,
48            content: content.into(),
49        }
50    }
51}
52
53fn path_to_url(path: &str) -> String {
54    if !path.starts_with('/') {
55        format!("/{path}")
56    } else {
57        path.to_string()
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use rstest::*;
65
66    #[rstest]
67    fn asset_new_owned_values() {
68        let path = String::from("foo");
69        let content = vec![1, 2, 3];
70
71        let asset = Asset::new(path.clone(), content.clone());
72
73        assert_eq!(asset.path, path);
74        assert_eq!(asset.url, "/foo");
75        assert_eq!(asset.content, content);
76    }
77
78    #[rstest]
79    fn asset_new_borrowed_values() {
80        let path = "foo";
81        let content = [1, 2, 3].as_slice();
82
83        let asset = Asset::new(path, content);
84
85        assert_eq!(asset.path, path);
86        assert_eq!(asset.url, "/foo");
87        assert_eq!(asset.content, content);
88    }
89}