zvariant_utils/signature/
fields.rs

1use super::Signature;
2
3/// Signatures of the fields of a [`Signature::Structure`].
4#[derive(Debug, Clone)]
5pub enum Fields {
6    Static {
7        fields: &'static [&'static Signature],
8    },
9    Dynamic {
10        fields: Box<[Signature]>,
11    },
12}
13
14impl Fields {
15    /// A iterator over the fields' signatures.
16    pub fn iter(&self) -> impl Iterator<Item = &Signature> {
17        use std::slice::Iter;
18
19        enum Fields<'a> {
20            Static(Iter<'static, &'static Signature>),
21            Dynamic(Iter<'a, Signature>),
22        }
23
24        impl<'a> Iterator for Fields<'a> {
25            type Item = &'a Signature;
26
27            fn next(&mut self) -> Option<Self::Item> {
28                match self {
29                    Fields::Static(iter) => iter.next().copied(),
30                    Fields::Dynamic(iter) => iter.next(),
31                }
32            }
33        }
34
35        match self {
36            Self::Static { fields } => Fields::Static(fields.iter()),
37            Self::Dynamic { fields } => Fields::Dynamic(fields.iter()),
38        }
39    }
40
41    /// The number of fields.
42    pub const fn len(&self) -> usize {
43        match self {
44            Self::Static { fields } => fields.len(),
45            Self::Dynamic { fields } => fields.len(),
46        }
47    }
48
49    /// Whether there are no fields.
50    pub fn is_empty(&self) -> bool {
51        self.len() == 0
52    }
53}
54
55impl From<Box<[Signature]>> for Fields {
56    fn from(fields: Box<[Signature]>) -> Self {
57        Fields::Dynamic { fields }
58    }
59}
60
61impl From<Vec<Signature>> for Fields {
62    fn from(fields: Vec<Signature>) -> Self {
63        Fields::Dynamic {
64            fields: fields.into(),
65        }
66    }
67}
68
69impl<const N: usize> From<[Signature; N]> for Fields {
70    fn from(fields: [Signature; N]) -> Self {
71        Fields::Dynamic {
72            fields: fields.into(),
73        }
74    }
75}
76
77impl From<&'static [&'static Signature]> for Fields {
78    fn from(fields: &'static [&'static Signature]) -> Self {
79        Fields::Static { fields }
80    }
81}