musli 0.0.149

Müsli is a flexible and efficient serialization framework.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Serialization options.

use core::fmt;

/// [`Options`] builder.
pub struct Builder(Options);

const DEFAULT: Options = (ByteOrder::Little as Options) << BYTEORDER_BIT;

/// Start building new options.
///
/// Call [`Builder::build`] to construct them.
///
/// # Examples
///
/// ```
/// use musli::options::{self, Integer, Options};
///
/// const OPTIONS: Options = options::new().integer(Integer::Fixed).build();
/// ```
#[inline]
pub const fn new() -> Builder {
    Builder(DEFAULT)
}

/// Construct a [`Builder`] from the raw underlying value of an [`Options`].
///
/// This can be used to modify a value at compile time.
///
/// # Examples
///
/// ```
/// use musli::options::{self, Float, Options};
///
/// const BASE: Options = options::new().build();
/// const MODIFIED: Options = options::from_raw(BASE).float(Float::Fixed).build();
/// ```
#[inline]
pub const fn from_raw(value: Options) -> Builder {
    Builder(value)
}

/// Type encapsulating a static options for an encoding.
///
/// Note: despite being made up of a primitive type, this cannot be serialized
/// and correctly re-used. This is simply the case because of restrictions in
/// constant evaluation.
///
/// Making assumptions about its layout might lead to unspecified behavior
/// during encoding. Only use this type through the provided [`options`] APIs.
///
/// [`options`]: crate::options
pub type Options = u32;

const BYTEORDER_BIT: Options = 0;
const INTEGER_BIT: Options = 4;
const FLOAT_BIT: Options = 8;
const LENGTH_BIT: Options = 12;
const MAP_KEYS_AS_NUMBERS_BIT: Options = 16;

impl Builder {
    /// Indicates if an integer serialization should be variable.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Integer, Options};
    ///
    /// const OPTIONS: Options = options::new().integer(Integer::Fixed).build();
    /// ```
    #[inline]
    pub const fn integer(self, integer: Integer) -> Self {
        const MASK: Options = Integer::MASK << INTEGER_BIT;
        Self((self.0 & !MASK) | ((integer as Options) << INTEGER_BIT))
    }

    /// Indicates the configuration of float serialization.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Float, Options};
    ///
    /// const OPTIONS: Options = options::new().float(Float::Fixed).build();
    /// ```
    #[inline]
    pub const fn float(self, float: Float) -> Self {
        const MASK: Options = Float::MASK << FLOAT_BIT;
        Self((self.0 & !MASK) | ((float as Options) << FLOAT_BIT))
    }

    /// Specify which byte order to use.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, ByteOrder, Options};
    ///
    /// const OPTIONS: Options = options::new().byte_order(ByteOrder::Little).build();
    /// ```
    #[inline]
    pub const fn byte_order(self, byte_order: ByteOrder) -> Self {
        const MASK: Options = ByteOrder::MASK << BYTEORDER_BIT;
        Self((self.0 & !MASK) | ((byte_order as Options) << BYTEORDER_BIT))
    }

    /// Specify that the [`ByteOrder::NATIVE`] byte order should be used.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Width, Options};
    ///
    /// const OPTIONS: Options = options::new().native_byte_order().build();
    /// ```
    #[inline]
    pub const fn native_byte_order(self) -> Self {
        self.byte_order(ByteOrder::NATIVE)
    }

    /// Sets the way in which pointer-like `usize` and `isize` types are
    /// encoded.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Width, Options};
    ///
    /// const OPTIONS: Options = options::new().pointer(Width::U32).build();
    /// ```
    #[inline]
    pub const fn pointer(self, width: Width) -> Self {
        const MASK: Options = Width::MASK << LENGTH_BIT;
        Self((self.0 & !MASK) | ((width as Options) << LENGTH_BIT))
    }

    /// Configured a format to use numbers as map keys.
    ///
    /// This options is used for an encoding such as JSON to allow for storing
    /// numbers as string keys, since this would otherwise not be possible and
    /// cause an error.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Options};
    ///
    /// const OPTIONS: Options = options::new().map_keys_as_numbers().build();
    /// ```
    #[inline]
    pub const fn map_keys_as_numbers(self) -> Self {
        const MASK: Options = 0b1 << MAP_KEYS_AS_NUMBERS_BIT;
        Self((self.0 & !MASK) | (1 << MAP_KEYS_AS_NUMBERS_BIT))
    }

