bilrost 0.1016.0

A compact protobuf-like serializer and deserializer for the Rust Language.
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
use crate::buf::ReverseBuf;
use crate::encoding::message::{RawDistinguishedMessageDecoder, RawMessage};
use crate::encoding::proxy::SealedBilrostTag;
use crate::encoding::schema::{Schema, ValueRepr};
use crate::encoding::{
    delegate_encoding, delegate_proxied_encoding, delegate_value_encoding,
    encoding_implemented_via_value_encoding, encoding_uses_base_empty_state,
    impl_cow_value_encoding, read_arc_str, read_box_str, read_rc_str, Canonicity, Capped,
    DecodeContext, DecodeError, DistinguishedProxiable, DistinguishedValueBorrowDecoder,
    DistinguishedValueDecoder, EmptyState, Fixed, Map, MessageEncoding, Packed, PlainBytes,
    Proxiable, RawDistinguishedMessageBorrowDecoder, RawMessageBorrowDecoder, RawMessageDecoder,
    RestrictedDecodeContext, Unpacked, ValueBorrowDecoder, ValueDecoder, ValueEncoder, Varint,
    WireType, Wiretyped,
};
use crate::DecodeErrorKind::InvalidValue;
use crate::{Blob, DecodeErrorKind};
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::rc::Rc;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use bytes::{Buf, BufMut, Bytes};
use core::fmt::Display;
use core::mem;
use core::str;

const PREFER_UNPACKED: u8 = 0;
const PREFER_PACKED: u8 = 1;

/// The `GeneralGeneric` struct is used for general encoding, and is the default with some
/// contextual differences; it is parametrized differently depending on whether it's in a message or a
/// oneof. Different defaults make sense in different contexts; `General<PreferUnpacked>` becomes
/// the `general` encoding in message attributes and is the implicit default for non-annotated
/// fields in Messages, and `General<PreferPacked>` likewise becomes the `general_packed` encoding
/// and is the implicit default for variants with no annotated encoding in `Oneof` enums, as well as
/// the default for fields nested inside fields that are already collections.
///
/// These are also available as the type aliases `General` and `GeneralPacked`; `GeneralGeneric` is
/// still public to allow for generic implementations that are the same when packedness does not
/// matter, which is most of the time.
pub struct GeneralGeneric<const P: u8>;
pub type General = GeneralGeneric<PREFER_UNPACKED>;
pub type GeneralPacked = GeneralGeneric<PREFER_PACKED>;

encoding_uses_base_empty_state!(GeneralGeneric<P>, with generics (const P: u8));
encoding_implemented_via_value_encoding!(GeneralGeneric<P>, with generics (const P: u8));

// `general` and `general_in_oneof` delegate to the `unpacked` and `packed` encodings respectively
// by default, but only for select collection types. Other implementers of the `Collection` trait
// must choose an encoding explicitly.
delegate_encoding!(
    delegate from (General) to (Unpacked) for type (Vec<T>)
    including distinguished
    including schema
    with generics (T)
);
delegate_encoding!(
    delegate from (General) to (Unpacked) for type (Cow<'a, [T]>)
    including distinguished
    including schema
    with where clause (T: Clone)
    with generics ('a, T: 'a)
);
delegate_encoding!(
    delegate from (General) to (Unpacked) for type (BTreeSet<T>)
    including distinguished
    including schema
    with generics (T)
);

delegate_value_encoding!(
    delegate from (GeneralPacked) to (Packed) for type (Vec<T>)
    including distinguished
    including schema
    with generics (T)
);
delegate_value_encoding!(
    delegate from (GeneralPacked) to (Packed) for type (Cow<'a, [T]>)
    including distinguished
    including schema
    with where clause for relaxed (T: Clone)
    with generics ('a, T: 'a)
);
delegate_value_encoding!(
    delegate from (GeneralPacked) to (Packed) for type (BTreeSet<T>)
    including distinguished
    including schema
    with generics (T)
);

delegate_value_encoding!(
    delegate from (GeneralGeneric<P>) to (Map) for type (BTreeMap<K, V>)
    including distinguished
    including schema
    with where clause for relaxed (K: Ord)
    with where clause for distinguished (V: Eq)
    with generics (const P: u8, K, V)
);

// General encodings encode Range and RangeInclusive with the General encoding; to use a different
// encoding for the T value, encode ranges as tuples directly
delegate_value_encoding!(
    delegate from (GeneralGeneric<P>) to ((General, General))
    for type (core::ops::Range<T>)
    including distinguished
    including schema
    with generics (const P: u8, T)
);
delegate_value_encoding!(
    delegate from (GeneralGeneric<P>) to ((General, General))
    for type (core::ops::RangeInclusive<T>)
    including distinguished
    including schema
    with generics (const P: u8, T)
);

// General encodes bool and integers as varints.
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (bool)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (u16)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (i16)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (u32)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (i32)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (u64)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (i64)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (usize)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint) for type (isize)
    including distinguished
    including schema
    with generics (const P: u8));

delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroU8)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroI8)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroU16)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroI16)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroU32)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroI32)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroU64)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroI64)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroUsize)
    including distinguished
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Varint)
    for type (core::num::NonZeroIsize)
    including distinguished
    including schema
    with generics (const P: u8));

// General also encodes floating point values.
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Fixed) for type (f32)
    including schema
    with generics (const P: u8));
delegate_value_encoding!(delegate from (GeneralGeneric<P>) to (Fixed) for type (f64)
    including schema
    with generics (const P: u8));

impl<const P: u8> Wiretyped<GeneralGeneric<P>, &str> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, &str> for () {
    fn repr(_: &Schema) -> Box<dyn Display> {
        Box::new("delimited bytes; utf8")
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, &str> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &&str, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &&str, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &&str) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_bytes())
    }
}

impl<'a, const P: u8> ValueBorrowDecoder<'a, GeneralGeneric<P>, &'a str> for () {
    #[inline]
    fn borrow_decode_value(
        value: &mut &'a str,
        mut buf: Capped<&'a [u8]>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        *value = str::from_utf8(buf.take_borrowed_length_delimited()?).map_err(|_| InvalidValue)?;
        Ok(())
    }
}

impl<'a, const P: u8> DistinguishedValueBorrowDecoder<'a, GeneralGeneric<P>, &'a str> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn borrow_decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut &'a str,
        buf: Capped<&'a [u8]>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueBorrowDecoder<GeneralGeneric<P>, _>>::borrow_decode_value(
            value,
            buf,
            ctx.into_inner(),
        )?;
        Ok(Canonicity::Canonical)
    }
}

#[cfg(test)]
mod ref_str {
    crate::encoding::test::check_borrowable!(borrowed: str, encoding: crate::encoding::General);
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, String> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, String> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<General, &str>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, String> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &String, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &String, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &String) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_bytes())
    }
}

#[cfg(not(feature = "forbid-unsafe"))]
impl<const P: u8> ValueDecoder<GeneralGeneric<P>, String> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut String,
        mut buf: Capped<B>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        // ## Unsafety
        //
        // Copies string data from the buffer, with an additional check of utf-8 well-formedness.
        // If the utf-8 is not well-formed, or if any other error occurs while copying the data,
        // then the string is cleared so as to avoid leaking a string field with invalid data.
        //
        // This implementation uses the unsafe `String::as_mut_vec` method instead of the safe
        // alternative of temporarily swapping an empty `String` into the field, because it results
        // in up to 10% better performance on the protobuf message decoding benchmarks.
        //
        // It's required when using `String::as_mut_vec` that invalid utf-8 data not be leaked into
        // the backing `String`. To enforce this, even in the event of a panic in the decoder or
        // in the buf implementation, a drop guard is used.
        struct DropGuard<'a>(&'a mut Vec<u8>);
        impl Drop for DropGuard<'_> {
            #[inline]
            fn drop(&mut self) {
                self.0.clear();
            }
        }

        let source = buf.take_length_delimited()?.take_all();
        // If we must copy, make sure to copy only once.
        value.clear();
        value.reserve(source.remaining());
        unsafe {
            let drop_guard = DropGuard(value.as_mut_vec());
            drop_guard.0.put(source);
            match str::from_utf8(drop_guard.0) {
                Ok(_) => {
                    // Success; do not clear the bytes.
                    mem::forget(drop_guard);
                    Ok(())
                }
                Err(_) => Err(DecodeError::new(InvalidValue)),
            }
        }
    }
}

