1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use byteorder::ByteOrder;
use core::convert::TryInto;

use crate::{Decode, Encode, EncodingFormat};
use crate::{SharedData, Signature, SimpleDecode};
use crate::{Variant, VariantError};

/// An unordered collection of items of the same type.
///
/// API is provided to transform this into, and from a [`Vec`].
///
/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
#[derive(Debug, Clone, Default)]
pub struct Array(Vec<Variant>);

impl Array {
    /// Creates a new empty `Array`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates an `Array` from given variants.
    ///
    /// All variants must all contain the same type.
    ///
    /// # Example:
    ///
    /// ```
    /// use zvariant::{Array, Encode, Variant};
    ///
    /// let variants = vec![42u8.to_variant(), 45u8.to_variant()];
    /// let array = Array::new_from_vec(variants).unwrap();
    ///
    /// let variants = vec![42u8.to_variant(), 45u32.to_variant()];
    /// assert!(Array::new_from_vec(variants).is_err());
    /// ```
    pub fn new_from_vec(vec: Vec<Variant>) -> Result<Self, VariantError> {
        // Ensure all elements are of the same type
        if let Some(first) = vec.first() {
            let first_sig = first.value_signature();

            for element in &vec[1..] {
                if element.value_signature() != first_sig {
                    return Err(VariantError::IncorrectType);
                }
            }
        }

        Ok(Array(vec))
    }

    /// Creates an `Array` from given variants.
    ///
    /// Same as [`new_from_vec`] but the caller guarantees all variants in the `vec` are of the same
    /// type.
    ///
    /// [`new_from_vec`]: struct.Array.html#method.new_from_vec
    pub fn new_from_vec_unchecked(vec: Vec<Variant>) -> Self {
        Array(vec)
    }

    /// Adds the given `element` to `self`.
    ///
    /// # Example:
    ///
    /// ```
    /// use zvariant::{Array, Decode, Variant};
    ///
    /// let mut array = Array::new();
    /// array.add_element(42u8).unwrap();
    /// assert!(array.add_element("hi").is_err());
    /// array.add_element(45u8).unwrap();
    /// assert!(array.add_element(42u32).is_err());
    /// ```
    pub fn add_element<T: Encode>(&mut self, element: T) -> Result<(), VariantError> {
        // Ensure we only add elements of the same type
        if self.0.last().map(|v| !T::is(v)).unwrap_or(false) {
            return Err(VariantError::IncorrectType);
        }

        self.0.push(element.to_variant());

        Ok(())
    }

    /// Get the element at the given index.
    ///
    /// # Example:
    ///
    /// ```
    /// use zvariant::{Array, Decode, Variant};
    ///
    /// let array = Array::from(vec![42u8, 43, 44]);
    /// assert!(*array.get_element::<u8>(0).unwrap() == 42);
    /// assert!(*array.get_element::<u8>(1).unwrap() == 43);
    /// assert!(*array.get_element::<u8>(2).unwrap() == 44);
    /// ```
    pub fn get_element<T: Decode>(&self, index: usize) -> Result<&T, VariantError> {
        T::from_variant(&self.0[index])
    }

    fn get(&self) -> &Vec<Variant> {
        &self.0
    }

    fn into_inner(self) -> Vec<Variant> {
        self.0
    }
}

impl Encode for Array {
    const SIGNATURE_CHAR: char = 'a';
    const SIGNATURE_STR: &'static str = "a";
    const ALIGNMENT: usize = 4;

    fn encode_into(&self, bytes: &mut Vec<u8>, format: EncodingFormat) {
        Self::add_padding(bytes, format);

        let len_position = bytes.len();
        bytes.extend(&0u32.to_ne_bytes());
        let n_bytes_before = bytes.len();
        let mut first_element = true;
        let mut first_padding = 0;

        for element in self.get() {
            if first_element {
                // Length we report doesn't include padding for the first element
                first_padding = element.value_padding(bytes.len(), format);
                first_element = false;
            }

            // Deep copying, nice!!! 🙈
            element.encode_value_into(bytes, format);
        }

        // Set size of array in bytes
        let len = crate::utils::usize_to_u32(bytes.len() - n_bytes_before - first_padding);
        byteorder::NativeEndian::write_u32(&mut bytes[len_position..len_position + 4], len);
    }

    fn signature(&self) -> Signature {
        let signature = format!("a{}", self.get()[0].value_signature().as_str());

        Signature::from(signature)
    }

    fn to_variant(self) -> Variant {
        Variant::Array(self)
    }

    fn is(variant: &Variant) -> bool {
        if let Variant::Array(_) = variant {
            true
        } else {
            false
        }
    }
}

