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            if let Some(half) = f16_bits_of(v as f32) {
278                if f64::from(f32_of_f16_bits(half)) == v {
279                    return self.float_exact(u64::from(half), 25);
280                }
281            }
282            if !v.is_nan() && f64::from(v as f32) == v {
283                return self.float_exact(u64::from((v as f32).to_bits()), 26);
284            }
285            self.float_exact(v.to_bits(), 27)
286        }
287
288        /// Encodes an `f32` unconditionally as IEEE 754 binary16.
289        ///
290        /// Non-representable values lose information; prefer [`f32`](Self::f32)
291        /// for automatic width selection.
292        pub fn f16(&mut self, v: f32) -> Result<&mut Self, Error> {
293            let half = f16_bits_of(v).unwrap_or(0x7e00);
294            self.float_exact(u64::from(half), 25)
295        }
296
297        #[inline]
298        fn float_exact(&mut self, bits: u64, ai: u8) -> Result<&mut Self, Error> {
299            let n = write_head_exact(self.tail(), bits, ai)?;
300            self.pos += n;
301            Ok(self)
302        }
303    }
304}
305
306/// Compile-time serialization helpers (`const fn`, panic on overflow).
307///
308/// Inside `const` evaluation a panic is a compile error, which turns these
309/// into checked builders for constant CBOR items:
310///
311/// ```
312/// use const_cbor::encode::consts;
313///
314/// const HEARTBEAT: ([u8; 3], usize) = {
315///     let mut buf = [0u8; 3];
316///     let n = consts::put_u64(&mut buf, 0);
317///     (buf, n)
318/// };
319/// assert_eq!(&HEARTBEAT.0[..HEARTBEAT.1], &[0x00]);
320/// ```
321pub mod consts {
322    use crate::error::Error;
323    use crate::head::{Major, write_head};
324
325    /// Preferred encoded length of unsigned integer `v`.
326    #[inline]
327    #[must_use]
328    pub const fn uint_len(v: u64) -> usize {
329        crate::head::uint_len(v)
330    }
331
332    /// Preferred encoded length of signed integer `v`.
333    #[inline]
334    #[must_use]
335    pub const fn i64_len(v: i64) -> usize {
336        match v >= 0 {
337            true => uint_len(v as u64),
338            false => uint_len(!(v as u64)),
339        }
340    }
341
342    /// Encoded length of a string/bytes item with `payload_len` content bytes.
343    #[inline]
344    #[must_use]
345    pub const fn chunk_len(payload_len: usize) -> usize {
346        uint_len(payload_len as u64) + payload_len
347    }
348
349    /// Writes unsigned integer `v` into `buf`; returns bytes written.
350    ///
351    /// # Panics
352    ///
353    /// Panics if `buf` is too small — a compile error under `const` eval.
354    #[inline]
355    #[must_use]
356    pub const fn put_u64(buf: &mut [u8], v: u64) -> usize {
357        expect(write_head(buf, Major::Unsigned, v))
358    }
359
360    /// Writes signed integer `v` into `buf`; returns bytes written.
361    ///
362    /// # Panics
363    ///
364    /// Panics if `buf` is too small — a compile error under `const` eval.
365    #[inline]
366    #[must_use]
367    pub const fn put_i64(buf: &mut [u8], v: i64) -> usize {
368        match v >= 0 {
369            true => put_u64(buf, v as u64),
370            false => expect(write_head(buf, Major::Negative, !(v as u64))),
371        }
372    }
373
374    /// Converts an error to a panic (a compile error during const eval).
375    #[inline]
376    const fn expect(r: Result<usize, Error>) -> usize {
377        match r {
378            Ok(n) => n,
379            Err(_) => panic!("const-cbor: output buffer too small"),
380        }
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use super::Encoder;
387    use super::consts::{chunk_len, i64_len, put_i64, put_u64, uint_len};
388    use crate::Error;
389
390    #[test]
391    fn integers_preferred_widths() {
392        let mut b = [0u8; 20];
393        let mut e = Encoder::new(&mut b);
394        e.u8(23).unwrap().u8(24).unwrap().u32(1000).unwrap();
395        e.u64(1_000_000).unwrap().u64(u64::MAX).unwrap();
396        assert_eq!(e.written(), 20, "1 + 2 + 3 + 5 + 9 bytes expected");
397        assert_eq!(
398            &b,
399            &[
400                0x17, 0x18, 0x18, 0x19, 0x03, 0xe8, 0x1a, 0x00, 0x0f, 0x42, 0x40, 0x1b, 0xff, 0xff,
401                0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
402            ]
403        );
404    }
405
406    #[test]
407    fn negative_mapping_rfc_examples() {
408        let cases: [(i64, &[u8]); 4] =
409            [(-1, &[0x20]), (-10, &[0x29]), (-100, &[0x38, 0x63]), (-1000, &[0x39, 0x03, 0xe7])];
410        for (v, want) in cases {
411            let mut b = [0u8; 9];
412            let mut e = Encoder::new(&mut b);
413            e.i64(v).unwrap();
414            let n = e.written();
415            assert_eq!(&b[..n], want);
416        }
417        // i64::MIN maps through bitwise NOT without overflow.
418        let mut b = [0u8; 9];
419        let mut e = Encoder::new(&mut b);
420        e.i64(i64::MIN).unwrap();
421        assert_eq!(e.written(), 9);
422        // Magnitudes beyond i64 are legal CBOR via nint.
423        let mut b2 = [0u8; 9];
424        let mut e2 = Encoder::new(&mut b2);
425        e2.nint(u64::MAX).unwrap();
426        assert_eq!(e2.written(), 9);
427    }
428
429    #[test]
430    fn strings_and_bytes() {
431        let mut b = [0u8; 32];
432        let mut e = Encoder::new(&mut b);
433        e.str("hello").unwrap().bytes(&[1, 2, 3]).unwrap();
434        assert_eq!(e.written(), 6 + 4);
435        assert_eq!(&b[..6], &[0x65, b'h', b'e', b'l', b'l', b'o']);
436    }
437
438    #[test]
439    fn headers_and_tags() {
440        let mut b = [0u8; 16];
441        let mut e = Encoder::new(&mut b);
442        e.array_len(3).unwrap().map_len(2).unwrap().tag(1).unwrap().u32(1).unwrap();
443        assert_eq!(e.written(), 4);
444        assert_eq!(&b[..4], &[0x83, 0xa2, 0xc1, 0x01]);
445    }
446
447    #[test]
448    fn simple_values() {
449        let mut b = [0u8; 4];
450        let mut e = Encoder::new(&mut b);
451        e.bool(true).unwrap().null().unwrap();
452        assert!(e.simple(crate::Simple(31)).is_err_and(|err| err == Error::INVALID_SIMPLE));
453        assert!(e.simple(crate::Simple(99)).is_ok());
454        // Ending the borrow explicitly documents that the buffer is final.
455        let Encoder { buf, .. } = e;
456        let _ = buf;
457        assert_eq!(&b, &[0xf5, 0xf6, 0xf8, 99]);
458    }
459
460    #[test]
461    fn out_of_space_preserves_cursor() {
462        let mut b = [0u8; 3];
463        let mut e = Encoder::new(&mut b);
464        e.u8(7).unwrap();
465        assert!(e.str("toolong").is_err_and(|err| err == Error::OUT_OF_SPACE));
466        assert_eq!(e.written(), 1);
467    }
468
469    #[test]
470    fn const_helpers_match_runtime() {
471        assert_eq!(uint_len(23), 1);
472        assert_eq!(i64_len(-1000), 3);
473        assert_eq!(chunk_len(300), 303);
474        let mut b = [0u8; 9];
475        let n = put_i64(&mut b, -1000);
476        assert_eq!(n, 3);
477        assert_eq!(put_u64(&mut b[n..], 0), 1);
478    }
479}