#[cfg(feature = "forbid-unsafe")]
impl<const P: u8> ValueDecoder<GeneralGeneric<P>, String> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut String,
        buf: Capped<B>,
        ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        // In this implementation we do the safe thing: the string is taken out and turned into a
        // Vec, we decode into that, and then we convert it into a String before putting it back.
        let mut taken_value = <Vec<u8>>::from(mem::take(value));
        <() as ValueDecoder<PlainBytes, Vec<u8>>>::decode_value(&mut taken_value, buf, ctx)?;
        *value = String::from_utf8(taken_value).map_err(|_| DecodeError::new(InvalidValue))?;
        Ok(())
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, String> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut String,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueDecoder<GeneralGeneric<P>, _>>::decode_value(value, buf, ctx.into_inner())?;
        Ok(Canonicity::Canonical)
    }
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>)
    borrows type (String) as owned
    including distinguished
    with generics (const P: u8)
);

#[cfg(test)]
mod string {
    use super::{General, String};
    use crate::encoding::test::check_type_test;
    check_type_test!(General, relaxed, String, WireType::LengthDelimited);
    check_type_test!(General, distinguished, String, WireType::LengthDelimited);
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, Arc<str>> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, Arc<str>> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<General, &str>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, Arc<str>> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &Arc<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &Arc<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &Arc<str>) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_bytes())
    }
}

impl<const P: u8> ValueDecoder<GeneralGeneric<P>, Arc<str>> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut Arc<str>,
        mut buf: Capped<B>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        *value = read_arc_str(buf.take_length_delimited()?)?;
        Ok(())
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, Arc<str>> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut Arc<str>,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueDecoder<GeneralGeneric<P>, _>>::decode_value(value, buf, ctx.into_inner())?;
        Ok(Canonicity::Canonical)
    }
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>)
    borrows type (Arc<str>) as owned
    including distinguished
    with generics (const P: u8)
);

#[cfg(test)]
mod arc_str {
    use super::{Arc, General};
    use crate::encoding::test::{check_type_test, decode_noncontiguous_pointered_str};
    check_type_test!(General, relaxed, Arc<str>, WireType::LengthDelimited);
    check_type_test!(General, distinguished, Arc<str>, WireType::LengthDelimited);

    #[test]
    fn noncontiguous() {
        decode_noncontiguous_pointered_str::<Arc<str>>();
    }
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, Rc<str>> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, Rc<str>> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<General, &str>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, Rc<str>> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &Rc<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &Rc<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &Rc<str>) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_bytes())
    }
}

impl<const P: u8> ValueDecoder<GeneralGeneric<P>, Rc<str>> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut Rc<str>,
        mut buf: Capped<B>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        *value = read_rc_str(buf.take_length_delimited()?)?;
        Ok(())
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, Rc<str>> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut Rc<str>,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueDecoder<GeneralGeneric<P>, _>>::decode_value(value, buf, ctx.into_inner())?;
        Ok(Canonicity::Canonical)
    }
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>)
    borrows type (Rc<str>) as owned
    including distinguished
    with generics (const P: u8)
);

#[cfg(test)]
mod rc_str {
    use super::{General, Rc};
    use crate::encoding::test::{check_type_test, decode_noncontiguous_pointered_str};
    check_type_test!(General, relaxed, Rc<str>, WireType::LengthDelimited);
    check_type_test!(General, distinguished, Rc<str>, WireType::LengthDelimited);

