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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
pub use phf;
use std::{
borrow::Cow,
path::{Component, Path},
};
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AssetKey(String);
impl From<AssetKey> for String {
fn from(key: AssetKey) -> Self {
key.0
}
}
impl AsRef<str> for AssetKey {
fn as_ref(&self) -> &str {
&self.0
}
}
impl<P: AsRef<Path>> From<P> for AssetKey {
fn from(path: P) -> Self {
let path = path.as_ref().to_owned();
let path = if path.has_root() {
path
} else {
Path::new(&Component::RootDir).join(path)
};
let buf = if cfg!(windows) {
let mut buf = String::new();
for component in path.components() {
match component {
Component::RootDir => buf.push('/'),
Component::CurDir => buf.push_str("./"),
Component::ParentDir => buf.push_str("../"),
Component::Prefix(prefix) => buf.push_str(&prefix.as_os_str().to_string_lossy()),
Component::Normal(s) => {
buf.push_str(&s.to_string_lossy());
buf.push('/')
}
}
}
if buf != "/" {
buf.pop();
}
buf
} else {
path.to_string_lossy().to_string()
};
AssetKey(buf)
}
}
pub trait Assets: Send + Sync + 'static {
fn get<Key: Into<AssetKey>>(&self, key: Key) -> Option<Cow<'_, [u8]>>;
}
pub struct EmbeddedAssets(phf::Map<&'static str, &'static [u8]>);
impl EmbeddedAssets {
pub const fn from_zstd(map: phf::Map<&'static str, &'static [u8]>) -> Self {
Self(map)
}
}
impl Assets for EmbeddedAssets {
fn get<Key: Into<AssetKey>>(&self, key: Key) -> Option<Cow<'_, [u8]>> {
self
.0
.get(key.into().as_ref())
.copied()
.map(zstd::decode_all)
.and_then(Result::ok)
.map(Cow::Owned)
}
}