thruput-xdrs 0.17.1

XDR Serialization Library
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Const-compatible CXS encoding.
//!
//! This module provides [`ConstWriter`], which encodes CXS data into a
//! fixed-size buffer in `const` contexts, along with `size_*` functions
//! that compute the encoded size of each primitive type and `max_size_*`
//! functions that compute worst-case size bounds over all values.

/// A const-compatible writer for CXS (Compact XDR Serialization).
///
/// All methods panic on buffer overflow. In a `const` context, this
/// produces a compile-time error.
///
/// Use [`into_bytes`](Self::into_bytes) to extract the final buffer,
/// which panics if the writer has not filled the buffer exactly.
pub struct ConstWriter<const N: usize> {
    buf: [u8; N],
    pos: usize,
}

// CXS encoding constants (mirrors cxs::limits and cxs::put)
const V_MULTIBYTE: u8 = 63;
const S_8BYTE: u8 = 3 << 6;
const S_4BYTE: u8 = 2 << 6;
const S_2BYTE: u8 = 1 << 6;
const S_1BYTE: u8 = 0 << 6;
const S_HEADER: u8 = 0 << 6;

const IH_MAX: i8 = 31;
const IH_MIN: i8 = -31;
const UH_MAX: u8 = 62;

impl<const N: usize> Default for ConstWriter<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> ConstWriter<N> {
    /// Creates a new writer with a zeroed buffer.
    pub const fn new() -> Self {
        Self {
            buf: [0u8; N],
            pos: 0,
        }
    }

    /// Returns the number of bytes written so far.
    pub const fn pos(&self) -> usize {
        self.pos
    }

    /// Consumes the writer and returns the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the number of bytes written does not equal `N`.
    pub const fn into_bytes(self) -> [u8; N] {
        assert!(
            self.pos == N,
            "ConstWriter: bytes written does not equal buffer size N"
        );
        self.buf
    }

    // -- internal helpers --

    const fn put_byte(&mut self, b: u8) {
        self.buf[self.pos] = b;
        self.pos += 1;
    }

    const fn put_bytes(&mut self, bytes: &[u8]) {
        let mut i = 0;
        while i < bytes.len() {
            self.buf[self.pos + i] = bytes[i];
            i += 1;
        }
        self.pos += bytes.len();
    }

    // -- opaque writes --

    #[doc(hidden)]
    pub const fn write_opaque_fixed(&mut self, bytes: &[u8]) {
        assert!(
            bytes.len() <= u32::MAX as usize,
            "opaque length exceeds u32::MAX"
        );
        self.put_bytes(bytes);
    }

    /// Writes variable-length opaque data: CXS-encoded u32 length prefix,
    /// then raw bytes.
    pub const fn write_opaque_variable(&mut self, bytes: &[u8]) {
        assert!(
            bytes.len() <= u32::MAX as usize,
            "opaque length exceeds u32::MAX"
        );
        self.write_u32(bytes.len() as u32);
        self.put_bytes(bytes);
    }

    // -- integer writes --

    /// Writes a boolean as CXS-encoded i32 (0 or 1).
    pub const fn write_bool(&mut self, v: bool) {
        self.write_i32(if v { 1 } else { 0 });
    }

    /// Writes a 32-bit IEEE 754 float as raw little-endian bytes (4 bytes).
    ///
    /// Unlike integers, floats are not compressed with CXS variable-width
    /// encoding — the bit pattern is written as-is. Little-endian byte order
    /// follows CXS convention (not RFC 4506 big-endian).
    pub const fn write_f32(&mut self, n: f32) {
        let b = n.to_le_bytes();
        self.put_bytes(&b);
    }

    /// Writes a 64-bit IEEE 754 double as raw little-endian bytes (8 bytes).
    ///
    /// Unlike integers, floats are not compressed with CXS variable-width
    /// encoding — the bit pattern is written as-is. Little-endian byte order
    /// follows CXS convention (not RFC 4506 big-endian).
    pub const fn write_f64(&mut self, n: f64) {
        let b = n.to_le_bytes();
        self.put_bytes(&b);
    }

