Skip to main content

cbor_core/
array.rs

1use crate::Value;
2
3/// Helper for flexible array construction.
4///
5/// Wraps `Vec<Value>` and implements `From` for slices, fixed-size
6/// arrays, `Vec`s, and `()` (empty array), so that [`Value::array`]
7/// can accept all of these through a single `Into<Array>` bound.
8/// Rarely used directly.
9#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
10pub struct Array(pub(crate) Vec<Value>);
11
12impl Array {
13    /// Create an empty array.
14    #[must_use]
15    pub const fn new() -> Self {
16        Self(Vec::new())
17    }
18
19    /// Borrow the inner `Vec`.
20    #[must_use]
21    pub const fn get_ref(&self) -> &Vec<Value> {
22        &self.0
23    }
24
25    /// Mutably borrow the inner `Vec`.
26    pub fn get_mut(&mut self) -> &mut Vec<Value> {
27        &mut self.0
28    }
29
30    /// Unwrap into the inner `Vec`.
31    #[must_use]
32    pub fn into_inner(self) -> Vec<Value> {
33        self.0
34    }
35}
36
37impl<T: Into<Value> + Copy> From<&[T]> for Array {
38    fn from(slice: &[T]) -> Self {
39        Self(slice.iter().map(|&x| x.into()).collect())
40    }
41}
42
43impl<const N: usize, T: Into<Value>> From<[T; N]> for Array {
44    fn from(array: [T; N]) -> Self {
45        Self(array.into_iter().map(|x| x.into()).collect())
46    }
47}
48
49impl<T: Into<Value>> From<Vec<T>> for Array {
50    fn from(vec: Vec<T>) -> Self {
51        Self(vec.into_iter().map(|x| x.into()).collect())
52    }
53}
54
55impl<T: Into<Value>> From<Box<[T]>> for Array {
56    fn from(boxed: Box<[T]>) -> Self {
57        Self(Vec::from(boxed).into_iter().map(|x| x.into()).collect())
58    }
59}
60
61impl From<()> for Array {
62    fn from(_: ()) -> Self {
63        Self(Vec::new())
64    }
65}