impl Decode for Array {
    fn slice_data(
        data: impl Into<SharedData>,
        signature: impl Into<Signature>,
        format: EncodingFormat,
    ) -> Result<SharedData, VariantError> {
        let signature = Self::ensure_correct_signature(signature)?;

        // Child signature
        let child_signature = crate::decode::slice_signature(&signature[1..])?;

        let data = data.into();
        // Array size in bytes
        let len_slice = u32::slice_data_simple(&data, format)?;
        let mut extracted = len_slice.len();
        let mut len = u32::decode_simple(&len_slice, format)? as usize + extracted;
        let mut first_element = true;
        while extracted < len {
            let element_data = data.tail(extracted);

            if first_element {
                // Length we got from array doesn't include padding for the first element
                len += crate::encode::padding_for_signature(
                    element_data.position(),
                    child_signature.as_str(),
                    format,
                );
                first_element = false;
            }

            let slice = crate::decode::slice_data(element_data, child_signature.as_str(), format)?;
            extracted += slice.len();
            if extracted > len {
                return Err(VariantError::InsufficientData);
            }
        }
        if extracted == 0 {
            return Err(VariantError::ExcessData);
        }

        Ok(data.head(extracted as usize))
    }

    fn decode(
        data: impl Into<SharedData>,
        signature: impl Into<Signature>,
        format: EncodingFormat,
    ) -> Result<Self, VariantError> {
        let data = data.into();
        let padding = Self::padding(data.position(), format);
        if data.len() < padding + 4 {
            return Err(VariantError::InsufficientData);
        }
        let signature = Self::ensure_correct_signature(signature)?;

        // Child signature
        let child_signature = crate::decode::slice_signature(&signature[1..])?;

        // Array size in bytes
        let mut extracted = padding + 4;
        let mut len =
            u32::decode_simple(&data.subset(padding, extracted), format)? as usize + extracted;
        let mut elements = vec![];

        let mut first_element = true;
        while extracted < len {
            let element_data = data.tail(extracted);

            if first_element {
                // Length we got from array doesn't include padding for the first element
                len += crate::encode::padding_for_signature(
                    element_data.position(),
                    child_signature.as_str(),
                    format,
                );
                first_element = false;
            }

            let slice = crate::decode::slice_data(element_data, child_signature.as_str(), format)?;
            extracted += slice.len();
            if extracted > len {
                return Err(VariantError::InsufficientData);
            }

            let element = Variant::from_data_slice(slice, child_signature.as_str(), format)?;
            elements.push(element);
        }
        if extracted == 0 {
            return Err(VariantError::ExcessData);
        }

        // Not using Array::new_from_vec() as that will entail redundant (in this context) type
        // checks
        Ok(Array::new_from_vec_unchecked(elements))
    }

    fn ensure_correct_signature(
        signature: impl Into<Signature>,
    ) -> Result<Signature, VariantError> {
        let signature = signature.into();
        let len = signature.len();
        let slice = Self::slice_signature(signature)?;
        if slice.len() != len {
            return Err(VariantError::IncorrectType);
        }

        Ok(slice)
    }

    fn slice_signature(signature: impl Into<Signature>) -> Result<Signature, VariantError> {
        let signature = signature.into();
        if signature.len() < 2 {
            return Err(VariantError::InsufficientData);
        }
        if !signature.starts_with('a') {
            return Err(VariantError::IncorrectType);
        }

        // There should be a valid complete signature after 'a' but not more than 1
        let slice = crate::decode::slice_signature(&signature[1..])?;

        Ok(Signature::from(&signature[0..=slice.len()]))
    }

    fn take_from_variant(variant: Variant) -> Result<Self, VariantError> {
        if let Variant::Array(value) = variant {
            Ok(value)
        } else {
            Err(VariantError::IncorrectType)
        }
    }

    fn from_variant(variant: &Variant) -> Result<&Self, VariantError> {
        if let Variant::Array(value) = variant {
            Ok(value)
        } else {
            Err(VariantError::IncorrectType)
        }
    }
}

impl<T> TryInto<Vec<T>> for Array
where
    T: Decode,
{
    type Error = VariantError;

    fn try_into(self) -> Result<Vec<T>, VariantError> {
        let mut v = vec![];

        for value in self.into_inner() {
            v.push(T::take_from_variant(value)?);
        }

        Ok(v)
    }
}

impl<'a, T> TryInto<Vec<&'a T>> for &'a Array
where
    T: Decode,
{
    type Error = VariantError;

    fn try_into(self) -> Result<Vec<&'a T>, VariantError> {
        let mut v = vec![];

        for value in self.get() {
            v.push(T::from_variant(value)?);
        }

        Ok(v)
    }
}

impl<T> From<Vec<T>> for Array
where
    T: Encode,
{
    fn from(values: Vec<T>) -> Self {
        let v = values.into_iter().map(|value| value.to_variant()).collect();

        Array::new_from_vec_unchecked(v)
    }
}

impl From<crate::Dict> for Array {
    fn from(value: crate::Dict) -> Self {
        Array::from(value.into_inner())
    }
}