    /// Writes a signed 64-bit integer using CXS variable-width encoding.
    pub const fn write_i64(&mut self, n: i64) {
        if n > i32::MAX as i64 || n < (i32::MIN as i64) {
            let h = V_MULTIBYTE | S_8BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]];
            self.put_bytes(&combined);
        } else {
            self.write_i32(n as i32);
        }
    }

    /// Writes a signed 32-bit integer using CXS variable-width encoding.
    pub const fn write_i32(&mut self, n: i32) {
        if n > i16::MAX as i32 || n < (i16::MIN as i32) {
            let h = V_MULTIBYTE | S_4BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1], b[2], b[3]];
            self.put_bytes(&combined);
        } else {
            self.write_i16(n as i16);
        }
    }

    /// Writes a signed 16-bit integer using CXS variable-width encoding.
    pub const fn write_i16(&mut self, n: i16) {
        if n > i8::MAX as i16 || n < (i8::MIN as i16) {
            let h = V_MULTIBYTE | S_2BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1]];
            self.put_bytes(&combined);
        } else {
            self.const_write_i8(n as i8);
        }
    }

    const fn const_write_i8(&mut self, n: i8) {
        if n < IH_MIN || n > IH_MAX {
            let h = V_MULTIBYTE | S_1BYTE;
            let combined = [h, n as u8];
            self.put_bytes(&combined);
        } else {
            // 6-bit one's complement in header byte
            let nu: u8 = n.unsigned_abs();
            let v = if n >= 0 {
                nu
            } else {
                (!nu & 0b01_1111) | 0b0010_0000
            };
            let h = v | S_HEADER;
            self.put_byte(h);
        }
    }

    /// Writes a signed 128-bit integer as `(i64, u64)` using CXS variable-width encoding.
    #[cfg(feature = "int128")]
    #[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
    pub const fn write_i128(&mut self, n: i128) {
        self.write_i64((n >> 64) as i64);
        self.write_u64((n & 0xffffffffffffffff) as u64);
    }

    /// Writes an unsigned 128-bit integer as `(u64, u64)` using CXS variable-width encoding.
    #[cfg(feature = "int128")]
    #[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
    pub const fn write_u128(&mut self, n: u128) {
        self.write_u64((n >> 64) as u64);
        self.write_u64((n & 0xffffffffffffffff) as u64);
    }

    /// Writes an unsigned 64-bit integer using CXS variable-width encoding.
    pub const fn write_u64(&mut self, n: u64) {
        if n > u32::MAX as u64 {
            let h = V_MULTIBYTE | S_8BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]];
            self.put_bytes(&combined);
        } else {
            self.write_u32(n as u32);
        }
    }

    /// Writes an unsigned 32-bit integer using CXS variable-width encoding.
    pub const fn write_u32(&mut self, n: u32) {
        if n > u16::MAX as u32 {
            let h = V_MULTIBYTE | S_4BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1], b[2], b[3]];
            self.put_bytes(&combined);
        } else {
            self.write_u16(n as u16);
        }
    }

    /// Writes an unsigned 16-bit integer using CXS variable-width encoding.
    pub const fn write_u16(&mut self, n: u16) {
        if n > u8::MAX as u16 {
            let h = V_MULTIBYTE | S_2BYTE;
            let b = n.to_le_bytes();
            let combined = [h, b[0], b[1]];
            self.put_bytes(&combined);
        } else {
            self.const_write_u8(n as u8);
        }
    }

    const fn const_write_u8(&mut self, n: u8) {
        if n > UH_MAX {
            let h = V_MULTIBYTE | S_1BYTE;
            let combined = [h, n];
            self.put_bytes(&combined);
        } else {
            self.put_byte(n);
        }
    }
}

// -- Size calculation helpers --
// These are free functions usable in const contexts to compute CXS encoded sizes.
// Sizes are value-dependent due to variable-width encoding.

/// Returns the CXS encoded size of a boolean (encoded as i32).
pub const fn size_bool(v: bool) -> usize {
    size_i32(if v { 1 } else { 0 })
}

