kmip-protocol 0.5.1

KMIP protocol object (de)serialization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Serializing TTLV elements.
//!
//! This module provides low-level TTLV serialization support.  It is entirely
//! manual -- it does not provide a declarative interface.  It is designed for
//! fast, streaming operation.

use core::{
    fmt,
    mem::{MaybeUninit, transmute},
    ops::{Deref, DerefMut},
};

use super::types::{Tag, Type};

//----------- Formatter ------------------------------------------------------

/// A TTLV formatter.
///
/// ## Panics
///
/// TTLV uses 32-bit fields to express the size of serialized data, in units of
/// bytes.  To guarantee panic-free operation, only the first 4GiB of a given
/// input buffer will be used.  A write that would overflow a length field is
/// guaranteed to return [`TruncationError`] instead.
pub struct Formatter<'b> {
    /// The buffer to write into.
    ///
    /// - Invariant `size`:
    ///   `buffer.as_flattened().len() <= 2^32`.
    buffer: &'b mut [MaybeUninit<[u8; 8]>],

    /// The current position into the buffer.
    ///
    /// - Invariant `initialized`:
    ///   `self.buffer[..self.position]` is initialized.
    ///
    /// - Invariant `coherent-position`:
    ///   `self.position <= self.buffer.len()`.
    position: usize,
}

impl<'b> Formatter<'b> {
    /// Construct a new [`Formatter`].
    ///
    /// The input will be truncated to the first 4GiB, and to a multiple of 8
    /// bytes, as per limitations of the TTLV format.  It should ideally be
    /// aligned to an 8-byte address boundary (for better performance).
    pub const fn new(buffer: &'b mut [MaybeUninit<u8>]) -> Self {
        let mut num_blocks = buffer.len() / 8;

        // Equivalent to 'buffer.len() >= 2^32'.  If 'usize' is smaller than
        // 'u32', this is equivalent to 'buffer.len() > usize::MAX', which is
        // trivially false.
        if buffer.len() > u32::MAX as usize {
            num_blocks = 1usize << 29;
        }

        let ptr = buffer.as_mut_ptr().cast::<MaybeUninit<[u8; 8]>>();
        let buffer = unsafe { core::slice::from_raw_parts_mut(ptr, num_blocks) };

        Self { buffer, position: 0 }
    }

    /// Construct a new [`Formatter`] from its raw parts.
    ///
    /// ## Safety
    ///
    /// `Formatter::from_raw_parts(buffer, position)` is sound if and only if:
    /// - `position <= buffer.len()`.
    /// - `buffer[..position]` is initialized.
    /// - `buffer.len() * 8 <= 2^32`.
    pub const unsafe fn from_raw_parts(buffer: &'b mut [MaybeUninit<[u8; 8]>], position: usize) -> Self {
        debug_assert!(position <= buffer.len());
        debug_assert!(usize::BITS <= u32::BITS || buffer.len() <= (1usize << 29));
        Self { buffer, position }
    }

    pub fn clear(&mut self) {
        self.position = 0;
    }

    /// The filled part of the buffer.
    pub fn filled(&self) -> &[[u8; 8]] {
        unsafe {
            let blocks = self.buffer.get_unchecked(..self.position);
            transmute::<&[MaybeUninit<[u8; 8]>], &[[u8; 8]]>(blocks)
        }
    }

    /// The filled part of the buffer, mutably.
    pub fn filled_mut(&mut self) -> &mut [[u8; 8]] {
        unsafe {
            let blocks = self.buffer.get_unchecked_mut(..self.position);
            transmute::<&mut [MaybeUninit<[u8; 8]>], &mut [[u8; 8]]>(blocks)
        }
    }

    /// The remaining part of the buffer.
    pub fn remaining(&mut self) -> &mut [MaybeUninit<[u8; 8]>] {
        unsafe { self.buffer.get_unchecked_mut(self.position..) }
    }

    /// Destructure a [`Formatter`] into its raw parts.
    ///
    /// ## Invariants
    ///
    /// For `(buffer, position) = self.into_raw_parts()`:
    /// - Invariant `coherent-position`: `position <= buffer.len()`.
    /// - Invariant `initialized`: `buffer[..position]` is initialized.
    /// - Invariant `size`: `buffer.as_flattened().len() <= 2^32`.
    pub const fn into_raw_parts(self) -> (&'b mut [MaybeUninit<[u8; 8]>], usize) {
        (self.buffer, self.position)
    }
}

