dbus_message_parser/value/
container.rs1use crate::value::{Type, TypeError, Value};
2use std::convert::{AsRef, TryFrom};
3use thiserror::Error;
4
5#[derive(Debug, Clone, PartialOrd, PartialEq)]
6pub struct Array {
7 pub(crate) type_: Type,
8 pub(crate) array: Vec<Value>,
9}
10
11#[derive(Debug, PartialEq, Error)]
12pub enum ArrayError {
13 #[error("The type of an array element is different: expected '{0}' got '{1}'")]
14 TypeMismatch(Type, Type),
15 #[error("Coult not get type of element: {0}")]
16 TypeError(#[from] TypeError),
17}
18
19impl Array {
20 pub fn new(array: Vec<Value>, type_: Type) -> Result<Array, ArrayError> {
21 for v in &array {
22 let s = v.get_type()?;
23 if s != type_ {
24 return Err(ArrayError::TypeMismatch(type_, s));
25 }
26 }
27 let array = Array { type_, array };
28 Ok(array)
29 }
30
31 #[inline]
32 pub const fn get_type(&self) -> &Type {
33 &self.type_
34 }
35}
36
37impl AsRef<[Value]> for Array {
38 fn as_ref(&self) -> &[Value] {
39 self.array.as_ref()
40 }
41}
42
43impl From<Array> for Vec<Value> {
44 fn from(array: Array) -> Self {
45 array.array
46 }
47}
48
49#[derive(Debug, Clone, PartialOrd, PartialEq)]
50pub struct Struct(pub(crate) Vec<Value>);
51
52#[derive(Debug, PartialEq, Error)]
53pub enum StructError {
54 #[error("Strcut cannot be empty")]
55 Empty,
56}
57
58impl AsRef<[Value]> for Struct {
59 fn as_ref(&self) -> &[Value] {
60 self.0.as_ref()
61 }
62}
63
64impl TryFrom<Vec<Value>> for Struct {
65 type Error = StructError;
66
67 fn try_from(values: Vec<Value>) -> Result<Self, Self::Error> {
68 if values.is_empty() {
69 Err(StructError::Empty)
70 } else {
71 Ok(Struct(values))
72 }
73 }
74}
75
76impl From<Struct> for Vec<Value> {
77 fn from(struct_: Struct) -> Self {
78 struct_.0
79 }
80}