Skip to main content

const_cbor/
encode.rs

1//! CBOR encoding into caller-provided buffers.
2//!
3//! [`Encoder`] advances through a fixed `&mut [u8]` output and exposes one
4//! method per CBOR type. Methods return `Result<&mut Self, _>` so calls
5//! chain naturally; nothing allocates and nothing panics at runtime.
6//!
7//! The submodule [`consts`] mirrors the encoder with `const fn`s that
8//! report insufficient space by panic, making whole encodings evaluable at
9//! compile time.
10
11use crate::error::Error;
12use crate::head::{Major, Simple, write_head};
13
14/// Serializes CBOR items into a fixed buffer.
15///
16/// On success each method advances the cursor by exactly the item's
17/// preferred-encoding length. On failure ([`Error::OUT_OF_SPACE`]) nothing
18/// is written for that item, so the encoder stays valid and reusable.
19#[derive(Debug)]
20pub struct Encoder<'b> {
21    pub(crate) buf: &'b mut [u8],
22    pub(crate) pos: usize,
23    /// Open indefinite scopes, innermost last (`indefinite` feature).
24    #[cfg(feature = "indefinite")]
25    pub(crate) indef: [u8; 16],
26    #[cfg(feature = "indefinite")]
27    pub(crate) indef_sp: u8,
28}
29
30impl<'b> Encoder<'b> {
31    /// Creates an encoder writing into `buf`, starting at offset 0.
32    #[inline]
33    #[must_use]
34    pub const fn new(buf: &'b mut [u8]) -> Self {
35        {
36            #[cfg(feature = "indefinite")]
37            let this = Self { buf, pos: 0, indef: [0; 16], indef_sp: 0 };
38            #[cfg(not(feature = "indefinite"))]
39            let this = Self { buf, pos: 0 };
40            this
41        }
42    }
43
44    /// Number of bytes successfully written so far.
45    #[inline]
46    #[must_use]
47    pub const fn written(&self) -> usize {
48        self.pos
49    }
50
51    /// Number of bytes still available for writing.
52    #[inline]
53    #[must_use]
54    pub const fn remaining(&self) -> usize {
55        self.buf.len() - self.pos
56    }
57
58    /// Consumes the encoder, returning the buffer and the bytes written.
59    #[inline]
60    #[must_use]
61    pub const fn finish(self) -> (&'b [u8], usize) {
62        (self.buf, self.pos)
63    }
64
65    /// Fails unless `n` more bytes fit.
66    #[inline]
67    pub(crate) const fn reserve(&self, n: usize) -> Result<(), Error> {
68        match n > self.remaining() {
69            true => Err(Error::OUT_OF_SPACE),
70            false => Ok(()),
71        }
72    }
73
74    /// Writes a head with a preferred-width argument.
75    #[inline]
76    pub(crate) fn put_head(&mut self, major: Major, arg: u64) -> Result<(), Error> {
77        let n = write_head(self.tail(), major, arg)?;
78        self.pos += n;
79        Ok(())
80    }
81
82    #[inline]
83    fn tail(&mut self) -> &mut [u8] {
84        &mut self.buf[self.pos..]
85    }
86
87    /// Writes a length-prefixed payload (byte/text string content).
88    #[inline]
89    pub(crate) fn put_payload(&mut self, major: Major, payload: &[u8]) -> Result<&mut Self, Error> {
90        let len = u64::try_from(payload.len()).map_err(|_| Error::OUT_OF_SPACE)?;
91        self.reserve(crate::head::head_len(len) + payload.len())?;
92        let head = crate::head::head_len(len);
93        let _ = write_head(self.tail(), major, len)?;
94        self.pos += head;
95        self.copy_payload(payload);
96        Ok(self)
97    }
98
99    #[inline]
100    fn copy_payload(&mut self, payload: &[u8]) {
101        let end = self.pos + payload.len();
102        self.buf[self.pos..end].copy_from_slice(payload);
103        self.pos = end;
104    }
105
106    /// Encodes any unsigned integer using its preferred width.
107    ///
108    /// Prefer the typed helpers (`u8`, `u16`, …); they compile to
109    /// identical code and document the value's range.
110    #[inline]
111    pub fn uint(&mut self, v: u64) -> Result<&mut Self, Error> {
112        self.put_head(Major::Unsigned, v)?;
113        Ok(self)
114    }
115
116    /// Encodes `-1 - n` for magnitude `n` (RFC 8949 §3.1).
117    ///
118    /// Magnitudes above `i64::MIN`'s range remain representable in CBOR,
119    /// so this accepts the full `u64` range.
120    #[inline]
121    pub fn nint(&mut self, n: u64) -> Result<&mut Self, Error> {
122        self.put_head(Major::Negative, n)?;
123        Ok(self)
124    }
125
126    /// Encodes a signed integer.
127    #[inline]
128    pub fn i64(&mut self, v: i64) -> Result<&mut Self, Error> {
129        match v >= 0 {
130            true => self.uint(v as u64),
131            false => self.nint(!(v as u64)),
132        }
133    }
134
135    /// Encodes `v`.
136    #[inline]
137    pub fn u8(&mut self, v: u8) -> Result<&mut Self, Error> {
138        self.uint(u64::from(v))
139    }
140
141    /// Encodes `v`.
142    #[inline]
143    pub fn u16(&mut self, v: u16) -> Result<&mut Self, Error> {
144        self.uint(u64::from(v))
145    }
146
147    /// Encodes `v`.
148    #[inline]
149    pub fn u32(&mut self, v: u32) -> Result<&mut Self, Error> {
150        self.uint(u64::from(v))
151    }
152
153    /// Encodes `v`.
154    #[inline]
155    pub fn u64(&mut self, v: u64) -> Result<&mut Self, Error> {
156        self.uint(v)
157    }
158
159    /// Encodes `v`.
160    #[inline]
161    pub fn i8(&mut self, v: i8) -> Result<&mut Self, Error> {
162        self.i64(i64::from(v))
163    }
164
165    /// Encodes `v`.
166    #[inline]
167    pub fn i16(&mut self, v: i16) -> Result<&mut Self, Error> {
168        self.i64(i64::from(v))
169    }
170
171    /// Encodes `v`.
172    #[inline]
173    pub fn i32(&mut self, v: i32) -> Result<&mut Self, Error> {
174        self.i64(i64::from(v))
175    }
176
177    /// Encodes a byte string header followed by its contents.
178    #[inline]
179    pub fn bytes(&mut self, b: &[u8]) -> Result<&mut Self, Error> {
180        self.put_payload(Major::Bytes, b)
181    }
182
183    /// Encodes a text string header followed by its UTF-8 contents.
184    #[inline]
185    pub fn str(&mut self, s: &str) -> Result<&mut Self, Error> {
186        self.put_payload(Major::Text, s.as_bytes())
187    }
188
189    /// Encodes `true` or `false`.
190    #[inline]
191    pub fn bool(&mut self, v: bool) -> Result<&mut Self, Error> {
192        self.simple(match v {
193            true => Simple::TRUE,
194            false => Simple::FALSE,
195        })
196    }
197
198    /// Encodes `null`.
199    #[inline]
200    pub fn null(&mut self) -> Result<&mut Self, Error> {
201        self.simple(Simple::NULL)
202    }
203
204    /// Encodes `undefined`. RFC 8949 §5.7 discourages its use on the wire,
205    /// but the encoding is supported.
206    #[inline]
207    pub fn undefined(&mut self) -> Result<&mut Self, Error> {
208        self.simple(Simple::UNDEFINED)
209    }
210
211    /// Encodes a simple value.
212    ///
213    /// # Errors
214    ///
215    /// Returns [`Error::INVALID_SIMPLE`] when the value would require the
216    /// two-byte form while being below 32; RFC 8949 §3.3 forbids that form.
217    #[inline]
218    pub fn simple(&mut self, s: Simple) -> Result<&mut Self, Error> {
219        match s.0 < 24 || s.valid_two_byte() {
220            true => {
221                self.put_head(Major::Simple, u64::from(s.0))?;
222                Ok(self)
223            }
224            false => Err(Error::INVALID_SIMPLE),
225        }
226    }
227
228    /// Emits a tag header; encode the tagged item immediately after.
229    ///
230    /// Tag semantics live outside this crate (RFC 8949 §3.4): only the tag
231    /// number travels on the wire.
232    #[inline]
233    pub fn tag(&mut self, number: u64) -> Result<&mut Self, Error> {
234        self.put_head(Major::Tag, number)?;
235        Ok(self)
236    }
237
238    /// Emits an array header for `len` following items.
239    #[inline]
240    pub fn array_len(&mut self, len: usize) -> Result<&mut Self, Error> {
241        match u64::try_from(len) {
242            Ok(n) => self.put_head(Major::Array, n)?,
243            Err(_) => return Err(Error::OUT_OF_SPACE),
244        }
245        Ok(self)
246    }
247
248    /// Emits a map header for `pairs` following key/value pairs.
249    #[inline]
250    pub fn map_len(&mut self, pairs: usize) -> Result<&mut Self, Error> {
251        match u64::try_from(pairs) {
252            Ok(n) => self.put_head(Major::Map, n)?,
253            Err(_) => return Err(Error::OUT_OF_SPACE),
254        }
255        Ok(self)
256    }
257}
258
259#[cfg(feature = "float")]
260mod float_impls {
261    use super::{Encoder, Error};
262    use crate::float::{f16_bits_of, f32_of_f16_bits};
263    use crate::head::write_head_exact;
264
265    impl Encoder<'_> {
266        /// Encodes an `f32` using the shortest representation that
267        /// preserves the value exactly (RFC 8949 §4.2.2).
268        pub fn f32(&mut self, v: f32) -> Result<&mut Self, Error> {
269            match f16_bits_of(v) {
270                Some(half) => self.float_exact(u64::from(half), 25),
271                None => self.float_exact(u64::from(v.to_bits()), 26),
272            }
273        }
274
275        /// Encodes an `f64` using the shortest exact representation.
276        pub fn f64(&mut self, v: f64) -> Result<&mut Self, Error> {
277            // Canonical NaN form regardless of payload (RFC 8949 §4.2.2).
278            if v.is_nan() {
279                return self.float_exact(0x7e00, 25);
280            }
281            if let Some(half) = f16_bits_of(v as f32)
282                && f64::from(f32_of_f16_bits(half)) == v
283            {
284                return self.float_exact(u64::from(half), 25);
285            }
286            if f64::from(v as f32) == v {
287                return self.float_exact(u64::from((v as f32).to_bits()), 26);
288            }
289            self.float_exact(v.to_bits(), 27)
290        }
291
292        /// Encodes an `f32` unconditionally as IEEE 754 binary16.
293        ///
294        /// Non-representable values lose information; prefer [`f32`](Self::f32)
295        /// for automatic width selection.
296        pub fn f16(&mut self, v: f32) -> Result<&mut Self, Error> {
297            let half = f16_bits_of(v).unwrap_or(0x7e00);
298            self.float_exact(u64::from(half), 25)
299        }
300
301        #[inline]
302        fn float_exact(&mut self, bits: u64, ai: u8) -> Result<&mut Self, Error> {
303            let n = write_head_exact(self.tail(), bits, ai)?;
304            self.pos += n;
305            Ok(self)
306        }
307    }
308}
309
310/// Compile-time serialization helpers (`const fn`, panic on overflow).
311///
312/// Inside `const` evaluation a panic is a compile error, which turns these
313/// into checked builders for constant CBOR items:
314///
315/// ```
316/// use const_cbor::encode::consts;
317///
318/// const HEARTBEAT: ([u8; 3], usize) = {
319///     let mut buf = [0u8; 3];
320///     let n = consts::put_u64(&mut buf, 0);
321///     (buf, n)
322/// };
323/// assert_eq!(&HEARTBEAT.0[..HEARTBEAT.1], &[0x00]);
324/// ```
325pub mod consts {
326    use crate::error::Error;
327    use crate::head::{Major, write_head};
328
329    /// Preferred encoded length of unsigned integer `v`.
330    #[inline]
331    #[must_use]
332    pub const fn uint_len(v: u64) -> usize {
333        crate::head::uint_len(v)
334    }
335
336    /// Preferred encoded length of signed integer `v`.
337    #[inline]
338    #[must_use]
339    pub const fn i64_len(v: i64) -> usize {
340        match v >= 0 {
341            true => uint_len(v as u64),
342            false => uint_len(!(v as u64)),
343        }
344    }
345
346    /// Encoded length of a string/bytes item with `payload_len` content bytes.
347    #[inline]
348    #[must_use]
349    pub const fn chunk_len(payload_len: usize) -> usize {
350        uint_len(payload_len as u64) + payload_len
351    }
352
353    /// Writes unsigned integer `v` into `buf`; returns bytes written.
354    ///
355    /// # Panics
356    ///
357    /// Panics if `buf` is too small — a compile error under `const` eval.
358    #[inline]
359    #[must_use]
360    pub const fn put_u64(buf: &mut [u8], v: u64) -> usize {
361        expect(write_head(buf, Major::Unsigned, v))
362    }
363
364    /// Writes signed integer `v` into `buf`; returns bytes written.
365    ///
366    /// # Panics
367    ///
368    /// Panics if `buf` is too small — a compile error under `const` eval.
369    #[inline]
370    #[must_use]
371    pub const fn put_i64(buf: &mut [u8], v: i64) -> usize {
372        match v >= 0 {
373            true => put_u64(buf, v as u64),
374            false => expect(write_head(buf, Major::Negative, !(v as u64))),
375        }
376    }
377
378    /// Converts an error to a panic (a compile error during const eval).
379    #[inline]
380    const fn expect(r: Result<usize, Error>) -> usize {
381        match r {
382            Ok(n) => n,
383            Err(_) => panic!("const-cbor: output buffer too small"),
384        }
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::Encoder;
391    use super::consts::{chunk_len, i64_len, put_i64, put_u64, uint_len};
392    use crate::Error;
393
394    #[test]
395    fn integers_preferred_widths() {
396        let mut b = [0u8; 20];
397        let mut e = Encoder::new(&mut b);
398        e.u8(23).unwrap().u8(24).unwrap().u32(1000).unwrap();
399        e.u64(1_000_000).unwrap().u64(u64::MAX).unwrap();
400        assert_eq!(e.written(), 20, "1 + 2 + 3 + 5 + 9 bytes expected");
401        assert_eq!(
402            &b,
403            &[
404                0x17, 0x18, 0x18, 0x19, 0x03, 0xe8, 0x1a, 0x00, 0x0f, 0x42, 0x40, 0x1b, 0xff, 0xff,
405                0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
406            ]
407        );
408    }
409
410    #[test]
411    fn negative_mapping_rfc_examples() {
412        let cases: [(i64, &[u8]); 4] =
413            [(-1, &[0x20]), (-10, &[0x29]), (-100, &[0x38, 0x63]), (-1000, &[0x39, 0x03, 0xe7])];
414        for (v, want) in cases {
415            let mut b = [0u8; 9];
416            let mut e = Encoder::new(&mut b);
417            e.i64(v).unwrap();
418            let n = e.written();
419            assert_eq!(&b[..n], want);
420        }
421        // i64::MIN maps through bitwise NOT without overflow.
422        let mut b = [0u8; 9];
423        let mut e = Encoder::new(&mut b);
424        e.i64(i64::MIN).unwrap();
425        assert_eq!(e.written(), 9);
426        // Magnitudes beyond i64 are legal CBOR via nint.
427        let mut b2 = [0u8; 9];
428        let mut e2 = Encoder::new(&mut b2);
429        e2.nint(u64::MAX).unwrap();
430        assert_eq!(e2.written(), 9);
431    }
432
433    #[test]
434    fn strings_and_bytes() {
435        let mut b = [0u8; 32];
436        let mut e = Encoder::new(&mut b);
437        e.str("hello").unwrap().bytes(&[1, 2, 3]).unwrap();
438        assert_eq!(e.written(), 6 + 4);
439        assert_eq!(&b[..6], &[0x65, b'h', b'e', b'l', b'l', b'o']);
440    }
441
442    #[test]
443    fn headers_and_tags() {
444        let mut b = [0u8; 16];
445        let mut e = Encoder::new(&mut b);
446        e.array_len(3).unwrap().map_len(2).unwrap().tag(1).unwrap().u32(1).unwrap();
447        assert_eq!(e.written(), 4);
448        assert_eq!(&b[..4], &[0x83, 0xa2, 0xc1, 0x01]);
449    }
450
451    #[test]
452    fn simple_values() {
453        let mut b = [0u8; 4];
454        let mut e = Encoder::new(&mut b);
455        e.bool(true).unwrap().null().unwrap();
456        assert!(e.simple(crate::Simple(31)).is_err_and(|err| err == Error::INVALID_SIMPLE));
457        assert!(e.simple(crate::Simple(99)).is_ok());
458        // Ending the borrow explicitly documents that the buffer is final.
459        let Encoder { buf, .. } = e;
460        let _ = buf;
461        assert_eq!(&b, &[0xf5, 0xf6, 0xf8, 99]);
462    }
463
464    #[test]
465    fn out_of_space_preserves_cursor() {
466        let mut b = [0u8; 3];
467        let mut e = Encoder::new(&mut b);
468        e.u8(7).unwrap();
469        assert!(e.str("toolong").is_err_and(|err| err == Error::OUT_OF_SPACE));
470        assert_eq!(e.written(), 1);
471    }
472
473    #[test]
474    fn const_helpers_match_runtime() {
475        assert_eq!(uint_len(23), 1);
476        assert_eq!(i64_len(-1000), 3);
477        assert_eq!(chunk_len(300), 303);
478        let mut b = [0u8; 9];
479        let n = put_i64(&mut b, -1000);
480        assert_eq!(n, 3);
481        assert_eq!(put_u64(&mut b[n..], 0), 1);
482    }
483}