/// Returns the CXS encoded size of a 32-bit float (always 4).
pub const fn size_f32(_n: f32) -> usize {
    4
}

/// Returns the CXS encoded size of a 64-bit double (always 8).
pub const fn size_f64(_n: f64) -> usize {
    8
}

/// Returns the CXS encoded size of a signed 64-bit integer.
pub const fn size_i64(n: i64) -> usize {
    if n > i32::MAX as i64 || n < (i32::MIN as i64) {
        9 // 1 header + 8 data
    } else {
        size_i32(n as i32)
    }
}

/// Returns the CXS encoded size of a signed 32-bit integer.
pub const fn size_i32(n: i32) -> usize {
    if n > i16::MAX as i32 || n < (i16::MIN as i32) {
        5 // 1 header + 4 data
    } else {
        size_i16(n as i16)
    }
}

/// Returns the CXS encoded size of a signed 16-bit integer.
pub const fn size_i16(n: i16) -> usize {
    if n > i8::MAX as i16 || n < (i8::MIN as i16) {
        3 // 1 header + 2 data
    } else {
        size_i8(n as i8)
    }
}

const fn size_i8(n: i8) -> usize {
    if n < IH_MIN || n > IH_MAX {
        2 // 1 header + 1 data
    } else {
        1 // header only
    }
}

/// Returns the CXS encoded size of a signed 128-bit integer.
#[cfg(feature = "int128")]
#[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
pub const fn size_i128(n: i128) -> usize {
    size_i64((n >> 64) as i64) + size_u64((n & 0xffffffffffffffff) as u64)
}

/// Returns the CXS encoded size of an unsigned 128-bit integer.
#[cfg(feature = "int128")]
#[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
pub const fn size_u128(n: u128) -> usize {
    size_u64((n >> 64) as u64) + size_u64((n & 0xffffffffffffffff) as u64)
}

/// Returns the CXS encoded size of an unsigned 64-bit integer.
pub const fn size_u64(n: u64) -> usize {
    if n > u32::MAX as u64 {
        9
    } else {
        size_u32(n as u32)
    }
}

/// Returns the CXS encoded size of an unsigned 32-bit integer.
pub const fn size_u32(n: u32) -> usize {
    if n > u16::MAX as u32 {
        5
    } else {
        size_u16(n as u16)
    }
}

/// Returns the CXS encoded size of an unsigned 16-bit integer.
pub const fn size_u16(n: u16) -> usize {
    if n > u8::MAX as u16 {
        3
    } else {
        size_u8(n as u8)
    }
}

const fn size_u8(n: u8) -> usize {
    if n > UH_MAX { 2 } else { 1 }
}

/// Returns the CXS encoded size of fixed-length opaque data (raw bytes, no padding).
pub const fn size_opaque_fixed(len: usize) -> usize {
    assert!(len <= u32::MAX as usize, "opaque length exceeds u32::MAX");
    len
}

/// Returns the CXS encoded size of variable-length opaque data
/// (CXS-encoded u32 length prefix + raw bytes).
pub const fn size_opaque_variable(len: usize) -> usize {
    assert!(len <= u32::MAX as usize, "opaque length exceeds u32::MAX");
    size_u32(len as u32) + len
}

// -- Worst-case size helpers --
// Type-level maximums over all values of a type, used by
// `#[derive(ConstXDRSize)]` to fold `ConstMaxSize::MAX_SIZE` bounds.
// `None` means unbounded, or a bound that overflows `usize` on this target.

/// Worst-case CXS encoded size of a boolean (always 1: header byte only).
pub const fn max_size_bool() -> usize {
    1
}

/// Worst-case CXS encoded size of a 32-bit float (always 4).
pub const fn max_size_f32() -> usize {
    4
}

/// Worst-case CXS encoded size of a 64-bit double (always 8).
pub const fn max_size_f64() -> usize {
    8
}

/// Worst-case CXS encoded size of a signed 16-bit integer (1 header + 2 data).
pub const fn max_size_i16() -> usize {
    3
}

/// Worst-case CXS encoded size of an unsigned 16-bit integer (1 header + 2 data).
pub const fn max_size_u16() -> usize {
    3
}

