Skip to main content

kmip_protocol/ttlv/
format.rs

1//! Serializing TTLV elements.
2//!
3//! This module provides low-level TTLV serialization support.  It is entirely
4//! manual -- it does not provide a declarative interface.  It is designed for
5//! fast, streaming operation.
6
7use core::{
8    fmt,
9    mem::{MaybeUninit, transmute},
10    ops::{Deref, DerefMut},
11};
12
13use super::types::{Tag, Type};
14
15//----------- Formatter ------------------------------------------------------
16
17/// A TTLV formatter.
18///
19/// ## Panics
20///
21/// TTLV uses 32-bit fields to express the size of serialized data, in units of
22/// bytes.  To guarantee panic-free operation, only the first 4GiB of a given
23/// input buffer will be used.  A write that would overflow a length field is
24/// guaranteed to return [`TruncationError`] instead.
25pub struct Formatter<'b> {
26    /// The buffer to write into.
27    ///
28    /// - Invariant `size`:
29    ///   `buffer.as_flattened().len() <= 2^32`.
30    buffer: &'b mut [MaybeUninit<[u8; 8]>],
31
32    /// The current position into the buffer.
33    ///
34    /// - Invariant `initialized`:
35    ///   `self.buffer[..self.position]` is initialized.
36    ///
37    /// - Invariant `coherent-position`:
38    ///   `self.position <= self.buffer.len()`.
39    position: usize,
40}
41
42impl<'b> Formatter<'b> {
43    /// Construct a new [`Formatter`].
44    ///
45    /// The input will be truncated to the first 4GiB, and to a multiple of 8
46    /// bytes, as per limitations of the TTLV format.  It should ideally be
47    /// aligned to an 8-byte address boundary (for better performance).
48    pub const fn new(buffer: &'b mut [MaybeUninit<u8>]) -> Self {
49        let mut num_blocks = buffer.len() / 8;
50
51        // Equivalent to 'buffer.len() >= 2^32'.  If 'usize' is smaller than
52        // 'u32', this is equivalent to 'buffer.len() > usize::MAX', which is
53        // trivially false.
54        if buffer.len() > u32::MAX as usize {
55            num_blocks = 1usize << 29;
56        }
57
58        let ptr = buffer.as_mut_ptr().cast::<MaybeUninit<[u8; 8]>>();
59        let buffer = unsafe { core::slice::from_raw_parts_mut(ptr, num_blocks) };
60
61        Self { buffer, position: 0 }
62    }
63
64    /// Construct a new [`Formatter`] from its raw parts.
65    ///
66    /// ## Safety
67    ///
68    /// `Formatter::from_raw_parts(buffer, position)` is sound if and only if:
69    /// - `position <= buffer.len()`.
70    /// - `buffer[..position]` is initialized.
71    /// - `buffer.len() * 8 <= 2^32`.
72    pub const unsafe fn from_raw_parts(buffer: &'b mut [MaybeUninit<[u8; 8]>], position: usize) -> Self {
73        debug_assert!(position <= buffer.len());
74        debug_assert!(usize::BITS <= u32::BITS || buffer.len() <= (1usize << 29));
75        Self { buffer, position }
76    }
77
78    pub fn clear(&mut self) {
79        self.position = 0;
80    }
81
82    /// The filled part of the buffer.
83    pub fn filled(&self) -> &[[u8; 8]] {
84        unsafe {
85            let blocks = self.buffer.get_unchecked(..self.position);
86            transmute::<&[MaybeUninit<[u8; 8]>], &[[u8; 8]]>(blocks)
87        }
88    }
89
90    /// The filled part of the buffer, mutably.
91    pub fn filled_mut(&mut self) -> &mut [[u8; 8]] {
92        unsafe {
93            let blocks = self.buffer.get_unchecked_mut(..self.position);
94            transmute::<&mut [MaybeUninit<[u8; 8]>], &mut [[u8; 8]]>(blocks)
95        }
96    }
97
98    /// The remaining part of the buffer.
99    pub fn remaining(&mut self) -> &mut [MaybeUninit<[u8; 8]>] {
100        unsafe { self.buffer.get_unchecked_mut(self.position..) }
101    }
102
103    /// Destructure a [`Formatter`] into its raw parts.
104    ///
105    /// ## Invariants
106    ///
107    /// For `(buffer, position) = self.into_raw_parts()`:
108    /// - Invariant `coherent-position`: `position <= buffer.len()`.
109    /// - Invariant `initialized`: `buffer[..position]` is initialized.
110    /// - Invariant `size`: `buffer.as_flattened().len() <= 2^32`.
111    pub const fn into_raw_parts(self) -> (&'b mut [MaybeUninit<[u8; 8]>], usize) {
112        (self.buffer, self.position)
113    }
114}
115
116impl<'b> Formatter<'b> {
117    /// Format a structure.
118    ///
119    /// The returned sub-formatter should be used to format the fields of the
120    /// `struct`; once it is finished, `self` can continue.
121    #[must_use = "Use the returned formatter to fill the structure, and call `.finish()` when it is ready"]
122    #[inline]
123    pub fn format_struct(&mut self, tag: Tag) -> Result<FieldFormatter<'_>, TruncationError> {
124        // Can't use 'self.remaining()', would borrow more than '.buffer'.
125        let buffer = &mut self.buffer[self.position..];
126        let (header_slot, rest) = buffer.split_first_mut().ok_or(TruncationError)?;
127
128        // Write the field header.
129        let header = (tag.with_type(Type::Structure).value() as u64) << 32;
130        let header = header_slot.write(header.to_be_bytes());
131
132        Ok(FieldFormatter {
133            outer_pos: &mut self.position,
134            header,
135            inner: Formatter {
136                buffer: rest,
137                position: 0,
138            },
139        })
140    }
141
142    /// Format an integer.
143    #[inline]
144    pub fn format_int(&mut self, tag: Tag, value: i32) -> FormatResult {
145        let header = (tag.with_type(Type::Integer).value() as u64) << 32 | 4;
146
147        let buffer = &mut self.buffer[self.position..];
148        let [header_slot, value_slot, ..] = buffer else {
149            return Err(TruncationError);
150        };
151
152        header_slot.write(header.to_be_bytes());
153        value_slot.write(((value as u32 as u64) << 32).to_be_bytes());
154        self.position += 2;
155        Ok(FormatDone(()))
156    }
157
158    /// Format a long integer.
159    #[inline]
160    pub fn format_long_int(&mut self, tag: Tag, value: i64) -> FormatResult {
161        let header = (tag.with_type(Type::LongInteger).value() as u64) << 32 | 8;
162
163        let buffer = &mut self.buffer[self.position..];
164        let [header_slot, value_slot, ..] = buffer else {
165            return Err(TruncationError);
166        };
167
168        header_slot.write(header.to_be_bytes());
169        value_slot.write((value as u64).to_be_bytes());
170        self.position += 2;
171        Ok(FormatDone(()))
172    }
173
174    /// Format a big integer.
175    ///
176    /// `value` should be the bytewise digits of a signed (two's complement)
177    /// big-endian integer.  It will be padded (with leading sign-extension
178    /// bytes) into a multiple of 8 bytes before being stored.
179    ///
180    /// # Panics
181    ///
182    /// Panics if the length of `value` (when rounded up to a multiple of 8
183    /// bytes) does not fit in a `u32`.
184    #[inline]
185    pub fn format_big_int(&mut self, tag: Tag, value: &[u8]) -> FormatResult {
186        let num_blocks = value.len().div_ceil(8);
187        let buffer = &mut self.buffer[self.position..];
188        if buffer.len() < 1 + num_blocks {
189            return Err(TruncationError);
190        }
191
192        let header = tag.with_type(Type::BigInteger).value();
193        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
194        let length = (value.len() as u32).next_multiple_of(8);
195        let header = (header as u64) << 32 | length as u64;
196        buffer[0].write(header.to_be_bytes());
197
198        if let &[first, ..] = value {
199            // Fill the first 8 bytes by sign extension.
200            //
201            // This also ensures all bytes are initialized.
202            //
203            // On the one hand, we could extract the top bit from 'first' and
204            // sign-extend just that.  On the other hand, we know that at least
205            // one byte of 'buffer[1]' (which always includes the last byte)
206            // will get overwritten by the later copy.
207            //
208            // This code is likely constant-time, which may be beneficial in
209            // case secret data is being serialized.  But we do not provide any
210            // public guarantees about constant-time operation.
211            let ext = first as i8 as i64;
212            buffer[1].write(ext.to_be_bytes());
213
214            // Fill the remaining bytes.
215            let ptr = buffer[1..1 + num_blocks].as_mut_ptr_range().end.cast::<u8>();
216            unsafe {
217                ptr.sub(value.len())
218                    .copy_from_nonoverlapping(value.as_ptr(), value.len())
219            };
220        } else {
221            // The value is empty; we don't write anything.
222            //
223            // TODO: The spec is a bit ambiguous about whether this is allowed.
224            // How do other TTLV implementations parse this?
225        }
226
227        self.position += 1 + num_blocks;
228        Ok(FormatDone(()))
229    }
230
231    /// Format an enumeration.
232    #[inline]
233    pub fn format_enum(&mut self, tag: Tag, value: u32) -> FormatResult {
234        let header = (tag.with_type(Type::Enumeration).value() as u64) << 32 | 4;
235
236        let buffer = &mut self.buffer[self.position..];
237        let [header_slot, value_slot, ..] = buffer else {
238            return Err(TruncationError);
239        };
240
241        header_slot.write(header.to_be_bytes());
242        value_slot.write(((value as u64) << 32).to_be_bytes());
243        self.position += 2;
244        Ok(FormatDone(()))
245    }
246
247    /// Format a boolean.
248    #[inline]
249    pub fn format_bool(&mut self, tag: Tag, value: bool) -> FormatResult {
250        let header = (tag.with_type(Type::Boolean).value() as u64) << 32 | 8;
251
252        let buffer = &mut self.buffer[self.position..];
253        let [header_slot, value_slot, ..] = buffer else {
254            return Err(TruncationError);
255        };
256
257        header_slot.write(header.to_be_bytes());
258        value_slot.write((value as u64).to_be_bytes());
259        self.position += 2;
260        Ok(FormatDone(()))
261    }
262
263    /// Format a text string.
264    #[inline]
265    pub fn format_text(&mut self, tag: Tag, value: &str) -> FormatResult {
266        let num_blocks = value.len().div_ceil(8);
267        let buffer = &mut self.buffer[self.position..];
268        if buffer.len() < 1 + num_blocks {
269            return Err(TruncationError);
270        }
271
272        let header = tag.with_type(Type::TextString).value();
273        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
274        let length = value.len() as u32;
275        let header = (header as u64) << 32 | length as u64;
276        buffer[0].write(header.to_be_bytes());
277
278        // Make sure the last block is completely initialized.
279        if num_blocks > 0 {
280            buffer[num_blocks].write([0; 8]);
281        }
282        let ptr = buffer[1..].as_mut_ptr().cast::<u8>();
283        unsafe { ptr.copy_from_nonoverlapping(value.as_ptr(), value.len()) };
284
285        self.position += 1 + num_blocks;
286        Ok(FormatDone(()))
287    }
288
289    /// Format a byte string.
290    #[inline]
291    pub fn format_bytes(&mut self, tag: Tag, value: &[u8]) -> FormatResult {
292        let num_blocks = value.len().div_ceil(8);
293        let buffer = &mut self.buffer[self.position..];
294        if buffer.len() < 1 + num_blocks {
295            return Err(TruncationError);
296        }
297
298        let header = tag.with_type(Type::ByteString).value();
299        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
300        let length = value.len() as u32;
301        let header = (header as u64) << 32 | length as u64;
302        buffer[0].write(header.to_be_bytes());
303
304        // Make sure the last block is completely initialized.
305        if num_blocks > 0 {
306            buffer[num_blocks].write([0; 8]);
307        }
308        let ptr = buffer[1..].as_mut_ptr().cast::<u8>();
309        unsafe { ptr.copy_from_nonoverlapping(value.as_ptr(), value.len()) };
310
311        self.position += 1 + num_blocks;
312        Ok(FormatDone(()))
313    }
314
315    /// Format a date-time.
316    #[inline]
317    pub fn format_date_time(&mut self, tag: Tag, value: i64) -> FormatResult {
318        let header = (tag.with_type(Type::DateTime).value() as u64) << 32 | 8;
319
320        let buffer = &mut self.buffer[self.position..];
321        let [header_slot, value_slot, ..] = buffer else {
322            return Err(TruncationError);
323        };
324
325        header_slot.write(header.to_be_bytes());
326        value_slot.write((value as u64).to_be_bytes());
327        self.position += 2;
328        Ok(FormatDone(()))
329    }
330
331    /// Format an interval.
332    #[inline]
333    pub fn format_interval(&mut self, tag: Tag, value: u32) -> FormatResult {
334        let header = (tag.with_type(Type::Interval).value() as u64) << 32 | 4;
335
336        let buffer = &mut self.buffer[self.position..];
337        let [header_slot, value_slot, ..] = buffer else {
338            return Err(TruncationError);
339        };
340
341        header_slot.write(header.to_be_bytes());
342        value_slot.write(((value as u64) << 32).to_be_bytes());
343        self.position += 2;
344        Ok(FormatDone(()))
345    }
346}
347
348//----------- FieldFormatter -------------------------------------------------
349
350/// A [`Formatter`] for filling a particular TTLV field.
351///
352/// A [`Formatter`] can delegate to a [`FieldFormatter`] to format a TTLV
353/// field such as a structure.  This provides an incremental API to fill the
354/// field.
355pub struct FieldFormatter<'f> {
356    /// The position of the outer formatter.
357    outer_pos: &'f mut usize,
358
359    /// The header slot.
360    ///
361    /// The length of the created field will be written here.  The tag and type
362    /// (i.e. the top 4 bytes) are already initialized.
363    header: &'f mut [u8; 8],
364
365    /// The inner formatter.
366    ///
367    /// This formatter borrows its buffer from the outer one.
368    inner: Formatter<'f>,
369}
370
371impl FieldFormatter<'_> {
372    /// Successfully finish formatting.
373    pub fn finish(self) -> FormatDone {
374        // Update the length of the field.
375        let length = self.inner.position;
376        // This is guaranteed by invariant 'size': since the input buffer is at
377        // most 4GiB, and we are writing an 8-byte TTL header (whose length does
378        // not include itself), we are encoding a length of at most 2^32 - 8.
379        debug_assert!(length * 8 <= u32::MAX as usize);
380        let length = (length * 8) as u32;
381        self.header[4..].copy_from_slice(&length.to_be_bytes());
382
383        // Update the position of the outer formatter.
384        *self.outer_pos += 1 + self.inner.position;
385
386        FormatDone(())
387    }
388}
389
390impl<'f> Deref for FieldFormatter<'f> {
391    type Target = Formatter<'f>;
392
393    fn deref(&self) -> &Self::Target {
394        &self.inner
395    }
396}
397
398impl<'f> DerefMut for FieldFormatter<'f> {
399    fn deref_mut(&mut self) -> &mut Self::Target {
400        &mut self.inner
401    }
402}
403
404//----------- FormatResult ---------------------------------------------------
405
406/// The result of formatting a field.
407pub type FormatResult = Result<FormatDone, TruncationError>;
408
409//----------- FormatDone -----------------------------------------------------
410
411/// A token showing that formatting completed successfully.
412///
413/// This is an opaque struct instead of a simple alias to `()`, to prevent users
414/// from creating it without understanding the implications of doing so.  It is
415/// usually incorrect to create this token yourself.
416pub struct FormatDone(());
417
418impl FormatDone {
419    /// Manually assert that formatting is complete.
420    ///
421    /// It is not recommended to call this yourself; a [`FormatDone`] will be
422    /// provided to you by the primitive formatting methods, as well as
423    /// [`FieldFormatter::finish()`].
424    pub const fn assert() -> Self {
425        Self(())
426    }
427}
428
429//----------- TruncationError ------------------------------------------------
430
431/// A [`Formatter`] ran out of space to serialize TTLV data.
432#[derive(Clone, PartialEq, Eq)]
433pub struct TruncationError;
434
435impl std::error::Error for TruncationError {}
436
437impl fmt::Debug for TruncationError {
438    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439        fmt::Display::fmt(self, f)
440    }
441}
442
443impl fmt::Display for TruncationError {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        f.write_str("ran out of space while serializing TTLV data")
446    }
447}