    /// Configure the options to use fixed serialization.
    ///
    /// This causes numerical types to use the default fixed-length
    /// serialization which is typically more efficient than variable-length
    /// through [`variable()`] but is less compact.
    ///
    /// This is the same as calling [`integer(Integer::Fixed)`],
    /// [`float(Float::Fixed)`], and [`pointer(Width::NATIVE)`].
    ///
    /// [`variable()`]: Builder::variable
    /// [`integer(Integer::Fixed)`]: Builder::integer
    /// [`float(Float::Fixed)`]: Builder::float
    /// [`pointer(Width::NATIVE)`]: Builder::pointer
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Options};
    ///
    /// const OPTIONS: Options = options::new().fixed().build();
    /// ```
    #[inline]
    pub const fn fixed(self) -> Self {
        self.integer(Integer::Fixed)
            .float(Float::Fixed)
            .pointer(Width::NATIVE)
    }

    /// Configure the options to use variable serialization.
    ///
    /// This causes numerical types to use the default variable-length
    /// serialization which is typically less efficient than fixed-length
    /// through [`fixed()`] but is more compact.
    ///
    /// This is the same as calling [`integer(Integer::Variable)`],
    /// [`float(Float::Variable)`], and [`pointer(Width::Variable)`].
    ///
    /// [`fixed()`]: Builder::fixed
    /// [`integer(Integer::Variable)`]: Builder::integer
    /// [`float(Float::Variable)`]: Builder::float
    /// [`pointer(Width::Variable)`]: Builder::pointer
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Options};
    ///
    /// const OPTIONS: Options = options::new().variable().build();
    /// ```
    #[inline]
    pub const fn variable(self) -> Self {
        self.integer(Integer::Variable)
            .float(Float::Variable)
            .pointer(Width::Variable)
    }

    /// Built an options builder into a constant.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Options};
    ///
    /// const OPTIONS: Options = options::new().variable().build();
    /// ```
    #[inline]
    pub const fn build(self) -> Options {
        self.0
    }
}

impl fmt::Debug for Builder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Builder")
            .field("byteorder", &byteorder_value(self.0))
            .field("integer", &integer_value(self.0))
            .field("float", &float_value(self.0))
            .field("length", &length_value(self.0))
            .field(
                "is_map_keys_as_numbers",
                &is_map_keys_as_numbers_value(self.0),
            )
            .finish()
    }
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "json",
    feature = "value"
))]
#[inline]
pub(crate) const fn integer<const OPT: Options>() -> Integer {
    integer_value(OPT)
}

#[inline]
const fn integer_value(opt: Options) -> Integer {
    match (opt >> INTEGER_BIT) & 0b1 {
        0 => Integer::Variable,
        _ => Integer::Fixed,
    }
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "json",
    feature = "value"
))]
#[inline]
pub(crate) const fn float<const OPT: Options>() -> Float {
    float_value(OPT)
}

#[inline]
const fn float_value(opt: Options) -> Float {
    match (opt >> FLOAT_BIT) & 0b11 {
        0b00 => Float::Integer,
        0b01 => Float::Variable,
        0b10 => Float::Fixed,
        _ => Float::Pad0,
    }
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "json",
    feature = "value"
))]
#[inline]
pub(crate) const fn length<const OPT: Options>() -> Width {
    length_value(OPT)
}

#[inline]
const fn length_value(opt: Options) -> Width {
    match (opt >> LENGTH_BIT) & 0b111 {
        0b000 => Width::Variable,
        0b001 => Width::U8,
        0b010 => Width::U16,
        0b011 => Width::U32,
        0b100 => Width::U64,
        0b101 => Width::Pad0,
        0b110 => Width::Pad1,
        _ => Width::Pad2,
    }
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "json",
    feature = "value"
))]
#[inline]
pub(crate) const fn byteorder<const OPT: Options>() -> ByteOrder {
    byteorder_value(OPT)
}

#[inline]
pub(crate) const fn byteorder_value(opt: Options) -> ByteOrder {
    match (opt >> BYTEORDER_BIT) & 0b1 {
        0 => ByteOrder::Little,
        _ => ByteOrder::Big,
    }
}

#[cfg(feature = "value")]
#[inline]
pub(crate) const fn is_map_keys_as_numbers<const OPT: Options>() -> bool {
    is_map_keys_as_numbers_value(OPT)
}

const fn is_map_keys_as_numbers_value(opt: Options) -> bool {
    ((opt >> MAP_KEYS_AS_NUMBERS_BIT) & 0b1) == 1
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "value"
))]
pub(crate) const fn is_native_fixed<const OPT: Options>() -> bool {
    matches!(
        (integer::<OPT>(), float::<OPT>(), length::<OPT>(),),
        (Integer::Fixed, Float::Fixed, Width::NATIVE)
    )
}

