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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
use crate::buf::{ReverseBuf, ReverseBuffer};
use crate::encoding::message::{
borrow_merge, borrow_merge_distinguished, merge, merge_distinguished,
};
use crate::encoding::{
encode_varint, encoded_len_varint, prepend_varint, Capped, DecodeContext,
RawDistinguishedMessageBorrowDecoder, RawDistinguishedMessageDecoder, RawMessage,
RawMessageBorrowDecoder, RawMessageDecoder, RestrictedDecodeContext,
};
use crate::Canonicity::{Canonical, NotCanonical};
use crate::{length_delimiter_len, Canonicity, DecodeError, EncodeError};
use alloc::vec::Vec;
use bytes::{Buf, BufMut, Bytes, BytesMut};
/// A Bilrost message. Provides basic encoding functionality for message types.
pub trait Message {
/// Creates a new message with an empty state.
fn new_empty() -> Self
where
Self: Sized;
/// Encodes the message to a buffer.
///
/// An error will be returned if the buffer does not have sufficient capacity.
fn encode<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError>
where
Self: Sized;
/// Prepends the message to a buffer.
fn prepend<B: ReverseBuf + ?Sized>(&self, buf: &mut B)
where
Self: Sized;
/// Encodes the message with a length-delimiter to a buffer.
///
/// An error will be returned if the buffer does not have sufficient capacity.
fn encode_length_delimited<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Returns whether the message is currently in an empty state.
fn message_is_empty(&self) -> bool;
/// Resets the message to an empty state.
fn clear_message(&mut self);
/// Returns the encoded length of the message without a length delimiter.
fn encoded_len(&self) -> usize;
/// Encodes the message to a newly allocated buffer.
fn encode_to_vec(&self) -> Vec<u8>;
/// Encodes the message to a `Bytes` buffer.
fn encode_to_bytes(&self) -> Bytes;
/// Encodes the message to a `ReverseBuffer`.
fn encode_fast(&self) -> ReverseBuffer;
/// Encodes the message with a length-delimiter to a `ReverseBuffer`.
fn encode_length_delimited_fast(&self) -> ReverseBuffer;
/// Encodes the message to a new `RevserseBuffer` which will have exactly the required capacity
/// in one contiguous slice.
fn encode_contiguous(&self) -> ReverseBuffer;
/// Encodes the message with a length-delimiter to a new `RevserseBuffer` which will have
/// exactly the required capacity in one contiguous slice.
fn encode_length_delimited_contiguous(&self) -> ReverseBuffer;
/// Encodes the message to a `Bytes` buffer.
fn encode_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError>;
/// Encodes the message with a length-delimiter to a newly allocated buffer.
fn encode_length_delimited_to_vec(&self) -> Vec<u8>;
/// Encodes the message with a length-delimiter to a `Bytes` buffer.
fn encode_length_delimited_to_bytes(&self) -> Bytes;
/// Encodes the message with a length-delimiter to a `Bytes` buffer.
fn encode_length_delimited_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError>;
}
/// Basic decoding functionality for a Bilrost message that can decode to an owned form. This
/// trait's decoding methods can decode from any byte buffer that implements `bytes::Buf`.
pub trait OwnedMessage: Message {
/// Decodes an instance of the message from a buffer.
///
/// The entire buffer will be consumed.
fn decode<B: Buf>(buf: B) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer.
fn decode_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes an instance from the given `Capped` buffer, consuming it to its cap.
#[doc(hidden)]
fn decode_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message from the buffer, replacing their values.
fn replace_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer.
fn replace_from_length_delimited<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message, replacing their values from the given capped
/// buffer.
#[doc(hidden)]
fn replace_from_capped<B: Buf + ?Sized>(&mut self, buf: Capped<B>) -> Result<(), DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes the non-ignored fields of this message from the buffer, replacing their values.
fn replace_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer.
fn replace_from_length_delimited_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message from the buffer, replacing their values.
fn replace_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer.
fn replace_from_length_delimited_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from the given capped
/// buffer.
#[doc(hidden)]
fn replace_from_capped_dyn(&mut self, buf: Capped<dyn Buf>) -> Result<(), DecodeError>;
}
/// An enhanced trait for owned Bilrost messages that promise a distinguished representation.
///
/// Implementation of this trait comes with the following promises:
///
/// 1. The message will always encode to the same bytes as any other message with an equal value.
/// 2. A message equal to that value will only ever decode canonically and without error from that
/// exact sequence of bytes, not from any other.
///
/// Distinguished decoding methods come in three flavors:
/// * "distinguished" methods, which decode anything that relaxed decoding will and return the
/// value along with a `Canonicity`
/// * "restricted" methods, which also require a minimum `Canonicity` and will early-exit decoding
/// and return an appropriate error if the canonicity violates that constraint:
/// * restrict to `Canonical` will return an error any time the encoding is not fully canonical
/// * restrict to `HasExtensions` will return an error any time the encoding has known fields
/// with non-canonical representations, but will not fail when unknown fields are present
/// * passing `NotCanonical` gives exactly the same result as using the distinguished decoding
/// methods
/// * "canonical" methods, which are shorthand for "restricted" methods with `Canonical` constraint
/// and do not return the `Canonicity`, because it will always be fully `Canonical`.
///
/// Note that currently the only restriction level that is sensible to *explicitly* pass to
/// "restricted" methods is `HasExtensions`: "distinguished" methods already dispatch to passing
/// `NotCanonical`, and when `Canonical` is passed only `Canonical` can be returned from a
/// successful result (hence the "canonical" methods). It can of course make sense to call these
/// methods with a varying restriction level.
pub trait DistinguishedOwnedMessage: OwnedMessage {
// ------------ Distinguished mode ------------
/// Decodes an instance of the message from a buffer in distinguished mode.
///
/// The entire buffer will be consumed.
fn decode_distinguished<B: Buf>(buf: B) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
fn decode_distinguished_length_delimited<B: Buf>(
buf: B,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes an instance from the given `Capped` buffer in distinguished mode, consuming it to
/// its cap.
#[doc(hidden)]
fn decode_distinguished_capped<B: Buf + ?Sized>(
buf: Capped<B>,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
/// replacing their values.
fn replace_distinguished_from<B: Buf>(&mut self, buf: B) -> Result<Canonicity, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
/// from a length-delimited value encoded in the buffer.
fn replace_distinguished_from_length_delimited<B: Buf>(
&mut self,
buf: B,
) -> Result<Canonicity, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
/// from the given capped buffer.
#[doc(hidden)]
fn replace_distinguished_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
) -> Result<Canonicity, DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
fn replace_distinguished_from_slice(&mut self, buf: &[u8]) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in distinguished mode.
fn replace_distinguished_from_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
/// replacing their values.
fn replace_distinguished_from_length_delimited_slice(
&mut self,
buf: &[u8],
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in distinguished mode.
fn replace_distinguished_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from the given capped
/// buffer in distinguished mode.
#[doc(hidden)]
fn replace_distinguished_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
) -> Result<Canonicity, DecodeError>;
// ------------ Restricted mode ------------
/// Decodes an instance of the message from a buffer in restricted mode.
///
/// The entire buffer will be consumed.
fn decode_restricted<B: Buf>(
buf: B,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in restricted mode.
fn decode_restricted_length_delimited<B: Buf>(
buf: B,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes an instance from the given `Capped` buffer in restricted mode, consuming it to
/// its cap.
#[doc(hidden)]
fn decode_restricted_capped<B: Buf + ?Sized>(
buf: Capped<B>,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message from the buffer in restricted mode,
/// replacing their values.
fn replace_restricted_from<B: Buf>(
&mut self,
buf: B,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in restricted mode, replacing their values
/// from a length-delimited value encoded in the buffer.
fn replace_restricted_from_length_delimited<B: Buf>(
&mut self,
buf: B,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in restricted mode, replacing their values
/// from the given capped buffer.
#[doc(hidden)]
fn replace_restricted_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes a length-delimited instance of the message from the buffer in restricted mode.
fn replace_restricted_from_slice(
&mut self,
buf: &[u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in restricted mode.
fn replace_restricted_from_dyn(
&mut self,
buf: &mut dyn Buf,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message from the buffer in restricted mode,
/// replacing their values.
fn replace_restricted_from_length_delimited_slice(
&mut self,
buf: &[u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in restricted mode.
fn replace_restricted_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from the given capped
/// buffer in restricted mode.
#[doc(hidden)]
fn replace_restricted_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
// ------------ Canonical mode ------------
/// Decodes an instance of the message from a buffer in canonical mode.
///
/// The entire buffer will be consumed.
fn decode_canonical<B: Buf>(buf: B) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in canonical mode.
fn decode_canonical_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes an instance from the given `Capped` buffer in canonical mode, consuming it to
/// its cap.
#[doc(hidden)]
fn decode_canonical_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message from the buffer in canonical mode,
/// replacing their values.
fn replace_canonical_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in canonical mode, replacing their values
/// from a length-delimited value encoded in the buffer.
fn replace_canonical_from_length_delimited<B: Buf>(
&mut self,
buf: B,
) -> Result<(), DecodeError>
where
Self: Sized;
/// Decodes the non-ignored fields of this message in canonical mode, replacing their values
/// from the given capped buffer.
#[doc(hidden)]
fn replace_canonical_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
) -> Result<(), DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes a length-delimited instance of the message from the buffer in canonical mode.
fn replace_canonical_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in canonical mode.
fn replace_canonical_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message from the buffer in canonical mode,
/// replacing their values.
fn replace_canonical_from_length_delimited_slice(
&mut self,
buf: &[u8],
) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer in canonical mode.
fn replace_canonical_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from the given capped
/// buffer in canonical mode.
#[doc(hidden)]
fn replace_canonical_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
) -> Result<(), DecodeError>;
}
/// Basic decoding functionality for a Bilrost message that can decode from a borrowed slice.
pub trait BorrowedMessage<'a>: Message {
/// Decodes an instance of the message from a buffer.
///
/// The entire buffer will be consumed.
fn decode_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn decode_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes the non-ignored fields of this message from the buffer, replacing their values.
fn replace_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message, replacing their values from a
/// length-delimited value encoded in the buffer.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn replace_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<(), DecodeError>;
}
/// An enhanced trait for borrowed Bilrost messages that promise a distinguished representation.
///
/// Implementation of this trait comes with the following promises:
///
/// 1. The message will always encode to the same bytes as any other message with an equal value.
/// 2. A message equal to that value will only ever decode canonically and without error from that
/// exact sequence of bytes, not from any other.
///
/// Distinguished decoding methods come in three flavors:
/// * "distinguished" methods, which decode anything that relaxed decoding will and return the
/// value along with a `Canonicity`
/// * "restricted" methods, which also require a minimum `Canonicity` and will early-exit decoding
/// and return an appropriate error if the canonicity violates that constraint:
/// * restrict to `Canonical` will return an error any time the encoding is not fully canonical
/// * restrict to `HasExtensions` will return an error any time the encoding has known fields
/// with non-canonical representations, but will not fail when unknown fields are present
/// * passing `NotCanonical` gives exactly the same result as using the distinguished decoding
/// methods
/// * "canonical" methods, which are shorthand for "restricted" methods with `Canonical` constraint
/// and do not return the `Canonicity`, because it will always be fully `Canonical`.
///
/// Note that currently the only restriction level that is sensible to *explicitly* pass to
/// "restricted" methods is `HasExtensions`: "distinguished" methods already dispatch to passing
/// `NotCanonical`, and when `Canonical` is passed only `Canonical` can be returned from a
/// successful result (hence the "canonical" methods). It can of course make sense to call these
/// methods with a varying restriction level.
pub trait DistinguishedBorrowedMessage<'a>: BorrowedMessage<'a> {
// ------------ Distinguished mode ------------
/// Decodes an instance of the message from a buffer in distinguished mode.
///
/// The entire buffer will be consumed.
fn decode_distinguished_borrowed(buf: &'a [u8]) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn decode_distinguished_borrowed_length_delimited(
buf: &mut &'a [u8],
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
/// replacing their values.
fn replace_distinguished_borrowed_from(
&mut self,
buf: &'a [u8],
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
/// from a length-delimited value encoded in the buffer.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn replace_distinguished_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<Canonicity, DecodeError>;
// ------------ Restricted mode ------------
/// Decodes an instance of the message from a buffer in restricted mode.
///
/// The entire buffer will be consumed.
fn decode_restricted_borrowed(
buf: &'a [u8],
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in restricted mode.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn decode_restricted_borrowed_length_delimited(
buf: &mut &'a [u8],
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes the non-ignored fields of this message from the buffer in restricted mode,
/// replacing their values.
fn replace_restricted_borrowed_from(
&mut self,
buf: &'a [u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
/// Decodes the non-ignored fields of this message in restricted mode, replacing their values
/// from a length-delimited value encoded in the buffer.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn replace_restricted_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError>;
// ------------ Canonical mode ------------
/// Decodes an instance of the message from a buffer in canonical mode.
///
/// The entire buffer will be consumed.
fn decode_canonical_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError>
where
Self: Sized;
/// Decodes a length-delimited instance of the message from the buffer in canonical mode.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn decode_canonical_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError>
where
Self: Sized;
// ------------ Dyn-compatible methods follow ------------
/// Decodes the non-ignored fields of this message from the buffer in canonical mode,
/// replacing their values.
fn replace_canonical_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError>;
/// Decodes the non-ignored fields of this message in canonical mode, replacing their values
/// from a length-delimited value encoded in the buffer.
///
/// * If the message decodes successfully, the provided slice will be shortened to no longer
/// include the bytes that encoded it or its length delimiter.
/// * If the message is correctly delimited within the bounds of the slice but fails to decode,
/// the provided slice will still be shortened even though an error is returned.
/// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
/// itself is truncated, an error with Truncated kind is returned and it is unspecified how
/// the provided slice value is modified.
fn replace_canonical_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<(), DecodeError>;
}
/// `Message` is implemented as a usability layer on top of the basic functionality afforded by
/// `RawMessage`.
// TODO: extension decoding: extensions can't be provided singly alongside the message that's to be
// decoded and capture extensions in anything but the top layer message's extension fields. doing
// this in a really robust way that people will probably eventually want will probably require some
// kind of moderately robust semi-reflective mapping that mirrors the parsed structure of the
// message that it came from; re-encoding from this type could be similarly difficult to implement
// efficiently, since the way inlining is done now type-erases the implementations of each field's
// encoding and applying extensions would need to either interleave encoded message data (which is
// honestly probably faster) or make all of the field encodings reachable polymorphically.
impl<T> Message for T
where
T: RawMessage + Sized,
{
fn new_empty() -> Self {
T::empty()
}
fn encode<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError> {
let required = self.encoded_len();
let remaining = buf.remaining_mut();
if required > remaining {
return Err(EncodeError::new(required, remaining));
}
self.raw_encode(buf);
Ok(())
}
fn prepend<B: ReverseBuf + ?Sized>(&self, buf: &mut B) {
self.raw_prepend(buf);
}
fn encode_length_delimited<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError> {
let len = self.encoded_len();
let required = len + encoded_len_varint(len as u64);
let remaining = buf.remaining_mut();
if required > remaining {
return Err(EncodeError::new(required, remaining));
}
encode_varint(len as u64, buf);
self.raw_encode(buf);
Ok(())
}
fn message_is_empty(&self) -> bool {
self.is_empty()
}
fn clear_message(&mut self) {
self.clear();
}
fn encoded_len(&self) -> usize {
self.raw_encoded_len()
}
fn encode_to_vec(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.encoded_len());
self.raw_encode(&mut buf);
buf
}
fn encode_to_bytes(&self) -> Bytes {
let mut buf = BytesMut::with_capacity(self.encoded_len());
self.raw_encode(&mut buf);
buf.freeze()
}
fn encode_fast(&self) -> ReverseBuffer {
let mut buf = ReverseBuffer::new();
self.raw_prepend(&mut buf);
buf
}
fn encode_length_delimited_fast(&self) -> ReverseBuffer {
let mut buf = self.encode_fast();
prepend_varint(buf.remaining() as u64, &mut buf);
buf
}
fn encode_contiguous(&self) -> ReverseBuffer {
let mut buf = ReverseBuffer::with_capacity(self.encoded_len());
self.raw_prepend(&mut buf);
debug_assert!(buf.contiguous().is_some());
debug_assert!(buf.capacity() == buf.len());
buf
}
fn encode_length_delimited_contiguous(&self) -> ReverseBuffer {
let len = self.encoded_len();
let mut buf = ReverseBuffer::with_capacity(len + length_delimiter_len(len));
self.raw_prepend(&mut buf);
prepend_varint(len as u64, &mut buf);
debug_assert!(buf.contiguous().is_some());
debug_assert!(buf.capacity() == buf.len());
buf
}
fn encode_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError> {
self.encode(buf)
}
fn encode_length_delimited_to_vec(&self) -> Vec<u8> {
let len = self.encoded_len();
let mut buf = Vec::with_capacity(len + encoded_len_varint(len as u64));
encode_varint(len as u64, &mut buf);
self.raw_encode(&mut buf);
buf
}
fn encode_length_delimited_to_bytes(&self) -> Bytes {
let len = self.encoded_len();
let mut buf = BytesMut::with_capacity(len + encoded_len_varint(len as u64));
encode_varint(len as u64, &mut buf);
self.raw_encode(&mut buf);
buf.freeze()
}
fn encode_length_delimited_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError> {
self.encode_length_delimited(buf)
}
}
impl<T> OwnedMessage for T
where
T: RawMessageDecoder + Sized,
{
fn decode<B: Buf>(mut buf: B) -> Result<Self, DecodeError> {
Self::decode_capped(Capped::new(&mut buf))
}
fn decode_length_delimited<B: Buf>(mut buf: B) -> Result<Self, DecodeError> {
Self::decode_capped(Capped::new_length_delimited(&mut buf)?)
}
#[doc(hidden)]
fn decode_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError> {
let mut message = Self::empty();
merge(&mut message, buf, DecodeContext::default())?;
Ok(message)
}
fn replace_from<B: Buf>(&mut self, mut buf: B) -> Result<(), DecodeError> {
self.replace_from_capped(Capped::new(&mut buf))
}
fn replace_from_length_delimited<B: Buf>(&mut self, mut buf: B) -> Result<(), DecodeError> {
self.replace_from_capped(Capped::new_length_delimited(&mut buf)?)
}
#[doc(hidden)]
fn replace_from_capped<B: Buf + ?Sized>(&mut self, buf: Capped<B>) -> Result<(), DecodeError> {
self.clear();
// MSRV: here, and elsewhere, this `map_err` could be `inspect_err` (1.76)
merge(self, buf, DecodeContext::default()).map_err(|err| {
self.clear();
err
})
}
fn replace_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
self.replace_from(buf)
}
fn replace_from_length_delimited_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
self.replace_from_length_delimited(buf)
}
fn replace_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
self.replace_from(buf)
}
fn replace_from_length_delimited_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
self.replace_from_length_delimited(buf)
}
#[doc(hidden)]
fn replace_from_capped_dyn(&mut self, buf: Capped<dyn Buf>) -> Result<(), DecodeError> {
self.replace_from_capped(buf)
}
}
impl<T> DistinguishedOwnedMessage for T
where
T: RawDistinguishedMessageDecoder + RawMessageDecoder,
{
fn decode_distinguished<B: Buf>(buf: B) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted(buf, NotCanonical)
}
fn decode_distinguished_length_delimited<B: Buf>(
buf: B,
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_length_delimited(buf, NotCanonical)
}
#[doc(hidden)]
fn decode_distinguished_capped<B: Buf + ?Sized>(
buf: Capped<B>,
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_capped(buf, NotCanonical)
}
fn replace_distinguished_from<B: Buf>(&mut self, buf: B) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from(buf, NotCanonical)
}
fn replace_distinguished_from_length_delimited<B: Buf>(
&mut self,
buf: B,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_length_delimited(buf, NotCanonical)
}
#[doc(hidden)]
fn replace_distinguished_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_capped(buf, NotCanonical)
}
fn replace_distinguished_from_slice(&mut self, buf: &[u8]) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from(buf, NotCanonical)
}
fn replace_distinguished_from_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from(buf, NotCanonical)
}
fn replace_distinguished_from_length_delimited_slice(
&mut self,
buf: &[u8],
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_length_delimited(buf, NotCanonical)
}
fn replace_distinguished_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_length_delimited(buf, NotCanonical)
}
#[doc(hidden)]
fn replace_distinguished_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_capped(buf, NotCanonical)
}
fn decode_restricted<B: Buf>(
mut buf: B,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_capped(Capped::new(&mut buf), restrict_to)
}
fn decode_restricted_length_delimited<B: Buf>(
mut buf: B,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_capped(Capped::new_length_delimited(&mut buf)?, restrict_to)
}
fn decode_restricted_capped<B: Buf + ?Sized>(
buf: Capped<B>,
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError> {
let mut message = Self::empty();
let ctx = RestrictedDecodeContext::new(restrict_to);
let canon = merge_distinguished(&mut message, buf, ctx.clone())
// Safety backstop to ensure we do not return a canonicity worse than restrict_to.
// See the docs on `RestrictedDecodeContext::check` for details on canonicity
// checking.
.and_then(|canon| ctx.check(canon))?;
Ok((message, canon))
}
fn replace_restricted_from<B: Buf>(
&mut self,
mut buf: B,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_capped(Capped::new(&mut buf), restrict_to)
}
fn replace_restricted_from_length_delimited<B: Buf>(
&mut self,
mut buf: B,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_capped(Capped::new_length_delimited(&mut buf)?, restrict_to)
}
fn replace_restricted_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.clear();
let ctx = RestrictedDecodeContext::new(restrict_to);
merge_distinguished(self, buf, ctx.clone())
.map_err(|err| {
self.clear();
err
})
// Safety backstop to ensure we do not return a canonicity worse than restrict_to.
// See the docs on `RestrictedDecodeContext::check` for details on canonicity
// checking.
.and_then(|canon| ctx.check(canon))
}
fn replace_restricted_from_slice(
&mut self,
buf: &[u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from(buf, restrict_to)
}
fn replace_restricted_from_dyn(
&mut self,
buf: &mut dyn Buf,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from(buf, restrict_to)
}
fn replace_restricted_from_length_delimited_slice(
&mut self,
buf: &[u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_length_delimited(buf, restrict_to)
}
fn replace_restricted_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_length_delimited(buf, restrict_to)
}
fn replace_restricted_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_from_capped(buf, restrict_to)
}
fn decode_canonical<B: Buf>(buf: B) -> Result<Self, DecodeError> {
Self::decode_restricted(buf, Canonical).map(|(val, _)| val)
}
fn decode_canonical_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError> {
Self::decode_restricted_length_delimited(buf, Canonical).map(|(val, _)| val)
}
#[doc(hidden)]
fn decode_canonical_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError> {
Self::decode_restricted_capped(buf, Canonical).map(|(val, _)| val)
}
fn replace_canonical_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError> {
self.replace_restricted_from(buf, Canonical).map(|_| ())
}
fn replace_canonical_from_length_delimited<B: Buf>(
&mut self,
buf: B,
) -> Result<(), DecodeError> {
self.replace_restricted_from_length_delimited(buf, Canonical)
.map(|_| ())
}
#[doc(hidden)]
fn replace_canonical_from_capped<B: Buf + ?Sized>(
&mut self,
buf: Capped<B>,
) -> Result<(), DecodeError> {
self.replace_restricted_from_capped(buf, Canonical)
.map(|_| ())
}
fn replace_canonical_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
self.replace_restricted_from(buf, Canonical).map(|_| ())
}
fn replace_canonical_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
self.replace_restricted_from(buf, Canonical).map(|_| ())
}
fn replace_canonical_from_length_delimited_slice(
&mut self,
buf: &[u8],
) -> Result<(), DecodeError> {
self.replace_restricted_from_length_delimited(buf, Canonical)
.map(|_| ())
}
fn replace_canonical_from_length_delimited_dyn(
&mut self,
buf: &mut dyn Buf,
) -> Result<(), DecodeError> {
self.replace_restricted_from_length_delimited(buf, Canonical)
.map(|_| ())
}
#[doc(hidden)]
fn replace_canonical_from_capped_dyn(
&mut self,
buf: Capped<dyn Buf>,
) -> Result<(), DecodeError> {
self.replace_restricted_from_capped(buf, Canonical)
.map(|_| ())
}
}
impl<'a, T> BorrowedMessage<'a> for T
where
T: RawMessageBorrowDecoder<'a> + Sized,
{
fn decode_borrowed(mut buf: &'a [u8]) -> Result<Self, DecodeError> {
let mut message = Self::empty();
borrow_merge(
&mut message,
Capped::new(&mut buf),
DecodeContext::default(),
)?;
Ok(message)
}
fn decode_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError> {
Self::decode_borrowed(Capped::new(buf).take_borrowed_length_delimited()?)
}
fn replace_borrowed_from(&mut self, mut buf: &'a [u8]) -> Result<(), DecodeError> {
self.clear();
borrow_merge(self, Capped::new(&mut buf), DecodeContext::default()).map_err(|err| {
self.clear();
err
})
}
fn replace_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<(), DecodeError> {
self.replace_borrowed_from(Capped::new(buf).take_borrowed_length_delimited()?)
}
}
impl<'a, T> DistinguishedBorrowedMessage<'a> for T
where
T: RawDistinguishedMessageBorrowDecoder<'a> + RawMessageBorrowDecoder<'a>,
{
fn decode_distinguished_borrowed(buf: &'a [u8]) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_borrowed(buf, NotCanonical)
}
fn decode_distinguished_borrowed_length_delimited(
buf: &mut &'a [u8],
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_borrowed_length_delimited(buf, NotCanonical)
}
fn replace_distinguished_borrowed_from(
&mut self,
buf: &'a [u8],
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_borrowed_from(buf, NotCanonical)
}
fn replace_distinguished_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_borrowed_from_length_delimited(buf, NotCanonical)
}
fn decode_restricted_borrowed(
mut buf: &'a [u8],
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError> {
let mut message = Self::empty();
let ctx = RestrictedDecodeContext::new(restrict_to);
let canon = borrow_merge_distinguished(&mut message, Capped::new(&mut buf), ctx.clone())
// Safety backstop to ensure we do not return a canonicity worse than restrict_to.
// See the docs on `RestrictedDecodeContext::check` for details on canonicity
// checking.
.and_then(|canon| ctx.check(canon))?;
Ok((message, canon))
}
fn decode_restricted_borrowed_length_delimited(
buf: &mut &'a [u8],
restrict_to: Canonicity,
) -> Result<(Self, Canonicity), DecodeError> {
Self::decode_restricted_borrowed(
Capped::new(buf).take_borrowed_length_delimited()?,
restrict_to,
)
}
fn replace_restricted_borrowed_from(
&mut self,
mut buf: &'a [u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.clear();
let ctx = RestrictedDecodeContext::new(restrict_to);
borrow_merge_distinguished(self, Capped::new(&mut buf), ctx.clone())
.map_err(|err| {
self.clear();
err
})
// Safety backstop to ensure we do not return a canonicity worse than restrict_to.
// See the docs on `RestrictedDecodeContext::check` for details on canonicity
// checking.
.and_then(|canon| ctx.check(canon))
}
fn replace_restricted_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
restrict_to: Canonicity,
) -> Result<Canonicity, DecodeError> {
self.replace_restricted_borrowed_from(
Capped::new(buf).take_borrowed_length_delimited()?,
restrict_to,
)
}
fn decode_canonical_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError> {
Self::decode_restricted_borrowed(buf, Canonical).map(|(val, _)| val)
}
fn decode_canonical_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError> {
Self::decode_restricted_borrowed_length_delimited(buf, Canonical).map(|(val, _)| val)
}
fn replace_canonical_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError> {
self.replace_restricted_borrowed_from(buf, Canonical)
.map(|_| ())
}
fn replace_canonical_borrowed_from_length_delimited(
&mut self,
buf: &mut &'a [u8],
) -> Result<(), DecodeError> {
self.replace_restricted_borrowed_from_length_delimited(buf, Canonical)
.map(|_| ())
}
}
#[cfg(test)]
mod tests {
use super::{
BorrowedMessage, DistinguishedBorrowedMessage, DistinguishedOwnedMessage, Message,
OwnedMessage,
};
use alloc::vec::Vec;
const _MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn Message> = None;
const _OWNED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn OwnedMessage> = None;
const _DISTINGUISHED_OWNED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn DistinguishedOwnedMessage> =
None;
const _BORROWED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn BorrowedMessage<'static>> = None;
const _DISTINGUISHED_BORROWED_MESSAGE_IS_DYN_COMPATIBLE: Option<
&dyn DistinguishedBorrowedMessage<'static>,
> = None;
fn use_dyn_owned_messages<M: DistinguishedOwnedMessage>(
safe: &mut dyn DistinguishedOwnedMessage,
mut msg: M,
) {
let mut vec = Vec::<u8>::new();
safe.encoded_len();
safe.encode_dyn(&mut vec).unwrap();
assert_eq!(vec, safe.encode_to_vec());
assert_eq!(vec, safe.encode_contiguous().into_vec());
safe.replace_from_length_delimited_dyn(&mut [0u8].as_slice())
.unwrap();
assert!(safe.message_is_empty());
safe.replace_canonical_from_length_delimited_dyn(&mut [0u8].as_slice())
.unwrap();
assert!(safe.message_is_empty());
safe.replace_from_slice(&[]).unwrap();
assert!(safe.message_is_empty());
safe.replace_canonical_from_slice(&[]).unwrap();
assert!(safe.message_is_empty());
msg.encoded_len();
msg = M::decode_length_delimited(&mut [0u8].as_slice()).unwrap();
msg.encode(&mut vec).unwrap();
msg.clear_message();
}
fn use_dyn_borrowed_messages<'a, M: DistinguishedBorrowedMessage<'a>>(
safe: &mut dyn DistinguishedBorrowedMessage<'a>,
mut msg: M,
) {
let mut vec = Vec::<u8>::new();
safe.encoded_len();
safe.encode_dyn(&mut vec).unwrap();
assert_eq!(vec, safe.encode_to_vec());
safe.replace_borrowed_from_length_delimited(&mut [0u8].as_slice())
.unwrap();
assert!(safe.message_is_empty());
safe.replace_canonical_borrowed_from_length_delimited(&mut [0u8].as_slice())
.unwrap();
assert!(safe.message_is_empty());
msg.encoded_len();
msg = M::decode_borrowed_length_delimited(&mut [0u8].as_slice()).unwrap();
msg.encode(&mut vec).unwrap();
msg.clear_message();
}
#[test]
fn using_dyn_messages() {
let mut vec = Vec::<u8>::new();
use_dyn_owned_messages(&mut (), ());
use_dyn_borrowed_messages(&mut (), ());
assert_eq!(().encoded_len(), 0);
().encode(&mut vec).unwrap();
().encode_dyn(&mut vec).unwrap();
<()>::decode(&mut [].as_slice()).unwrap();
}
}