impl<'b> Formatter<'b> {
    /// Format a structure.
    ///
    /// The returned sub-formatter should be used to format the fields of the
    /// `struct`; once it is finished, `self` can continue.
    #[must_use = "Use the returned formatter to fill the structure, and call `.finish()` when it is ready"]
    #[inline]
    pub fn format_struct(&mut self, tag: Tag) -> Result<FieldFormatter<'_>, TruncationError> {
        // Can't use 'self.remaining()', would borrow more than '.buffer'.
        let buffer = &mut self.buffer[self.position..];
        let (header_slot, rest) = buffer.split_first_mut().ok_or(TruncationError)?;

        // Write the field header.
        let header = (tag.with_type(Type::Structure).value() as u64) << 32;
        let header = header_slot.write(header.to_be_bytes());

        Ok(FieldFormatter {
            outer_pos: &mut self.position,
            header,
            inner: Formatter {
                buffer: rest,
                position: 0,
            },
        })
    }

    /// Format an integer.
    #[inline]
    pub fn format_int(&mut self, tag: Tag, value: i32) -> FormatResult {
        let header = (tag.with_type(Type::Integer).value() as u64) << 32 | 4;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write(((value as u32 as u64) << 32).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }

    /// Format a long integer.
    #[inline]
    pub fn format_long_int(&mut self, tag: Tag, value: i64) -> FormatResult {
        let header = (tag.with_type(Type::LongInteger).value() as u64) << 32 | 8;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write((value as u64).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }

    /// Format a big integer.
    ///
    /// `value` should be the bytewise digits of a signed (two's complement)
    /// big-endian integer.  It will be padded (with leading sign-extension
    /// bytes) into a multiple of 8 bytes before being stored.
    ///
    /// # Panics
    ///
    /// Panics if the length of `value` (when rounded up to a multiple of 8
    /// bytes) does not fit in a `u32`.
    #[inline]
    pub fn format_big_int(&mut self, tag: Tag, value: &[u8]) -> FormatResult {
        let num_blocks = value.len().div_ceil(8);
        let buffer = &mut self.buffer[self.position..];
        if buffer.len() < 1 + num_blocks {
            return Err(TruncationError);
        }

        let header = tag.with_type(Type::BigInteger).value();
        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
        let length = (value.len() as u32).next_multiple_of(8);
        let header = (header as u64) << 32 | length as u64;
        buffer[0].write(header.to_be_bytes());

        if let &[first, ..] = value {
            // Fill the first 8 bytes by sign extension.
            //
            // This also ensures all bytes are initialized.
            //
            // On the one hand, we could extract the top bit from 'first' and
            // sign-extend just that.  On the other hand, we know that at least
            // one byte of 'buffer[1]' (which always includes the last byte)
            // will get overwritten by the later copy.
            //
            // This code is likely constant-time, which may be beneficial in
            // case secret data is being serialized.  But we do not provide any
            // public guarantees about constant-time operation.
            let ext = first as i8 as i64;
            buffer[1].write(ext.to_be_bytes());

            // Fill the remaining bytes.
            let ptr = buffer[1..1 + num_blocks].as_mut_ptr_range().end.cast::<u8>();
            unsafe {
                ptr.sub(value.len())
                    .copy_from_nonoverlapping(value.as_ptr(), value.len())
            };
        } else {
            // The value is empty; we don't write anything.
            //
            // TODO: The spec is a bit ambiguous about whether this is allowed.
            // How do other TTLV implementations parse this?
        }

        self.position += 1 + num_blocks;
        Ok(FormatDone(()))
    }

    /// Format an enumeration.
    #[inline]
    pub fn format_enum(&mut self, tag: Tag, value: u32) -> FormatResult {
        let header = (tag.with_type(Type::Enumeration).value() as u64) << 32 | 4;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write(((value as u64) << 32).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }

    /// Format a boolean.
    #[inline]
    pub fn format_bool(&mut self, tag: Tag, value: bool) -> FormatResult {
        let header = (tag.with_type(Type::Boolean).value() as u64) << 32 | 8;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write((value as u64).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }

    /// Format a text string.
    #[inline]
    pub fn format_text(&mut self, tag: Tag, value: &str) -> FormatResult {
        let num_blocks = value.len().div_ceil(8);
        let buffer = &mut self.buffer[self.position..];
        if buffer.len() < 1 + num_blocks {
            return Err(TruncationError);
        }

        let header = tag.with_type(Type::TextString).value();
        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
        let length = value.len() as u32;
        let header = (header as u64) << 32 | length as u64;
        buffer[0].write(header.to_be_bytes());

        // Make sure the last block is completely initialized.
        if num_blocks > 0 {
            buffer[num_blocks].write([0; 8]);
        }
        let ptr = buffer[1..].as_mut_ptr().cast::<u8>();
        unsafe { ptr.copy_from_nonoverlapping(value.as_ptr(), value.len()) };

        self.position += 1 + num_blocks;
        Ok(FormatDone(()))
    }

    /// Format a byte string.
    #[inline]
    pub fn format_bytes(&mut self, tag: Tag, value: &[u8]) -> FormatResult {
        let num_blocks = value.len().div_ceil(8);
        let buffer = &mut self.buffer[self.position..];
        if buffer.len() < 1 + num_blocks {
            return Err(TruncationError);
        }

        let header = tag.with_type(Type::ByteString).value();
        // NOTE: 'buffer.len() * 8 <= 2^32' so 'num_blocks * 8 < 2^32'.
        let length = value.len() as u32;
        let header = (header as u64) << 32 | length as u64;
        buffer[0].write(header.to_be_bytes());

        // Make sure the last block is completely initialized.
        if num_blocks > 0 {
            buffer[num_blocks].write([0; 8]);
        }
        let ptr = buffer[1..].as_mut_ptr().cast::<u8>();
        unsafe { ptr.copy_from_nonoverlapping(value.as_ptr(), value.len()) };

        self.position += 1 + num_blocks;
        Ok(FormatDone(()))
    }

    /// Format a date-time.
    #[inline]
    pub fn format_date_time(&mut self, tag: Tag, value: i64) -> FormatResult {
        let header = (tag.with_type(Type::DateTime).value() as u64) << 32 | 8;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write((value as u64).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }

    /// Format an interval.
    #[inline]
    pub fn format_interval(&mut self, tag: Tag, value: u32) -> FormatResult {
        let header = (tag.with_type(Type::Interval).value() as u64) << 32 | 4;

        let buffer = &mut self.buffer[self.position..];
        let [header_slot, value_slot, ..] = buffer else {
            return Err(TruncationError);
        };

        header_slot.write(header.to_be_bytes());
        value_slot.write(((value as u64) << 32).to_be_bytes());
        self.position += 2;
        Ok(FormatDone(()))
    }
}

//----------- FieldFormatter -------------------------------------------------

/// A [`Formatter`] for filling a particular TTLV field.
///
/// A [`Formatter`] can delegate to a [`FieldFormatter`] to format a TTLV
/// field such as a structure.  This provides an incremental API to fill the
/// field.
pub struct FieldFormatter<'f> {
    /// The position of the outer formatter.
    outer_pos: &'f mut usize,

    /// The header slot.
    ///
    /// The length of the created field will be written here.  The tag and type
    /// (i.e. the top 4 bytes) are already initialized.
    header: &'f mut [u8; 8],

    /// The inner formatter.
    ///
    /// This formatter borrows its buffer from the outer one.
    inner: Formatter<'f>,
}

impl FieldFormatter<'_> {
    /// Successfully finish formatting.
    pub fn finish(self) -> FormatDone {
        // Update the length of the field.
        let length = self.inner.position;
        // This is guaranteed by invariant 'size': since the input buffer is at
        // most 4GiB, and we are writing an 8-byte TTL header (whose length does
        // not include itself), we are encoding a length of at most 2^32 - 8.
        debug_assert!(length * 8 <= u32::MAX as usize);
        let length = (length * 8) as u32;
        self.header[4..].copy_from_slice(&length.to_be_bytes());

        // Update the position of the outer formatter.
        *self.outer_pos += 1 + self.inner.position;

        FormatDone(())
    }
}

impl<'f> Deref for FieldFormatter<'f> {
    type Target = Formatter<'f>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'f> DerefMut for FieldFormatter<'f> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

//----------- FormatResult ---------------------------------------------------

/// The result of formatting a field.
pub type FormatResult = Result<FormatDone, TruncationError>;

//----------- FormatDone -----------------------------------------------------

/// A token showing that formatting completed successfully.
///
/// This is an opaque struct instead of a simple alias to `()`, to prevent users
/// from creating it without understanding the implications of doing so.  It is
/// usually incorrect to create this token yourself.
pub struct FormatDone(());

impl FormatDone {
    /// Manually assert that formatting is complete.
    ///
    /// It is not recommended to call this yourself; a [`FormatDone`] will be
    /// provided to you by the primitive formatting methods, as well as
    /// [`FieldFormatter::finish()`].
    pub const fn assert() -> Self {
        Self(())
    }
}

//----------- TruncationError ------------------------------------------------

/// A [`Formatter`] ran out of space to serialize TTLV data.
#[derive(Clone, PartialEq, Eq)]
pub struct TruncationError;

impl std::error::Error for TruncationError {}

impl fmt::Debug for TruncationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for TruncationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ran out of space while serializing TTLV data")
    }
}