/// Integer serialization mode.
///
/// # Examples
///
/// ```
/// use musli::options::{self, Integer};
///
/// const OPTIONS_VARIABLE: musli::options::Options = options::new()
///     .integer(Integer::Variable)
///     .build();
///
/// const OPTIONS_FIXED: musli::options::Options = options::new()
///     .integer(Integer::Fixed)
///     .build();
/// ```
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum Integer {
    /// Variable number encoding.
    Variable = 0b0,
    /// Fixed number encoding.
    Fixed = 0b1,
}

impl Integer {
    const MASK: Options = 0b1;
}

/// Float serialization mode.
///
/// # Examples
///
/// ```
/// use musli::options::{self, Float};
///
/// const OPTIONS_INTEGER: musli::options::Options = options::new()
///     .float(Float::Integer)
///     .build();
///
/// const OPTIONS_VARIABLE: musli::options::Options = options::new()
///     .float(Float::Variable)
///     .build();
///
/// const OPTIONS_FIXED: musli::options::Options = options::new()
///     .float(Float::Fixed)
///     .build();
/// ```
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum Float {
    /// Use the same serialization as integers, after coercing the bits of a
    /// float into an unsigned integer.
    Integer = 0b00,
    /// Use variable float encoding.
    Variable = 0b01,
    /// Use fixed float encoding.
    Fixed = 0b10,
    /// Padding.
    #[doc(hidden)]
    Pad0 = 0b11,
}

impl Float {
    const MASK: Options = 0b11;
}

/// Byte order to use when encoding numbers.
///
/// By default, this is the [`ByteOrder::NATIVE`] byte order of the target
/// platform.
///
/// # Examples
///
/// ```
/// use musli::options::{self, ByteOrder};
///
/// const OPTIONS_LITTLE: musli::options::Options = options::new()
///     .byte_order(ByteOrder::Little)
///     .build();
///
/// const OPTIONS_BIG: musli::options::Options = options::new()
///     .byte_order(ByteOrder::Big)
///     .build();
///
/// const OPTIONS_NATIVE: musli::options::Options = options::new()
///     .byte_order(ByteOrder::NATIVE)
///     .build();
/// ```
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum ByteOrder {
    /// Little endian byte order.
    Little = 0,
    /// Big endian byte order.
    Big = 1,
}

impl ByteOrder {
    const MASK: Options = 0b1;

    /// The native byte order.
    ///
    /// [`Little`] for little and [`Big`] for big endian platforms.
    ///
    /// [`Little`]: ByteOrder::Little
    /// [`Big`]: ByteOrder::Big
    pub const NATIVE: Self = if cfg!(target_endian = "little") {
        Self::Little
    } else {
        Self::Big
    };

    /// The network byte order.
    ///
    /// This is the same as [`Big`].
    ///
    /// [`Big`]: ByteOrder::Big
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, ByteOrder};
    /// use musli::packed::Encoding;
    ///
    /// // Configure network byte order (big endian) for cross-platform compatibility
    /// const OPTIONS: musli::options::Options = options::new()
    ///     .byte_order(ByteOrder::NETWORK)
    ///     .build();
    ///
    /// const CONFIG: Encoding<OPTIONS> = Encoding::new().with_options();
    /// let data = CONFIG.to_vec(&0x1234u16)?;
    /// let decoded: u16 = CONFIG.from_slice(&data)?;
    /// assert_eq!(decoded, 0x1234);
    /// # Ok::<_, musli::packed::Error>(())
    /// ```
    pub const NETWORK: Self = Self::Big;
}

#[doc(hidden)]
#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "value"
))]
macro_rules! width_arm {
    ($width:expr, $macro:path) => {
        match $width {
            $crate::options::Width::U8 => {
                $macro!(u8)
            }
            $crate::options::Width::U16 => {
                $macro!(u16)
            }
            $crate::options::Width::U32 => {
                $macro!(u32)
            }
            _ => {
                $macro!(u64)
            }
        }
    };
}

#[cfg(any(
    feature = "storage",
    feature = "wire",
    feature = "descriptive",
    feature = "value"
))]
pub(crate) use width_arm;

