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