    #[test]
    fn noncontiguous() {
        decode_noncontiguous_pointered_str::<Rc<str>>();
    }
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, Box<str>> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, Box<str>> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<General, &str>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, Box<str>> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &Box<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &Box<str>, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_bytes(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &Box<str>) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_bytes())
    }
}

impl<const P: u8> ValueDecoder<GeneralGeneric<P>, Box<str>> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut Box<str>,
        mut buf: Capped<B>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        *value = read_box_str(buf.take_length_delimited()?)?;
        Ok(())
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, Box<str>> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut Box<str>,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueDecoder<GeneralGeneric<P>, _>>::decode_value(value, buf, ctx.into_inner())?;
        Ok(Canonicity::Canonical)
    }
}

#[cfg(test)]
mod box_str {
    use super::{General, Rc};
    use crate::encoding::test::check_type_test;
    check_type_test!(General, relaxed, Rc<str>, WireType::LengthDelimited);
    check_type_test!(General, distinguished, Rc<str>, WireType::LengthDelimited);
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>)
    borrows type (Box<str>) as owned
    including distinguished
    with generics (const P: u8)
);

impl_cow_value_encoding!(
    borrowed str,
    owned String,
    encoding GeneralGeneric<P>,
    with generic (const P: u8)
);

#[cfg(test)]
mod cow_string {
    use super::{Cow, General};
    use crate::encoding::test::check_type_test;
    check_type_test!(General, relaxed, Cow<str>, WireType::LengthDelimited);
    check_type_test!(General, distinguished, Cow<str>, WireType::LengthDelimited);
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, Bytes> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, Bytes> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<PlainBytes, &[u8]>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, Bytes> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &Bytes, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&&**value, buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &Bytes, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&&**value, buf)
    }

    #[inline]
    fn value_encoded_len(value: &Bytes) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&&**value)
    }
}

impl<const P: u8> ValueDecoder<GeneralGeneric<P>, Bytes> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut Bytes,
        mut buf: Capped<B>,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        let mut buf = buf.take_length_delimited()?;
        let len = buf.remaining_before_cap();
        *value = buf.copy_to_bytes(len);
        Ok(())
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, Bytes> for () {
    const CHECKS_EMPTY: bool = false;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut Bytes,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as ValueDecoder<GeneralGeneric<P>, _>>::decode_value(value, buf, ctx.into_inner())?;
        Ok(Canonicity::Canonical)
    }
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>) borrows type (Bytes) as owned
    including distinguished with generics (const P: u8)
);

#[cfg(test)]
mod bytes_blob {
    use super::{Bytes, General, Vec};
    use crate::encoding::test::check_type_test;
    check_type_test!(General, relaxed, from Vec<u8>, into Bytes,
        WireType::LengthDelimited);
    check_type_test!(General, distinguished, from Vec<u8>, into Bytes,
        WireType::LengthDelimited);
}

impl<const P: u8> Wiretyped<GeneralGeneric<P>, Blob> for () {
    const WIRE_TYPE: WireType = WireType::LengthDelimited;
}

impl<const P: u8> ValueRepr<GeneralGeneric<P>, Blob> for () {
    fn repr(schema: &Schema) -> Box<dyn Display> {
        <() as ValueRepr<PlainBytes, &[u8]>>::repr(schema)
    }
}

impl<const P: u8> ValueEncoder<GeneralGeneric<P>, Blob> for () {
    #[inline]
    fn encode_value<B: BufMut + ?Sized>(value: &Blob, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::encode_value(&value.as_slice(), buf)
    }

    #[inline]
    fn prepend_value<B: ReverseBuf + ?Sized>(value: &Blob, buf: &mut B) {
        <() as ValueEncoder<PlainBytes, _>>::prepend_value(&value.as_slice(), buf)
    }