/// Worst-case CXS encoded size of a signed 32-bit integer (1 header + 4 data).
pub const fn max_size_i32() -> usize {
    5
}

/// Worst-case CXS encoded size of an unsigned 32-bit integer (1 header + 4 data).
pub const fn max_size_u32() -> usize {
    5
}

/// Worst-case CXS encoded size of a signed 64-bit integer (1 header + 8 data).
pub const fn max_size_i64() -> usize {
    9
}

/// Worst-case CXS encoded size of an unsigned 64-bit integer (1 header + 8 data).
pub const fn max_size_u64() -> usize {
    9
}

/// Worst-case CXS encoded size of a signed 128-bit integer (two 64-bit halves).
#[cfg(feature = "int128")]
#[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
pub const fn max_size_i128() -> usize {
    18
}

/// Worst-case CXS encoded size of an unsigned 128-bit integer (two 64-bit halves).
#[cfg(feature = "int128")]
#[cfg_attr(docsrs, doc(cfg(feature = "int128")))]
pub const fn max_size_u128() -> usize {
    18
}

/// Worst-case CXS encoded size of fixed-length opaque data, or `None` if the
/// length exceeds `u32::MAX` (such data can never be encoded).
pub const fn max_size_opaque_fixed(len: usize) -> Option<usize> {
    if len > u32::MAX as usize {
        None
    } else {
        Some(len)
    }
}

/// Worst-case CXS encoded size of variable-length opaque data with declared
/// bound `max_len`, or `None` if the bound overflows `usize` on this target.
pub const fn max_size_opaque_variable(max_len: u32) -> Option<usize> {
    size_u32(max_len).checked_add(max_len as usize)
}

/// Adds two size bounds. `None` (unbounded) and `usize` overflow propagate.
pub const fn max_size_add(a: Option<usize>, b: Option<usize>) -> Option<usize> {
    match (a, b) {
        (Some(a), Some(b)) => a.checked_add(b),
        _ => None,
    }
}

/// Takes the larger of two size bounds. `None` (unbounded) propagates.
pub const fn max_size_max(a: Option<usize>, b: Option<usize>) -> Option<usize> {
    match (a, b) {
        (Some(a), Some(b)) => Some(if a > b { a } else { b }),
        _ => None,
    }
}

