dcbor_parse/
compose.rs

1use dcbor::prelude::*;
2use crate::{ parse_dcbor_item, ParseError };
3use thiserror::Error;
4
5#[derive(Debug, Error, Clone, PartialEq)]
6#[rustfmt::skip]
7pub enum Error {
8    #[error("Invalid odd map length")]
9    OddMapLength,
10    #[error("Invalid CBOR item: {0}")]
11    ParseError(#[from] ParseError),
12}
13
14pub type Result<T> = std::result::Result<T, Error>;
15
16/// Composes a dCBOR array from a slice of string slices, and returns a CBOR
17/// object representing the array.
18///
19/// Each string slice is parsed as a dCBOR item.
20///
21/// # Example
22///
23/// ```rust
24/// # use dcbor_parse::compose_dcbor_array;
25/// let cbor = compose_dcbor_array(&["1", "2", "3"]).unwrap();
26/// assert_eq!(cbor.diagnostic(), "[1, 2, 3]");
27/// ```
28pub fn compose_dcbor_array(array: &[&str]) -> Result<CBOR> {
29    let mut result = Vec::new();
30    for item in array {
31        let cbor = parse_dcbor_item(item)?;
32        result.push(cbor);
33    }
34    Ok(result.into())
35}
36
37/// Composes a dCBOR map from a slice of string slices, and returns a CBOR
38/// object representing the map.
39///
40/// The length of the slice must be even, as each key must have a corresponding
41/// value.
42///
43/// Each string slice is parsed as a dCBOR item.
44///
45/// # Example
46///
47/// ```rust
48/// # use dcbor_parse::compose_dcbor_map;
49/// let cbor = compose_dcbor_map(&["1", "2", "3", "4"]).unwrap();
50/// assert_eq!(cbor.diagnostic(), "{1: 2, 3: 4}");
51/// ```
52pub fn compose_dcbor_map(array: &[&str]) -> Result<CBOR> {
53    if array.len() % 2 != 0 {
54        return Err(Error::OddMapLength);
55    }
56
57    let mut map = Map::new();
58    for i in (0..array.len()).step_by(2) {
59        let key = parse_dcbor_item(array[i])?;
60        let value = parse_dcbor_item(array[i + 1])?;
61        map.insert(key, value);
62    }
63
64    Ok(map.into())
65}