    #[inline]
    fn value_encoded_len(value: &Blob) -> usize {
        <() as ValueEncoder<PlainBytes, _>>::value_encoded_len(&value.as_slice())
    }
}

impl<const P: u8> ValueDecoder<GeneralGeneric<P>, Blob> for () {
    #[inline]
    fn decode_value<B: Buf + ?Sized>(
        value: &mut Blob,
        buf: Capped<B>,
        ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        <() as ValueDecoder<PlainBytes, _>>::decode_value(&mut **value, buf, ctx)
    }
}

impl<const P: u8> DistinguishedValueDecoder<GeneralGeneric<P>, Blob> for () {
    const CHECKS_EMPTY: bool = <() as DistinguishedValueDecoder<PlainBytes, Vec<u8>>>::CHECKS_EMPTY;

    #[inline]
    fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
        value: &mut Blob,
        buf: Capped<impl Buf + ?Sized>,
        ctx: RestrictedDecodeContext,
    ) -> Result<Canonicity, DecodeError> {
        <() as DistinguishedValueDecoder<PlainBytes, _>>::decode_value_distinguished::<ALLOW_EMPTY>(
            &mut **value,
            buf,
            ctx,
        )
    }
}

delegate_value_encoding!(
    encoding (GeneralGeneric<P>) borrows type (Blob) as owned
    including distinguished with generics (const P: u8)
);

#[cfg(test)]
mod blob {
    use super::{Blob, General};
    use crate::encoding::test::check_type_test;
    check_type_test!(General, relaxed, Blob, WireType::LengthDelimited);
    check_type_test!(General, distinguished, Blob, WireType::LengthDelimited);
}

impl Proxiable<SealedBilrostTag> for core::time::Duration {
    type Proxy = crate::encoding::local_proxy::LocalProxy<u64, 2>;

    fn encode_proxy(&self) -> Self::Proxy {
        Self::Proxy::new_without_empty_suffix([self.as_secs(), self.subsec_nanos() as u64])
    }

    fn decode_proxy(&mut self, proxy: Self::Proxy) -> Result<(), DecodeErrorKind> {
        let [secs, nanos @ 0..=999_999_999] = proxy.into_inner() else {
            return Err(InvalidValue);
        };
        *self = core::time::Duration::new(secs, nanos as u32);
        Ok(())
    }
}

impl DistinguishedProxiable<SealedBilrostTag> for core::time::Duration {
    fn decode_proxy_distinguished(
        &mut self,
        proxy: Self::Proxy,
    ) -> Result<Canonicity, DecodeErrorKind> {
        let ([secs, nanos @ 0..=999_999_999], canon) = proxy.into_inner_distinguished() else {
            return Err(InvalidValue);
        };
        *self = core::time::Duration::new(secs, nanos as u32);
        Ok(canon)
    }
}

delegate_proxied_encoding!(
    use encoding (Packed<Varint>) to encode proxied type (core::time::Duration)
    using proxy tag (SealedBilrostTag)
    with general encodings
    including distinguished
    including schema
);

#[cfg(test)]
mod core_time {
    use super::*;
    use crate::encoding::test::{check_type_empty, check_type_test};

    check_type_empty!(core::time::Duration, via proxy with tag SealedBilrostTag);
    check_type_test!(
        General,
        relaxed,
        core::time::Duration,
        WireType::LengthDelimited
    );
    check_type_empty!(core::time::Duration, via distinguished proxy with tag SealedBilrostTag);
    check_type_test!(
        General,
        distinguished,
        core::time::Duration,
        WireType::LengthDelimited
    );
}

mod delegate_to_message_encoding {
    use super::*;

    impl<const P: u8, T> Wiretyped<GeneralGeneric<P>, T> for ()
    where
        T: RawMessage,
        (): EmptyState<(), T>,
    {
        const WIRE_TYPE: WireType = <() as Wiretyped<MessageEncoding, T>>::WIRE_TYPE;
    }

