1use std::collections::HashMap;
10use std::fmt;
11
12#[derive(Debug, Clone, PartialEq)]
14pub enum Value {
15 Byte(u8),
16 Bool(bool),
17 Int16(i16),
18 Uint16(u16),
19 Int32(i32),
20 Uint32(u32),
21 Int64(i64),
22 Uint64(u64),
23 Double(f64),
24 Str(String),
26 ObjectPath(String),
28 Signature(String),
30 UnixFd(u32),
32 Array {
35 element: String,
36 items: Vec<Value>,
37 },
38 Struct(Vec<Value>),
40 Variant(Box<Value>),
42 DictEntry(Box<Value>, Box<Value>),
44}
45
46impl Value {
47 pub fn signature(&self) -> String {
49 match self {
50 Self::Byte(_) => "y".into(),
51 Self::Bool(_) => "b".into(),
52 Self::Int16(_) => "n".into(),
53 Self::Uint16(_) => "q".into(),
54 Self::Int32(_) => "i".into(),
55 Self::Uint32(_) => "u".into(),
56 Self::Int64(_) => "x".into(),
57 Self::Uint64(_) => "t".into(),
58 Self::Double(_) => "d".into(),
59 Self::Str(_) => "s".into(),
60 Self::ObjectPath(_) => "o".into(),
61 Self::Signature(_) => "g".into(),
62 Self::UnixFd(_) => "h".into(),
63 Self::Array { element, .. } => format!("a{element}"),
64 Self::Struct(fields) => {
65 let inner: String = fields.iter().map(Self::signature).collect();
66 format!("({inner})")
67 }
68 Self::Variant(_) => "v".into(),
69 Self::DictEntry(k, v) => format!("{{{}{}}}", k.signature(), v.signature()),
70 }
71 }
72
73 pub fn dict(entries: impl IntoIterator<Item = (String, Value)>) -> Self {
75 Self::Array {
76 element: "{sv}".into(),
77 items: entries
78 .into_iter()
79 .map(|(k, v)| {
80 Value::DictEntry(
81 Box::new(Value::Str(k)),
82 Box::new(Value::Variant(Box::new(v))),
83 )
84 })
85 .collect(),
86 }
87 }
88
89 pub fn string_array(items: impl IntoIterator<Item = String>) -> Self {
91 Self::Array {
92 element: "s".into(),
93 items: items.into_iter().map(Value::Str).collect(),
94 }
95 }
96
97 pub fn bytes(data: &[u8]) -> Self {
99 Self::Array {
100 element: "y".into(),
101 items: data.iter().copied().map(Value::Byte).collect(),
102 }
103 }
104
105 pub fn peel(&self) -> &Value {
112 match self {
113 Self::Variant(inner) => inner.peel(),
114 other => other,
115 }
116 }
117
118 pub fn as_str(&self) -> Option<&str> {
119 match self.peel() {
120 Self::Str(s) | Self::ObjectPath(s) | Self::Signature(s) => Some(s),
121 _ => None,
122 }
123 }
124
125 pub fn as_bool(&self) -> Option<bool> {
126 match self.peel() {
127 Self::Bool(b) => Some(*b),
128 _ => None,
129 }
130 }
131
132 pub fn as_u64(&self) -> Option<u64> {
133 match self.peel() {
134 Self::Byte(v) => Some(*v as u64),
135 Self::Uint16(v) => Some(*v as u64),
136 Self::Uint32(v) => Some(*v as u64),
137 Self::Uint64(v) => Some(*v),
138 Self::UnixFd(v) => Some(*v as u64),
139 _ => None,
140 }
141 }
142
143 pub fn as_i64(&self) -> Option<i64> {
144 match self.peel() {
145 Self::Byte(v) => Some(*v as i64),
146 Self::Int16(v) => Some(*v as i64),
147 Self::Uint16(v) => Some(*v as i64),
148 Self::Int32(v) => Some(*v as i64),
149 Self::Uint32(v) => Some(*v as i64),
150 Self::Int64(v) => Some(*v),
151 _ => None,
152 }
153 }
154
155 pub fn as_array(&self) -> Option<&[Value]> {
156 match self.peel() {
157 Self::Array { items, .. } => Some(items),
158 Self::Struct(fields) => Some(fields),
159 _ => None,
160 }
161 }
162
163 pub fn as_bytes(&self) -> Option<Vec<u8>> {
165 let items = self.as_array()?;
166 items
167 .iter()
168 .map(|v| match v.peel() {
169 Self::Byte(b) => Some(*b),
170 _ => None,
171 })
172 .collect()
173 }
174
175 pub fn as_strings(&self) -> Vec<String> {
177 self.as_array()
178 .map(|items| {
179 items
180 .iter()
181 .filter_map(|v| v.as_str().map(str::to_owned))
182 .collect()
183 })
184 .unwrap_or_default()
185 }
186
187 pub fn as_map(&self) -> HashMap<String, Value> {
189 let mut out = HashMap::new();
190 if let Some(items) = self.as_array() {
191 for item in items {
192 if let Self::DictEntry(k, v) = item.peel() {
193 if let Some(key) = k.as_str() {
194 out.insert(key.to_owned(), (**v).clone());
195 }
196 }
197 }
198 }
199 out
200 }
201
202 pub fn get(&self, key: &str) -> Option<Value> {
204 if let Some(items) = self.as_array() {
205 for item in items {
206 if let Self::DictEntry(k, v) = item.peel() {
207 if k.as_str() == Some(key) {
208 return Some((**v).clone());
209 }
210 }
211 }
212 }
213 None
214 }
215}
216
217impl fmt::Display for Value {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 match self {
220 Self::Str(s) | Self::ObjectPath(s) | Self::Signature(s) => write!(f, "{s}"),
221 Self::Variant(v) => write!(f, "{v}"),
222 other => write!(f, "{other:?}"),
223 }
224 }
225}
226
227pub fn alignment(code: u8) -> usize {
235 match code {
236 b'y' | b'g' | b'v' => 1,
237 b'n' | b'q' => 2,
238 b'b' | b'i' | b'u' | b's' | b'o' | b'a' | b'h' => 4,
239 b'x' | b't' | b'd' | b'(' | b')' | b'{' | b'}' | b'r' | b'e' => 8,
240 _ => 1,
241 }
242}
243
244pub fn complete_types(signature: &str) -> Vec<String> {
249 let bytes = signature.as_bytes();
250 let mut out = Vec::new();
251 let mut i = 0;
252 while i < bytes.len() {
253 let len = match type_length(&bytes[i..]) {
254 Some(n) => n,
255 None => break,
256 };
257 out.push(signature[i..i + len].to_string());
258 i += len;
259 }
260 out
261}
262
263pub fn type_length(signature: &[u8]) -> Option<usize> {
265 let first = *signature.first()?;
266 match first {
267 b'a' => Some(1 + type_length(&signature[1..])?),
269 b'(' | b'{' => {
271 let (open, close) = if first == b'(' {
272 (b'(', b')')
273 } else {
274 (b'{', b'}')
275 };
276 let mut depth = 0usize;
277 for (i, &c) in signature.iter().enumerate() {
278 if c == open {
279 depth += 1;
280 } else if c == close {
281 depth -= 1;
282 if depth == 0 {
283 return Some(i + 1);
284 }
285 }
286 }
287 None
288 }
289 _ => Some(1),
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn signatures_round_trip_through_values() {
299 assert_eq!(Value::Str("x".into()).signature(), "s");
300 assert_eq!(Value::bytes(&[1, 2]).signature(), "ay");
301 assert_eq!(Value::string_array(["a".into()]).signature(), "as");
302 assert_eq!(
303 Value::dict([("k".into(), Value::Uint32(1))]).signature(),
304 "a{sv}"
305 );
306 assert_eq!(
307 Value::Struct(vec![Value::Str("a".into()), Value::Uint32(2)]).signature(),
308 "(su)"
309 );
310 assert_eq!(Value::UnixFd(3).as_u64(), Some(3));
311 }
312
313 #[test]
314 fn complete_types_splits_concatenations() {
315 assert_eq!(complete_types("sa{sv}u"), vec!["s", "a{sv}", "u"]);
316 assert_eq!(complete_types("ay"), vec!["ay"]);
317 assert_eq!(complete_types(""), Vec::<String>::new());
318 assert_eq!(complete_types("a{oa{sa{sv}}}"), vec!["a{oa{sa{sv}}}"]);
320 assert_eq!(complete_types("(is)(bb)"), vec!["(is)", "(bb)"]);
321 }
322
323 #[test]
324 fn nested_brackets_are_balanced_not_counted() {
325 assert_eq!(type_length(b"a{sa{sv}}"), Some(9));
326 assert_eq!(type_length(b"((ii)(ss))x"), Some(10));
327 assert_eq!(type_length(b"(is"), None);
329 assert_eq!(type_length(b""), None);
330 }
331
332 #[test]
333 fn alignments_match_the_specification() {
334 for (code, want) in [
335 (b'y', 1),
336 (b'b', 4),
337 (b'n', 2),
338 (b'q', 2),
339 (b'i', 4),
340 (b'u', 4),
341 (b'x', 8),
342 (b't', 8),
343 (b'd', 8),
344 (b's', 4),
345 (b'o', 4),
346 (b'g', 1),
347 (b'a', 4),
348 (b'(', 8),
349 (b'{', 8),
350 (b'v', 1),
351 (b'h', 4),
352 ] {
353 assert_eq!(alignment(code), want, "alignment of {}", code as char);
354 }
355 }
356
357 #[test]
358 fn accessors_peel_variants() {
359 let wrapped = Value::Variant(Box::new(Value::Str("Pixel".into())));
361 assert_eq!(wrapped.as_str(), Some("Pixel"));
362
363 let nested = Value::Variant(Box::new(Value::Variant(Box::new(Value::Bool(true)))));
364 assert_eq!(nested.as_bool(), Some(true));
365
366 let map = Value::dict([("Name".into(), Value::Str("Pixel".into()))]);
367 assert_eq!(map.get("Name").unwrap().as_str(), Some("Pixel"));
368 assert_eq!(map.get("Missing"), None);
369 }
370
371 #[test]
372 fn byte_arrays_collect() {
373 let v = Value::bytes(&[0xDE, 0xAD]);
374 assert_eq!(v.as_bytes(), Some(vec![0xDE, 0xAD]));
375 assert_eq!(Value::string_array(["a".into()]).as_bytes(), None);
377 }
378}