Skip to main content

cbor/
cbor.rs

1// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17//! Example program demonstrating cbor usage.
18
19extern crate alloc;
20
21use sk_cbor::values::Value;
22use sk_cbor::{cbor_array, cbor_bytes, cbor_map, cbor_null, cbor_true};
23
24fn hexify(data: &[u8]) -> String {
25    let mut s = String::new();
26    for b in data {
27        s.push_str(&format!("{:02x}", b));
28    }
29    s
30}
31
32fn main() {
33    // Build a CBOR object with various different types included. Note that this
34    // object is not built in canonical order.
35    let manual_object = Value::map(vec![
36        (
37            Value::from(1),
38            Value::array(vec![Value::from(2), Value::from(3)]),
39        ),
40        (Value::from("tstr".to_owned()), Value::from(vec![1, 2, 3])),
41        (Value::from(-2), Value::null_value()),
42        (Value::from(3), Value::bool_value(true)),
43    ]);
44
45    // Build the same object using the crate's convenience macros.
46    let macro_object = cbor_map! {
47        1 => cbor_array![2, 3],
48        "tstr" => cbor_bytes!(vec![1, 2, 3]),
49        -2 => cbor_null!(),
50        3 => cbor_true!(),
51    };
52
53    assert_eq!(manual_object, macro_object);
54    println!("Object {:?}", manual_object);
55
56    // Serialize to bytes.
57    let mut manual_data = vec![];
58    sk_cbor::writer::write(manual_object, &mut manual_data).unwrap();
59    let hex_manual_data = hexify(&manual_data);
60    let mut macro_data = vec![];
61    sk_cbor::writer::write(macro_object, &mut macro_data).unwrap();
62    let hex_macro_data = hexify(&macro_data);
63
64    assert_eq!(hex_manual_data, hex_macro_data);
65
66    // Serialized version is in canonical order.
67    println!("Serializes to {}", hex_manual_data);
68    assert_eq!(
69        hex_manual_data,
70        concat!(
71            "a4",         // 4-map
72            "01",         // int(1) =>
73            "820203",     // 2-array [2, 3],
74            "03",         // int(3) =>
75            "f5",         // true,
76            "21",         // nint(-2) =>
77            "f6",         // null,
78            "6474737472", // 4-tstr "tstr" =>
79            "43010203"    // 3-bstr
80        )
81    );
82
83    // Convert back to an object.  This is different than the original object,
84    // because the map is now in canonical order.
85    let recovered_object = sk_cbor::reader::read(&manual_data).unwrap();
86    println!("Deserializes to {:?}", recovered_object);
87}