1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::prelude::http::Url;
use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, Serialize)]
pub struct AssetPath(Utf8PathBuf);
impl AssetPath {
pub fn local(&self, origin: Option<&Url>) -> Utf8PathBuf {
let mut components = Vec::new();
if let Some(origin) = origin {
if let Some(host) = origin.host_str() {
components.push(host);
}
let prefix = origin.path().trim_matches('/');
if !prefix.is_empty() {
components.push(prefix);
}
}
components.push(self.0.as_str());
let mut sep = [0u8; 4];
let sep = std::path::MAIN_SEPARATOR.encode_utf8(&mut sep);
let path = components.join(sep);
Utf8PathBuf::from(path)
}
pub fn remote(&self, origin: &Url) -> Url {
let prefix = origin.path().trim_end_matches('/');
let path = [prefix, self.0.as_str()].join("/");
let mut url = origin.clone();
url.set_path(&path);
url
}
}
impl AsRef<str> for AssetPath {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl FromStr for AssetPath {
type Err = <Utf8PathBuf as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Utf8PathBuf::from_str(s).map(Self)
}
}