/// The width of a numerical type.
///
/// # Examples
///
/// ```
/// use musli::options::{self, Width, Integer};
/// use musli::packed::Encoding;
///
/// // Configure encoding to use variable integer encoding
/// const OPTIONS: musli::options::Options = options::new()
///     .integer(Integer::Variable)
///     .build();
///
/// const CONFIG: Encoding<OPTIONS> = Encoding::new().with_options();
///
/// // Variable encoding is more efficient for small numbers
/// let data = CONFIG.to_vec(&42u32)?;
/// let decoded: u32 = CONFIG.from_slice(&data)?;
/// assert_eq!(decoded, 42);
/// # Ok::<_, musli::packed::Error>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum Width {
    /// Use a variable width encoding.
    Variable = 0b000,
    /// 8 bit width.
    U8 = 0b001,
    /// 16 bit width.
    U16 = 0b010,
    /// 32 bit width.
    U32 = 0b011,
    /// 64 bit width.
    U64 = 0b100,
    /// Padding.
    #[doc(hidden)]
    Pad0 = 0b101,
    /// Padding.
    #[doc(hidden)]
    Pad1 = 0b110,
    /// Padding.
    #[doc(hidden)]
    Pad2 = 0b111,
}

impl Width {
    const MASK: Options = 0b111;

    /// The native width.
    ///
    /// This is the width of the target platform's native integer type.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::options::{self, Width};
    /// use musli::packed::Encoding;
    ///
    /// // Use native pointer width for platform-optimized encoding
    /// const OPTIONS: musli::options::Options = options::new()
    ///     .pointer(Width::NATIVE)
    ///     .build();
    ///
    /// const CONFIG: Encoding<OPTIONS> = Encoding::new().with_options();
    ///
    /// // Encode a usize value using native width
    /// let value: usize = 42;
    /// let data = CONFIG.to_vec(&value)?;
    /// let decoded: usize = CONFIG.from_slice(&data)?;
    /// assert_eq!(value, decoded);
    /// # Ok::<_, musli::packed::Error>(())
    /// ```
    pub const NATIVE: Self = const {
        if cfg!(target_pointer_width = "64") {
            Self::U64
        } else if cfg!(target_pointer_width = "32") {
            Self::U32
        } else if cfg!(target_pointer_width = "16") {
            Self::U16
        } else {
            panic!("Unsupported target pointer width")
        }
    };
}

#[test]
fn test_builds() {
    macro_rules! assert_or_default {
        ($expr:expr, $test:expr, $default:expr, ()) => {
            assert_eq!(
                $test,
                $default,
                "{}: Expected default value for {}",
                stringify!($expr),
                stringify!($test)
            );
        };

        ($expr:expr, $test:expr, $_default:expr, ($expected:expr)) => {
            assert_eq!(
                $test,
                $expected,
                "{}: Expected custom value for {}",
                stringify!($expr),
                stringify!($test)
            );
        };
    }

    macro_rules! test_case {
        ($expr:expr => {
            $(byteorder = $byteorder:expr,)?
            $(integer = $integer:expr,)?
            $(float = $float:expr,)?
            $(length = $length:expr,)?
            $(is_map_keys_as_numbers = $is_map_keys_as_numbers:expr,)?
        }) => {{
            const O: Options = $expr.build();
            assert_or_default!($expr, byteorder::<O>(), ByteOrder::Little, ($($byteorder)?));
            assert_or_default!($expr, integer::<O>(), Integer::Variable, ($($integer)?));
            assert_or_default!($expr, float::<O>(), Float::Integer, ($($float)?));
            assert_or_default!($expr, length::<O>(), Width::Variable, ($($length)?));
            assert_or_default!($expr, is_map_keys_as_numbers::<O>(), false, ($($is_map_keys_as_numbers)?));
        }}
    }

    test_case! {
        self::new() => {}
    }

    test_case! {
        self::new().map_keys_as_numbers() => {
            is_map_keys_as_numbers = true,
        }
    }

    test_case! {
        self::new().integer(Integer::Fixed) => {
            integer = Integer::Fixed,
        }
    }

    test_case! {
        self::new().float(Float::Fixed) => {
            float = Float::Fixed,
        }
    }

    test_case! {
        self::new().float(Float::Variable) => {
            float = Float::Variable,
        }
    }

    test_case! {
        self::new().float(Float::Variable) => {
            float = Float::Variable,
        }
    }

    test_case! {
        self::new().byte_order(ByteOrder::Big) => {
            byteorder = ByteOrder::Big,
        }
    }

    test_case! {
        self::new().byte_order(ByteOrder::Little) => {
            byteorder = ByteOrder::Little,
        }
    }

    test_case! {
        self::new().pointer(Width::Variable) => {
            length = Width::Variable,
        }
    }

    test_case! {
        self::new().pointer(Width::U8) => {
            length = Width::U8,
        }
    }

    test_case! {
        self::new().pointer(Width::U16) => {
            length = Width::U16,
        }
    }

    test_case! {
        self::new().pointer(Width::U32) => {
            length = Width::U32,
        }
    }

    test_case! {
        self::new().pointer(Width::U64) => {
            length = Width::U64,
        }
    }
}