Skip to main content

dvm_api/
guest_files.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5/// Non-UTF-8 file name or symlink target bytes carried as lowercase hex.
6#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(try_from = "String", into = "String")]
8#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
9#[cfg_attr(
10    feature = "typescript",
11    ts(type = "string", export_to = "controller-api.ts")
12)]
13pub struct FileName(Vec<u8>);
14
15impl AsRef<[u8]> for FileName {
16    fn as_ref(&self) -> &[u8] {
17        &self.0
18    }
19}
20
21impl From<Vec<u8>> for FileName {
22    fn from(bytes: Vec<u8>) -> Self {
23        Self(bytes)
24    }
25}
26
27impl From<&[u8]> for FileName {
28    fn from(bytes: &[u8]) -> Self {
29        Self(bytes.to_vec())
30    }
31}
32
33impl<const N: usize> From<&[u8; N]> for FileName {
34    fn from(bytes: &[u8; N]) -> Self {
35        Self(bytes.to_vec())
36    }
37}
38
39impl From<&str> for FileName {
40    fn from(text: &str) -> Self {
41        Self(text.as_bytes().to_vec())
42    }
43}
44
45impl TryFrom<String> for FileName {
46    type Error = &'static str;
47
48    fn try_from(hex: String) -> Result<Self, Self::Error> {
49        const REFUSAL: &str = "a file name is lowercase hex, two digits a byte";
50        let digit = |byte: u8| match byte {
51            b'0'..=b'9' => Ok(byte - b'0'),
52            b'a'..=b'f' => Ok(byte - b'a' + 10),
53            _ => Err(REFUSAL),
54        };
55        hex.as_bytes()
56            .chunks(2)
57            .map(|pair| match pair {
58                [high, low] => Ok(digit(*high)? << 4 | digit(*low)?),
59                _ => Err(REFUSAL),
60            })
61            .collect::<Result<_, _>>()
62            .map(Self)
63    }
64}
65
66impl From<FileName> for String {
67    fn from(name: FileName) -> Self {
68        name.0.iter().map(|byte| format!("{byte:02x}")).collect()
69    }
70}
71
72impl fmt::Debug for FileName {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "{:?}", self.0.escape_ascii().to_string())
75    }
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
81#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
82pub enum FileType {
83    Regular,
84    Directory,
85    Symlink,
86    Fifo,
87    Socket,
88    CharDevice,
89    BlockDevice,
90}
91
92#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
93#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
94#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
95pub struct PathDirectoryEntry {
96    pub name: String,
97    pub raw_name: FileName,
98    #[serde(rename = "type")]
99    pub kind: FileType,
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
103#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
104#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
105pub struct FileTime(pub i64, pub u32);
106
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
108#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
109#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
110pub struct FileStatus {
111    #[serde(rename = "type")]
112    pub kind: FileType,
113    pub mode: u32,
114    pub uid: u32,
115    pub gid: u32,
116    pub size: u64,
117    pub links: u64,
118    pub mtime: FileTime,
119    pub ctime: FileTime,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    #[cfg_attr(feature = "typescript", ts(optional))]
122    pub target: Option<FileName>,
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    #[cfg_attr(feature = "typescript", ts(optional))]
125    pub mount: Option<String>,
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn a_name_is_any_bytes_in_hex() {
134        let name = FileName::from(b"caf\xe9");
135        let written = serde_json::to_string(&name).unwrap();
136        assert_eq!(written, r#""636166e9""#);
137        assert_eq!(serde_json::from_str::<FileName>(&written).unwrap(), name);
138        for wrong in [r#""6""#, r#""6G""#, r#""4A""#] {
139            assert!(serde_json::from_str::<FileName>(wrong).is_err(), "{wrong}");
140        }
141    }
142
143    #[test]
144    fn file_status_and_path_entries_round_trip() {
145        let status: FileStatus = serde_json::from_str(
146            r#"{"type":"symlink","mode":511,"uid":0,"gid":0,"size":6,"links":1,"mtime":[1732400000,123456789],"ctime":[1732400000,123456789],"target":"2e2e2f6c6962"}"#,
147        )
148        .unwrap();
149        assert_eq!(status.kind, FileType::Symlink);
150        assert_eq!(status.target, Some(FileName::from("../lib")));
151        assert_eq!(status.mtime, FileTime(1_732_400_000, 123_456_789));
152        let mount: FileStatus = serde_json::from_str(
153            r#"{"type":"directory","mode":365,"uid":0,"gid":0,"size":0,"links":2,"mtime":[0,0],"ctime":[0,0],"mount":"proc"}"#,
154        )
155        .unwrap();
156        assert_eq!(mount.mount.as_deref(), Some("proc"));
157        let entry: PathDirectoryEntry =
158            serde_json::from_str(r#"{"name":"hosts","raw_name":"686f737473","type":"regular"}"#)
159                .unwrap();
160        assert_eq!(entry.raw_name, FileName::from("hosts"));
161    }
162}