Skip to main content

cbor_size/
cbor-size.rs

1//! Binary-size probe: exercises one representative encoding + decoding
2//! path per enabled feature tier with black-boxed inputs so nothing is
3//! const-folded away, then reports the bytes written.
4//!
5//! Build & run on the host:
6//! ```text
7//! cargo run --release --example cbor-size --features <tier>
8//! ```
9//! Cross-build for Cortex-M3 and inspect linked sections:
10//! ```text
11//! cargo build --release --target thumbv7m-none-eabi \
12//!     --example cbor-size --features <tier>
13//! size target/thumbv7m-none-eabi/release/examples/cbor-size
14//! ```
15
16#![no_std]
17#![cfg_attr(target_os = "none", no_main)]
18
19use const_cbor::{Decoder, Encoder};
20use core::hint::black_box;
21
22#[cfg(not(target_os = "none"))]
23#[macro_use]
24extern crate std;
25
26#[cfg(target_os = "none")]
27#[panic_handler]
28fn ph(_info: &core::panic::PanicInfo<'_>) -> ! {
29    loop {}
30}
31
32/// Fallible calls resolve errors by early exit rather than panicking:
33/// the probe must measure the *library*, not the panic machinery.
34#[cfg(not(target_os = "none"))]
35macro_rules! bail {
36    () => {
37        return core::hint::black_box(Default::default())
38    };
39}
40#[cfg(target_os = "none")]
41macro_rules! bail {
42    () => {
43        loop {
44            core::hint::black_box(());
45        }
46    };
47}
48#[cfg(not(target_os = "none"))]
49macro_rules! ok {
50    ($e:expr) => {
51        match $e {
52            Ok(v) => v,
53            Err(_) => return core::hint::black_box(Default::default()),
54        }
55    };
56}
57#[cfg(target_os = "none")]
58macro_rules! ok {
59    ($e:expr) => {
60        match $e {
61            Ok(v) => v,
62            Err(_) => loop {
63                core::hint::black_box(());
64            },
65        }
66    };
67}
68
69#[cfg(not(target_os = "none"))]
70fn main() {
71    let n = run_once();
72    println!("{n}");
73}
74
75#[cfg(target_os = "none")]
76// Bare-metal entry point: no runtime exists, so we provide the symbol the
77// linker looks for. `no_mangle` is an FFI attribute, not memory-unsafe code.
78#[allow(unsafe_code)]
79#[unsafe(no_mangle)]
80pub extern "C" fn _start() -> ! {
81    loop {
82        black_box(run_once());
83    }
84}
85
86/// Exercises every enabled feature tier once.
87///
88/// Fallible calls resolve errors by early return rather than panicking:
89/// the probe must measure the *library*, not the panic machinery.
90fn run_once() -> usize {
91    let mut buf = [0u8; 512];
92
93    // ---- always available: definite-length core --------------------
94    let mut e = Encoder::new(&mut buf);
95    let input: u64 = black_box(0xa1_2b_3c_4d_5e_6f_70_81);
96    let neg: i64 = black_box(-25_000);
97    let text: &str = black_box("heartbeat");
98    ok!(e.uint(input));
99    ok!(e.i64(neg));
100    ok!(e.str(text));
101    ok!(ok!(e.array_len(2)).null().and_then(|e| e.bool(true)));
102    let n = e.written();
103
104    let mut d = Decoder::new(black_box(&buf[..n]));
105    let _ = black_box(ok!(d.u64()));
106    let _ = black_box(ok!(d.i64()));
107    let _ = black_box(ok!(d.str()));
108    ok!(d.skip());
109
110    #[cfg(feature = "float")]
111    float_tier(&mut buf);
112
113    #[cfg(feature = "indefinite")]
114    indefinite_tier(&mut buf);
115
116    #[cfg(feature = "bignum")]
117    bignum_tier(&mut buf);
118
119    #[cfg(feature = "diagnostic")]
120    diagnostic_tier();
121
122    #[cfg(feature = "canonical")]
123    canonical_tier(&mut buf);
124
125    #[cfg(all(feature = "raw", feature = "indefinite"))]
126    raw_tier(&mut buf);
127
128    n
129}
130
131#[cfg(feature = "float")]
132fn float_tier(buf: &mut [u8]) {
133    let mut e = Encoder::new(buf);
134    ok!(e.f64(black_box(1.0e300)));
135    ok!(e.f32(black_box(-273.15)));
136    let n = e.written();
137    let mut d = Decoder::new(&buf[..n]);
138    let _ = black_box(ok!(d.f64()));
139    let _ = black_box(ok!(d.f32()));
140}
141
142#[cfg(feature = "indefinite")]
143fn indefinite_tier(buf: &mut [u8]) {
144    let mut e = Encoder::new(buf);
145    ok!(e.begin_bytes());
146    ok!(e.bytes_chunk(black_box(b"chunked")));
147    ok!(e.end_bytes());
148    ok!(e.begin_array());
149    ok!(e.u8(1));
150    ok!(e.end_indef());
151    let n = e.written();
152    let mut d = Decoder::new(black_box(&buf[..n]));
153    if let Ok(mut chunks) = d.bytes_chunks() {
154        while chunks.next().is_some() {}
155        let _ = d.sync_chunks(&chunks);
156    }
157    let _ = black_box(d.skip());
158    black_box(n);
159}
160
161#[cfg(feature = "bignum")]
162fn bignum_tier(buf: &mut [u8]) {
163    let mut e = Encoder::new(buf);
164    let mag: [u8; 16] = black_box([0x01; 16]);
165    ok!(e.bignum_uint(&mag));
166    let n = e.written();
167    let mut d = Decoder::new(&buf[..n]);
168    let _ = black_box(d.bignum_i128());
169}
170
171#[cfg(feature = "diagnostic")]
172fn diagnostic_tier() {
173    let item = &[0x82u8, 0x01, 0x02];
174    let mut out = [0u8; 128];
175    let rendered = const_cbor::diagnostic::render(black_box(item), &mut out).unwrap_or("");
176    black_box(rendered.len());
177}
178
179#[cfg(feature = "canonical")]
180fn canonical_tier(buf: &mut [u8]) {
181    use const_cbor::canonical::MapBuilder;
182    let mut e = Encoder::new(buf);
183    ok!(e.map_len(2));
184    let mut m = MapBuilder::<2>::new(&mut e);
185    ok!(m.add(|k| k.str("bb"), |v| v.u8(1)));
186    ok!(m.add(|k| k.str("aa"), |v| v.u8(2)));
187    ok!(m.finish(&mut [0u8; 32]));
188    black_box(e.written());
189}
190
191#[cfg(feature = "raw")]
192fn raw_tier(buf: &mut [u8]) {
193    let item = [0x82u8, 0x01, 0x02];
194    let mut d = Decoder::new(black_box(&item));
195    let Ok(raw) = d.raw_value() else { bail!() };
196    let mut e = Encoder::new(buf);
197    ok!(e.raw(&raw));
198    black_box(e.written());
199}