/// Multiplies an element size bound by a fixed array length. `None` if the
/// element is unbounded, the product overflows `usize`, or the length exceeds
/// `u32::MAX` (such arrays can never be encoded). A zero-length array encodes
/// zero bytes regardless of its element type.
pub const fn max_size_array(len: usize, elem: Option<usize>) -> Option<usize> {
    if len == 0 {
        return Some(0);
    }
    if len > u32::MAX as usize {
        return None;
    }
    match elem {
        Some(elem) => elem.checked_mul(len),
        None => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Small values fit in header byte
    const SMALL_INTS: [u8; 4] = {
        let mut w = ConstWriter::<4>::new();
        w.write_i32(0); // 0x00
        w.write_i32(31); // 0x1f
        w.write_i32(-1); // 0x3e
        w.write_i32(1); // 0x01
        w.into_bytes()
    };

    #[test]
    fn const_encode_small_ints() {
        assert_eq!(SMALL_INTS, [0x00, 0x1f, 0x3e, 0x01]);
    }

    // Values outside i8 range use 2-byte encoding
    const TWO_BYTE: [u8; 3] = {
        let mut w = ConstWriter::<3>::new();
        w.write_i32(-32); // 0x3f 0xe0
        w.write_i32(1); // 0x01
        w.into_bytes()
    };

    #[test]
    fn const_encode_two_byte() {
        assert_eq!(TWO_BYTE, [0x3f, 0xe0, 0x01]);
    }

    // 4-byte encoding for values outside i16 range
    const FOUR_BYTE: [u8; 5] = {
        let mut w = ConstWriter::<5>::new();
        w.write_i32(i32::MAX);
        w.into_bytes()
    };

    #[test]
    fn const_encode_four_byte() {
        assert_eq!(FOUR_BYTE, [0xbf, 0xff, 0xff, 0xff, 0x7f]);
    }

    // Unsigned: u32 deadbeef
    const U32_DB: [u8; 5] = {
        let mut w = ConstWriter::<5>::new();
        w.write_u32(4022250974); // 0xEFBEADDE (LE bytes spell out 0xdeadbeef)
        w.into_bytes()
    };

    #[test]
    fn const_encode_u32_deadbeef() {
        assert_eq!(U32_DB, [0xbf, 0xde, 0xad, 0xbe, 0xef]);
    }

    // 8-byte encoding for i64
    const I64_MAX: [u8; 9] = {
        let mut w = ConstWriter::<9>::new();
        w.write_i64(i64::MAX);
        w.into_bytes()
    };

    #[test]
    fn const_encode_i64_max() {
        assert_eq!(
            I64_MAX,
            [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]
        );
    }

    // Opaque variable: CXS encodes length 2 as single byte 0x02, then "hi"
    const OPAQUE: [u8; 3] = {
        let mut w = ConstWriter::<3>::new();
        w.write_opaque_variable(b"hi");
        w.into_bytes()
    };

    #[test]
    fn const_encode_opaque_variable() {
        assert_eq!(OPAQUE, [0x02, 0x68, 0x69]);
    }

    const BOOL_TRUE: [u8; 1] = {
        let mut w = ConstWriter::<1>::new();
        w.write_bool(true);
        w.into_bytes()
    };

    #[test]
    fn const_encode_bool() {
        assert_eq!(BOOL_TRUE, [0x01]);
    }

    #[test]
    fn max_sizes_dominate_worst_case_values() {
        assert_eq!(max_size_i16(), size_i16(i16::MAX));
        assert_eq!(max_size_u16(), size_u16(u16::MAX));
        assert_eq!(max_size_i32(), size_i32(i32::MAX));
        assert_eq!(max_size_u32(), size_u32(u32::MAX));
        assert_eq!(max_size_i64(), size_i64(i64::MAX));
        assert_eq!(max_size_u64(), size_u64(u64::MAX));
        assert_eq!(max_size_bool(), size_bool(true));
        assert_eq!(max_size_f32(), size_f32(0.0));
        assert_eq!(max_size_f64(), size_f64(0.0));
    }

    #[cfg(feature = "int128")]
    #[test]
    fn max_sizes_dominate_worst_case_int128() {
        assert_eq!(max_size_i128(), size_i128(i128::MAX));
        assert_eq!(max_size_u128(), size_u128(u128::MAX));
    }

    #[test]
    fn max_size_opaque() {
        assert_eq!(max_size_opaque_fixed(0), Some(0));
        assert_eq!(max_size_opaque_fixed(7), Some(7));
        assert_eq!(max_size_opaque_variable(2), Some(size_opaque_variable(2)));
        #[cfg(target_pointer_width = "64")]
        {
            assert_eq!(
                max_size_opaque_variable(u32::MAX),
                Some(5 + u32::MAX as usize)
            );
        }
    }

    #[test]
    fn max_size_folds() {
        assert_eq!(max_size_add(Some(3), Some(4)), Some(7));
        assert_eq!(max_size_add(Some(3), None), None);
        assert_eq!(max_size_add(None, Some(4)), None);
        assert_eq!(max_size_add(Some(usize::MAX), Some(1)), None);
        assert_eq!(max_size_max(Some(3), Some(4)), Some(4));
        assert_eq!(max_size_max(Some(3), None), None);
        assert_eq!(max_size_array(4, Some(9)), Some(36));
        assert_eq!(max_size_array(0, Some(9)), Some(0));
        // A zero-length array encodes nothing, even of unbounded elements.
        assert_eq!(max_size_array(0, None), Some(0));
        assert_eq!(max_size_array(4, None), None);
        #[cfg(target_pointer_width = "64")]
        assert_eq!(max_size_array(usize::MAX, Some(1)), None);
        assert_eq!(max_size_array(2, Some(usize::MAX)), None);
    }
}