    impl<const P: u8, T> ValueRepr<GeneralGeneric<P>, T> for ()
    where
        T: RawMessage,
        (): EmptyState<(), T> + ValueRepr<MessageEncoding, T>,
    {
        fn repr(schema: &Schema) -> Box<dyn Display> {
            <() as ValueRepr<MessageEncoding, T>>::repr(schema)
        }
    }

    impl<const P: u8, T> ValueEncoder<GeneralGeneric<P>, T> for ()
    where
        T: RawMessage,
        (): EmptyState<(), T>,
    {
        #[inline(always)]
        fn encode_value<B: BufMut + ?Sized>(value: &T, buf: &mut B) {
            <() as ValueEncoder<MessageEncoding, _>>::encode_value(value, buf)
        }

        #[inline(always)]
        fn prepend_value<B: ReverseBuf + ?Sized>(value: &T, buf: &mut B) {
            <() as ValueEncoder<MessageEncoding, _>>::prepend_value(value, buf)
        }

        #[inline(always)]
        fn value_encoded_len(value: &T) -> usize {
            <() as ValueEncoder<MessageEncoding, _>>::value_encoded_len(value)
        }
    }

    impl<const P: u8, T> ValueDecoder<GeneralGeneric<P>, T> for ()
    where
        T: RawMessageDecoder,
        (): EmptyState<(), T>,
    {
        #[inline(always)]
        fn decode_value<B: Buf + ?Sized>(
            value: &mut T,
            buf: Capped<B>,
            ctx: DecodeContext,
        ) -> Result<(), DecodeError> {
            <() as ValueDecoder<MessageEncoding, _>>::decode_value(value, buf, ctx)
        }
    }

    impl<const P: u8, T> DistinguishedValueDecoder<GeneralGeneric<P>, T> for ()
    where
        T: RawDistinguishedMessageDecoder + Eq,
        (): EmptyState<(), T>,
    {
        const CHECKS_EMPTY: bool =
            <() as DistinguishedValueDecoder<MessageEncoding, T>>::CHECKS_EMPTY;

        #[inline(always)]
        fn decode_value_distinguished<const ALLOW_EMPTY: bool>(
            value: &mut T,
            buf: Capped<impl Buf + ?Sized>,
            ctx: RestrictedDecodeContext,
        ) -> Result<Canonicity, DecodeError> {
            <() as DistinguishedValueDecoder<MessageEncoding, _>>::decode_value_distinguished::<
                ALLOW_EMPTY,
            >(value, buf, ctx)
        }
    }

    impl<'a, const P: u8, T> ValueBorrowDecoder<'a, GeneralGeneric<P>, T> for ()
    where
        T: RawMessageBorrowDecoder<'a>,
        (): EmptyState<(), T>,
    {
        #[inline(always)]
        fn borrow_decode_value(
            value: &mut T,
            buf: Capped<&'a [u8]>,
            ctx: DecodeContext,
        ) -> Result<(), DecodeError> {
            <() as ValueBorrowDecoder<MessageEncoding, _>>::borrow_decode_value(value, buf, ctx)
        }
    }

    impl<'a, const P: u8, T> DistinguishedValueBorrowDecoder<'a, GeneralGeneric<P>, T> for ()
    where
        T: RawDistinguishedMessageBorrowDecoder<'a> + Eq,
        (): EmptyState<(), T>,
    {
        const CHECKS_EMPTY: bool =
            <() as DistinguishedValueBorrowDecoder<MessageEncoding, T>>::CHECKS_EMPTY;

        #[inline(always)]
        fn borrow_decode_value_distinguished<const ALLOW_EMPTY: bool>(
            value: &mut T,
            buf: Capped<&'a [u8]>,
            ctx: RestrictedDecodeContext,
        ) -> Result<Canonicity, DecodeError> {
            <() as DistinguishedValueBorrowDecoder<MessageEncoding, _>>::borrow_decode_value_distinguished::<
                ALLOW_EMPTY,
            >(value, buf, ctx)
        }
    }
}