Skip to main content

cbor_core/
array.rs

1use crate::Value;
2
3/// Conversion helper for [`Value::array`].
4///
5/// This type wraps `Vec<Value>` and provides `From` implementations
6/// for common collection types, so that `Value::array()` can accept
7/// them all through a single `impl Into<Array>` bound.
8///
9/// Supported source types (where `T: Into<Value>`):
10///
11/// - `[T; N]` — fixed-size array
12/// - `&[T]` — slice (requires `T: Copy`)
13/// - `Vec<T>` — vector
14/// - `Box<[T]>` — boxed slice
15/// - `()` — empty array
16///
17/// Elements are converted to `Value` via their `Into<Value>`
18/// implementation. This means any type that implements
19/// `Into<Value>` (integers, strings, booleans, floats, nested
20/// `Value`s, etc.) can be used as elements.
21///
22/// ```
23/// # use cbor_core::Value;
24/// // From a fixed-size array of integers:
25/// let a = Value::array([1, 2, 3]);
26///
27/// // From a Vec of strings:
28/// let b = Value::array(vec!["x", "y"]);
29///
30/// // From a slice:
31/// let items: &[i32] = &[10, 20];
32/// let c = Value::array(items);
33///
34/// // Empty array via ():
35/// let d = Value::array(());
36/// assert_eq!(d.len(), Some(0));
37/// ```
38#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
39pub struct Array(pub(crate) Vec<Value>);
40
41impl Array {
42    /// Create an empty array.
43    #[must_use]
44    pub const fn new() -> Self {
45        Self(Vec::new())
46    }
47
48    /// Borrow the inner `Vec`.
49    #[must_use]
50    pub const fn get_ref(&self) -> &Vec<Value> {
51        &self.0
52    }
53
54    /// Mutably borrow the inner `Vec`.
55    pub fn get_mut(&mut self) -> &mut Vec<Value> {
56        &mut self.0
57    }
58
59    /// Unwrap into the inner `Vec`.
60    #[must_use]
61    pub fn into_inner(self) -> Vec<Value> {
62        self.0
63    }
64}
65
66impl<T: Into<Value> + Copy> From<&[T]> for Array {
67    fn from(slice: &[T]) -> Self {
68        Self(slice.iter().map(|&x| x.into()).collect())
69    }
70}
71
72impl<const N: usize, T: Into<Value>> From<[T; N]> for Array {
73    fn from(array: [T; N]) -> Self {
74        Self(array.into_iter().map(|x| x.into()).collect())
75    }
76}
77
78impl<T: Into<Value>> From<Vec<T>> for Array {
79    fn from(vec: Vec<T>) -> Self {
80        Self(vec.into_iter().map(|x| x.into()).collect())
81    }
82}
83
84impl<T: Into<Value>> From<Box<[T]>> for Array {
85    fn from(boxed: Box<[T]>) -> Self {
86        Self(Vec::from(boxed).into_iter().map(|x| x.into()).collect())
87    }
88}
89
90impl From<()> for Array {
91    fn from(_: ()) -> Self {
92        Self(Vec::new())
93    }
94}