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 _ => None,
139 }
140 }
141
142 pub fn as_i64(&self) -> Option<i64> {
143 match self.peel() {
144 Self::Byte(v) => Some(*v as i64),
145 Self::Int16(v) => Some(*v as i64),
146 Self::Uint16(v) => Some(*v as i64),
147 Self::Int32(v) => Some(*v as i64),
148 Self::Uint32(v) => Some(*v as i64),
149 Self::Int64(v) => Some(*v),
150 _ => None,
151 }
152 }
153
154 pub fn as_array(&self) -> Option<&[Value]> {
155 match self.peel() {
156 Self::Array { items, .. } => Some(items),
157 Self::Struct(fields) => Some(fields),
158 _ => None,
159 }
160 }
161
162 pub fn as_bytes(&self) -> Option<Vec<u8>> {
164 let items = self.as_array()?;
165 items
166 .iter()
167 .map(|v| match v.peel() {
168 Self::Byte(b) => Some(*b),
169 _ => None,
170 })
171 .collect()
172 }
173
174 pub fn as_strings(&self) -> Vec<String> {
176 self.as_array()
177 .map(|items| {
178 items
179 .iter()
180 .filter_map(|v| v.as_str().map(str::to_owned))
181 .collect()
182 })
183 .unwrap_or_default()
184 }
185
186 pub fn as_map(&self) -> HashMap<String, Value> {
188 let mut out = HashMap::new();
189 if let Some(items) = self.as_array() {
190 for item in items {
191 if let Self::DictEntry(k, v) = item.peel() {
192 if let Some(key) = k.as_str() {
193 out.insert(key.to_owned(), (**v).clone());
194 }
195 }
196 }
197 }
198 out
199 }
200
201 pub fn get(&self, key: &str) -> Option<Value> {
203 if let Some(items) = self.as_array() {
204 for item in items {
205 if let Self::DictEntry(k, v) = item.peel() {
206 if k.as_str() == Some(key) {
207 return Some((**v).clone());
208 }
209 }
210 }
211 }
212 None
213 }
214}
215
216impl fmt::Display for Value {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 match self {
219 Self::Str(s) | Self::ObjectPath(s) | Self::Signature(s) => write!(f, "{s}"),
220 Self::Variant(v) => write!(f, "{v}"),
221 other => write!(f, "{other:?}"),
222 }
223 }
224}
225
226pub fn alignment(code: u8) -> usize {
234 match code {
235 b'y' | b'g' | b'v' => 1,
236 b'n' | b'q' => 2,
237 b'b' | b'i' | b'u' | b's' | b'o' | b'a' | b'h' => 4,
238 b'x' | b't' | b'd' | b'(' | b')' | b'{' | b'}' | b'r' | b'e' => 8,
239 _ => 1,
240 }
241}
242
243pub fn complete_types(signature: &str) -> Vec<String> {
248 let bytes = signature.as_bytes();
249 let mut out = Vec::new();
250 let mut i = 0;
251 while i < bytes.len() {
252 let len = match type_length(&bytes[i..]) {
253 Some(n) => n,
254 None => break,
255 };
256 out.push(signature[i..i + len].to_string());
257 i += len;
258 }
259 out
260}
261
262pub fn type_length(signature: &[u8]) -> Option<usize> {
264 let first = *signature.first()?;
265 match first {
266 b'a' => Some(1 + type_length(&signature[1..])?),
268 b'(' | b'{' => {
270 let (open, close) = if first == b'(' {
271 (b'(', b')')
272 } else {
273 (b'{', b'}')
274 };
275 let mut depth = 0usize;
276 for (i, &c) in signature.iter().enumerate() {
277 if c == open {
278 depth += 1;
279 } else if c == close {
280 depth -= 1;
281 if depth == 0 {
282 return Some(i + 1);
283 }
284 }
285 }
286 None
287 }
288 _ => Some(1),
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 #[test]
297 fn signatures_round_trip_through_values() {
298 assert_eq!(Value::Str("x".into()).signature(), "s");
299 assert_eq!(Value::bytes(&[1, 2]).signature(), "ay");
300 assert_eq!(Value::string_array(["a".into()]).signature(), "as");
301 assert_eq!(
302 Value::dict([("k".into(), Value::Uint32(1))]).signature(),
303 "a{sv}"
304 );
305 assert_eq!(
306 Value::Struct(vec![Value::Str("a".into()), Value::Uint32(2)]).signature(),
307 "(su)"
308 );
309 }
310
311 #[test]
312 fn complete_types_splits_concatenations() {
313 assert_eq!(complete_types("sa{sv}u"), vec!["s", "a{sv}", "u"]);
314 assert_eq!(complete_types("ay"), vec!["ay"]);
315 assert_eq!(complete_types(""), Vec::<String>::new());
316 assert_eq!(complete_types("a{oa{sa{sv}}}"), vec!["a{oa{sa{sv}}}"]);
318 assert_eq!(complete_types("(is)(bb)"), vec!["(is)", "(bb)"]);
319 }
320
321 #[test]
322 fn nested_brackets_are_balanced_not_counted() {
323 assert_eq!(type_length(b"a{sa{sv}}"), Some(9));
324 assert_eq!(type_length(b"((ii)(ss))x"), Some(10));
325 assert_eq!(type_length(b"(is"), None);
327 assert_eq!(type_length(b""), None);
328 }
329
330 #[test]
331 fn alignments_match_the_specification() {
332 for (code, want) in [
333 (b'y', 1),
334 (b'b', 4),
335 (b'n', 2),
336 (b'q', 2),
337 (b'i', 4),
338 (b'u', 4),
339 (b'x', 8),
340 (b't', 8),
341 (b'd', 8),
342 (b's', 4),
343 (b'o', 4),
344 (b'g', 1),
345 (b'a', 4),
346 (b'(', 8),
347 (b'{', 8),
348 (b'v', 1),
349 (b'h', 4),
350 ] {
351 assert_eq!(alignment(code), want, "alignment of {}", code as char);
352 }
353 }
354
355 #[test]
356 fn accessors_peel_variants() {
357 let wrapped = Value::Variant(Box::new(Value::Str("Pixel".into())));
359 assert_eq!(wrapped.as_str(), Some("Pixel"));
360
361 let nested = Value::Variant(Box::new(Value::Variant(Box::new(Value::Bool(true)))));
362 assert_eq!(nested.as_bool(), Some(true));
363
364 let map = Value::dict([("Name".into(), Value::Str("Pixel".into()))]);
365 assert_eq!(map.get("Name").unwrap().as_str(), Some("Pixel"));
366 assert_eq!(map.get("Missing"), None);
367 }
368
369 #[test]
370 fn byte_arrays_collect() {
371 let v = Value::bytes(&[0xDE, 0xAD]);
372 assert_eq!(v.as_bytes(), Some(vec![0xDE, 0xAD]));
373 assert_eq!(Value::string_array(["a".into()]).as_bytes(), None);
375 }
376}