forked from tokio-rs/prost
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathencoding.rs
1770 lines (1579 loc) · 52.6 KB
/
encoding.rs
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
//! Utility functions and types for encoding and decoding Protobuf types.
//!
//! Meant to be used only from `Message` implementations.
#![allow(clippy::implicit_hasher, clippy::ptr_arg)]
use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::min;
use core::convert::TryFrom;
use core::mem;
use core::str;
use core::u32;
use core::usize;
use ::bytes::{Buf, BufMut, Bytes};
use crate::DecodeError;
use crate::Message;
/// Encodes an integer value into LEB128 variable length format, and writes it to the buffer.
/// The buffer must have enough remaining space (maximum 10 bytes).
#[inline]
pub fn encode_varint<B>(mut value: u64, buf: &mut B)
where
B: BufMut,
{
// Safety notes:
//
// - ptr::write is an unsafe raw pointer write. The use here is safe since the length of the
// uninit slice is checked.
// - advance_mut is unsafe because it could cause uninitialized memory to be advanced over. The
// use here is safe since each byte which is advanced over has been written to in the
// previous loop iteration.
unsafe {
let mut i;
'outer: loop {
i = 0;
let uninit_slice = buf.chunk_mut();
for offset in 0..uninit_slice.len() {
i += 1;
let ptr = uninit_slice.as_mut_ptr().add(offset);
if value < 0x80 {
ptr.write(value as u8);
break 'outer;
} else {
ptr.write(((value & 0x7F) | 0x80) as u8);
value >>= 7;
}
}
buf.advance_mut(i);
debug_assert!(buf.has_remaining_mut());
}
buf.advance_mut(i);
}
}
/// Decodes a LEB128-encoded variable length integer from the buffer.
pub fn decode_varint<B>(buf: &mut B) -> Result<u64, DecodeError>
where
B: Buf,
{
let bytes = buf.chunk();
let len = bytes.len();
if len == 0 {
return Err(DecodeError::new("invalid varint"));
}
let byte = unsafe { *bytes.get_unchecked(0) };
if byte < 0x80 {
buf.advance(1);
Ok(u64::from(byte))
} else if len > 10 || bytes[len - 1] < 0x80 {
let (value, advance) = unsafe { decode_varint_slice(bytes) }?;
buf.advance(advance);
Ok(value)
} else {
decode_varint_slow(buf)
}
}
/// Decodes a LEB128-encoded variable length integer from the slice, returning the value and the
/// number of bytes read.
///
/// Based loosely on [`ReadVarint64FromArray`][1].
///
/// ## Safety
///
/// The caller must ensure that `bytes` is non-empty and either `bytes.len() >= 10` or the last
/// element in bytes is < `0x80`.
///
/// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.cc#L365-L406
#[inline]
unsafe fn decode_varint_slice(bytes: &[u8]) -> Result<(u64, usize), DecodeError> {
// Fully unrolled varint decoding loop. Splitting into 32-bit pieces gives better performance.
let mut b: u8;
let mut part0: u32;
b = *bytes.get_unchecked(0);
part0 = u32::from(b);
if b < 0x80 {
return Ok((u64::from(part0), 1));
};
part0 -= 0x80;
b = *bytes.get_unchecked(1);
part0 += u32::from(b) << 7;
if b < 0x80 {
return Ok((u64::from(part0), 2));
};
part0 -= 0x80 << 7;
b = *bytes.get_unchecked(2);
part0 += u32::from(b) << 14;
if b < 0x80 {
return Ok((u64::from(part0), 3));
};
part0 -= 0x80 << 14;
b = *bytes.get_unchecked(3);
part0 += u32::from(b) << 21;
if b < 0x80 {
return Ok((u64::from(part0), 4));
};
part0 -= 0x80 << 21;
let value = u64::from(part0);
let mut part1: u32;
b = *bytes.get_unchecked(4);
part1 = u32::from(b);
if b < 0x80 {
return Ok((value + (u64::from(part1) << 28), 5));
};
part1 -= 0x80;
b = *bytes.get_unchecked(5);
part1 += u32::from(b) << 7;
if b < 0x80 {
return Ok((value + (u64::from(part1) << 28), 6));
};
part1 -= 0x80 << 7;
b = *bytes.get_unchecked(6);
part1 += u32::from(b) << 14;
if b < 0x80 {
return Ok((value + (u64::from(part1) << 28), 7));
};
part1 -= 0x80 << 14;
b = *bytes.get_unchecked(7);
part1 += u32::from(b) << 21;
if b < 0x80 {
return Ok((value + (u64::from(part1) << 28), 8));
};
part1 -= 0x80 << 21;
let value = value + ((u64::from(part1)) << 28);
let mut part2: u32;
b = *bytes.get_unchecked(8);
part2 = u32::from(b);
if b < 0x80 {
return Ok((value + (u64::from(part2) << 56), 9));
};
part2 -= 0x80;
b = *bytes.get_unchecked(9);
part2 += u32::from(b) << 7;
if b < 0x80 {
return Ok((value + (u64::from(part2) << 56), 10));
};
// We have overrun the maximum size of a varint (10 bytes). Assume the data is corrupt.
Err(DecodeError::new("invalid varint"))
}
/// Decodes a LEB128-encoded variable length integer from the buffer, advancing the buffer as
/// necessary.
#[inline(never)]
fn decode_varint_slow<B>(buf: &mut B) -> Result<u64, DecodeError>
where
B: Buf,
{
let mut value = 0;
for count in 0..min(10, buf.remaining()) {
let byte = buf.get_u8();
value |= u64::from(byte & 0x7F) << (count * 7);
if byte <= 0x7F {
return Ok(value);
}
}
Err(DecodeError::new("invalid varint"))
}
/// Additional information passed to every decode/merge function.
///
/// The context should be passed by value and can be freely cloned. When passing
/// to a function which is decoding a nested object, then use `enter_recursion`.
#[derive(Clone, Debug)]
pub struct DecodeContext {
/// How many times we can recurse in the current decode stack before we hit
/// the recursion limit.
///
/// The recursion limit is defined by `RECURSION_LIMIT` and cannot be
/// customized. The recursion limit can be ignored by building the Prost
/// crate with the `no-recursion-limit` feature.
#[cfg(not(feature = "no-recursion-limit"))]
recurse_count: u32,
}
impl Default for DecodeContext {
#[cfg(not(feature = "no-recursion-limit"))]
#[inline]
fn default() -> DecodeContext {
DecodeContext {
recurse_count: crate::RECURSION_LIMIT,
}
}
#[cfg(feature = "no-recursion-limit")]
#[inline]
fn default() -> DecodeContext {
DecodeContext {}
}
}
impl DecodeContext {
/// Call this function before recursively decoding.
///
/// There is no `exit` function since this function creates a new `DecodeContext`
/// to be used at the next level of recursion. Continue to use the old context
// at the previous level of recursion.
#[cfg(not(feature = "no-recursion-limit"))]
#[inline]
pub(crate) fn enter_recursion(&self) -> DecodeContext {
DecodeContext {
recurse_count: self.recurse_count - 1,
}
}
#[cfg(feature = "no-recursion-limit")]
#[inline]
pub(crate) fn enter_recursion(&self) -> DecodeContext {
DecodeContext {}
}
/// Checks whether the recursion limit has been reached in the stack of
/// decodes described by the `DecodeContext` at `self.ctx`.
///
/// Returns `Ok<()>` if it is ok to continue recursing.
/// Returns `Err<DecodeError>` if the recursion limit has been reached.
#[cfg(not(feature = "no-recursion-limit"))]
#[inline]
pub(crate) fn limit_reached(&self) -> Result<(), DecodeError> {
if self.recurse_count == 0 {
Err(DecodeError::new("recursion limit reached"))
} else {
Ok(())
}
}
#[cfg(feature = "no-recursion-limit")]
#[inline]
#[allow(clippy::unnecessary_wraps)] // needed in other features
pub(crate) fn limit_reached(&self) -> Result<(), DecodeError> {
Ok(())
}
}
/// Returns the encoded length of the value in LEB128 variable length format.
/// The returned value will be between 1 and 10, inclusive.
#[inline]
pub fn encoded_len_varint(value: u64) -> usize {
// Based on [VarintSize64][1].
// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.h#L1301-L1309
((((value | 1).leading_zeros() ^ 63) * 9 + 73) / 64) as usize
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum WireType {
Varint = 0,
SixtyFourBit = 1,
LengthDelimited = 2,
StartGroup = 3,
EndGroup = 4,
ThirtyTwoBit = 5,
}
pub const MIN_TAG: u32 = 1;
pub const MAX_TAG: u32 = (1 << 29) - 1;
impl TryFrom<u64> for WireType {
type Error = DecodeError;
#[inline]
fn try_from(value: u64) -> Result<Self, Self::Error> {
match value {
0 => Ok(WireType::Varint),
1 => Ok(WireType::SixtyFourBit),
2 => Ok(WireType::LengthDelimited),
3 => Ok(WireType::StartGroup),
4 => Ok(WireType::EndGroup),
5 => Ok(WireType::ThirtyTwoBit),
_ => Err(DecodeError::new(format!(
"invalid wire type value: {}",
value
))),
}
}
}
/// Encodes a Protobuf field key, which consists of a wire type designator and
/// the field tag.
#[inline]
pub fn encode_key<B>(tag: u32, wire_type: WireType, buf: &mut B)
where
B: BufMut,
{
debug_assert!((MIN_TAG..=MAX_TAG).contains(&tag));
let key = (tag << 3) | wire_type as u32;
encode_varint(u64::from(key), buf);
}
/// Decodes a Protobuf field key, which consists of a wire type designator and
/// the field tag.
#[inline(always)]
pub fn decode_key<B>(buf: &mut B) -> Result<(u32, WireType), DecodeError>
where
B: Buf,
{
let key = decode_varint(buf)?;
if key > u64::from(u32::MAX) {
return Err(DecodeError::new(format!("invalid key value: {}", key)));
}
let wire_type = WireType::try_from(key & 0x07)?;
let tag = key as u32 >> 3;
if tag < MIN_TAG {
return Err(DecodeError::new("invalid tag value: 0"));
}
Ok((tag, wire_type))
}
/// Returns the width of an encoded Protobuf field key with the given tag.
/// The returned width will be between 1 and 5 bytes (inclusive).
#[inline]
pub fn key_len(tag: u32) -> usize {
encoded_len_varint(u64::from(tag << 3))
}
/// Checks that the expected wire type matches the actual wire type,
/// or returns an error result.
#[inline]
pub fn check_wire_type(expected: WireType, actual: WireType) -> Result<(), DecodeError> {
if expected != actual {
return Err(DecodeError::new(format!(
"invalid wire type: {:?} (expected {:?})",
actual, expected
)));
}
Ok(())
}
/// Helper function which abstracts reading a length delimiter prefix followed
/// by decoding values until the length of bytes is exhausted.
pub fn merge_loop<T, M, B>(
value: &mut T,
buf: &mut B,
ctx: DecodeContext,
mut merge: M,
) -> Result<(), DecodeError>
where
M: FnMut(&mut T, &mut B, DecodeContext) -> Result<(), DecodeError>,
B: Buf,
{
let len = decode_varint(buf)?;
let remaining = buf.remaining();
if len > remaining as u64 {
return Err(DecodeError::new("buffer underflow"));
}
let limit = remaining - len as usize;
while buf.remaining() > limit {
merge(value, buf, ctx.clone())?;
}
if buf.remaining() != limit {
return Err(DecodeError::new("delimited length exceeded"));
}
Ok(())
}
pub fn skip_field<B>(
wire_type: WireType,
tag: u32,
buf: &mut B,
ctx: DecodeContext,
) -> Result<(), DecodeError>
where
B: Buf,
{
ctx.limit_reached()?;
let len = match wire_type {
WireType::Varint => decode_varint(buf).map(|_| 0)?,
WireType::ThirtyTwoBit => 4,
WireType::SixtyFourBit => 8,
WireType::LengthDelimited => decode_varint(buf)?,
WireType::StartGroup => loop {
let (inner_tag, inner_wire_type) = decode_key(buf)?;
match inner_wire_type {
WireType::EndGroup => {
if inner_tag != tag {
return Err(DecodeError::new("unexpected end group tag"));
}
break 0;
}
_ => skip_field(inner_wire_type, inner_tag, buf, ctx.enter_recursion())?,
}
},
WireType::EndGroup => return Err(DecodeError::new("unexpected end group tag")),
};
if len > buf.remaining() as u64 {
return Err(DecodeError::new("buffer underflow"));
}
buf.advance(len as usize);
Ok(())
}
/// Helper macro which emits an `encode_repeated` function for the type.
macro_rules! encode_repeated {
($ty:ty) => {
pub fn encode_repeated<B>(tag: u32, values: &[$ty], buf: &mut B)
where
B: BufMut,
{
for value in values {
encode(tag, value, buf);
}
}
};
}
/// Helper macro which emits a `merge_repeated` function for the numeric type.
macro_rules! merge_repeated_numeric {
($ty:ty,
$wire_type:expr,
$merge:ident,
$merge_repeated:ident) => {
pub fn $merge_repeated<B>(
wire_type: WireType,
values: &mut Vec<$ty>,
buf: &mut B,
ctx: DecodeContext,
) -> Result<(), DecodeError>
where
B: Buf,
{
if wire_type == WireType::LengthDelimited {
// Packed.
merge_loop(values, buf, ctx, |values, buf, ctx| {
let mut value = Default::default();
$merge($wire_type, &mut value, buf, ctx)?;
values.push(value);
Ok(())
})
} else {
// Unpacked.
check_wire_type($wire_type, wire_type)?;
let mut value = Default::default();
$merge(wire_type, &mut value, buf, ctx)?;
values.push(value);
Ok(())
}
}
};
}
/// Macro which emits a module containing a set of encoding functions for a
/// variable width numeric type.
macro_rules! varint {
($ty:ty,
$proto_ty:ident) => (
varint!($ty,
$proto_ty,
to_uint64(value) { *value as u64 },
from_uint64(value) { value as $ty });
);
($ty:ty,
$proto_ty:ident,
to_uint64($to_uint64_value:ident) $to_uint64:expr,
from_uint64($from_uint64_value:ident) $from_uint64:expr) => (
pub mod $proto_ty {
use crate::encoding::*;
pub fn encode<B>(tag: u32, $to_uint64_value: &$ty, buf: &mut B) where B: BufMut {
encode_key(tag, WireType::Varint, buf);
encode_varint($to_uint64, buf);
}
pub fn merge<B>(wire_type: WireType, value: &mut $ty, buf: &mut B, _ctx: DecodeContext) -> Result<(), DecodeError> where B: Buf {
check_wire_type(WireType::Varint, wire_type)?;
let $from_uint64_value = decode_varint(buf)?;
*value = $from_uint64;
Ok(())
}
encode_repeated!($ty);
pub fn encode_packed<B>(tag: u32, values: &[$ty], buf: &mut B) where B: BufMut {
if values.is_empty() { return; }
encode_key(tag, WireType::LengthDelimited, buf);
let len: usize = values.iter().map(|$to_uint64_value| {
encoded_len_varint($to_uint64)
}).sum();
encode_varint(len as u64, buf);
for $to_uint64_value in values {
encode_varint($to_uint64, buf);
}
}
merge_repeated_numeric!($ty, WireType::Varint, merge, merge_repeated);
#[inline]
pub fn encoded_len(tag: u32, $to_uint64_value: &$ty) -> usize {
key_len(tag) + encoded_len_varint($to_uint64)
}
#[inline]
pub fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
key_len(tag) * values.len() + values.iter().map(|$to_uint64_value| {
encoded_len_varint($to_uint64)
}).sum::<usize>()
}
#[inline]
pub fn encoded_len_packed(tag: u32, values: &[$ty]) -> usize {
if values.is_empty() {
0
} else {
let len = values.iter()
.map(|$to_uint64_value| encoded_len_varint($to_uint64))
.sum::<usize>();
key_len(tag) + encoded_len_varint(len as u64) + len
}
}
#[cfg(test)]
mod test {
use proptest::prelude::*;
use crate::encoding::$proto_ty::*;
use crate::encoding::test::{
check_collection_type,
check_type,
};
proptest! {
#[test]
fn check(value: $ty, tag in MIN_TAG..=MAX_TAG) {
check_type(value, tag, WireType::Varint,
encode, merge, encoded_len)?;
}
#[test]
fn check_repeated(value: Vec<$ty>, tag in MIN_TAG..=MAX_TAG) {
check_collection_type(value, tag, WireType::Varint,
encode_repeated, merge_repeated,
encoded_len_repeated)?;
}
#[test]
fn check_packed(value: Vec<$ty>, tag in MIN_TAG..=MAX_TAG) {
check_type(value, tag, WireType::LengthDelimited,
encode_packed, merge_repeated,
encoded_len_packed)?;
}
}
}
}
);
}
varint!(bool, bool,
to_uint64(value) if *value { 1u64 } else { 0u64 },
from_uint64(value) value != 0);
varint!(i32, int32);
varint!(i64, int64);
varint!(u32, uint32);
varint!(u64, uint64);
varint!(i32, sint32,
to_uint64(value) {
((value << 1) ^ (value >> 31)) as u32 as u64
},
from_uint64(value) {
let value = value as u32;
((value >> 1) as i32) ^ (-((value & 1) as i32))
});
varint!(i64, sint64,
to_uint64(value) {
((value << 1) ^ (value >> 63)) as u64
},
from_uint64(value) {
((value >> 1) as i64) ^ (-((value & 1) as i64))
});
/// Macro which emits a module containing a set of encoding functions for a
/// fixed width numeric type.
macro_rules! fixed_width {
($ty:ty,
$width:expr,
$wire_type:expr,
$proto_ty:ident,
$put:ident,
$get:ident) => {
pub mod $proto_ty {
use crate::encoding::*;
pub fn encode<B>(tag: u32, value: &$ty, buf: &mut B)
where
B: BufMut,
{
encode_key(tag, $wire_type, buf);
buf.$put(*value);
}
pub fn merge<B>(
wire_type: WireType,
value: &mut $ty,
buf: &mut B,
_ctx: DecodeContext,
) -> Result<(), DecodeError>
where
B: Buf,
{
check_wire_type($wire_type, wire_type)?;
if buf.remaining() < $width {
return Err(DecodeError::new("buffer underflow"));
}
*value = buf.$get();
Ok(())
}
encode_repeated!($ty);
pub fn encode_packed<B>(tag: u32, values: &[$ty], buf: &mut B)
where
B: BufMut,
{
if values.is_empty() {
return;
}
encode_key(tag, WireType::LengthDelimited, buf);
let len = values.len() as u64 * $width;
encode_varint(len as u64, buf);
for value in values {
buf.$put(*value);
}
}
merge_repeated_numeric!($ty, $wire_type, merge, merge_repeated);
#[inline]
pub fn encoded_len(tag: u32, _: &$ty) -> usize {
key_len(tag) + $width
}
#[inline]
pub fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
(key_len(tag) + $width) * values.len()
}
#[inline]
pub fn encoded_len_packed(tag: u32, values: &[$ty]) -> usize {
if values.is_empty() {
0
} else {
let len = $width * values.len();
key_len(tag) + encoded_len_varint(len as u64) + len
}
}
#[cfg(test)]
mod test {
use proptest::prelude::*;
use super::super::test::{check_collection_type, check_type};
use super::*;
proptest! {
#[test]
fn check(value: $ty, tag in MIN_TAG..=MAX_TAG) {
check_type(value, tag, $wire_type,
encode, merge, encoded_len)?;
}
#[test]
fn check_repeated(value: Vec<$ty>, tag in MIN_TAG..=MAX_TAG) {
check_collection_type(value, tag, $wire_type,
encode_repeated, merge_repeated,
encoded_len_repeated)?;
}
#[test]
fn check_packed(value: Vec<$ty>, tag in MIN_TAG..=MAX_TAG) {
check_type(value, tag, WireType::LengthDelimited,
encode_packed, merge_repeated,
encoded_len_packed)?;
}
}
}
}
};
}
fixed_width!(
f32,
4,
WireType::ThirtyTwoBit,
float,
put_f32_le,
get_f32_le
);
fixed_width!(
f64,
8,
WireType::SixtyFourBit,
double,
put_f64_le,
get_f64_le
);
fixed_width!(
u32,
4,
WireType::ThirtyTwoBit,
fixed32,
put_u32_le,
get_u32_le
);
fixed_width!(
u64,
8,
WireType::SixtyFourBit,
fixed64,
put_u64_le,
get_u64_le
);
fixed_width!(
i32,
4,
WireType::ThirtyTwoBit,
sfixed32,
put_i32_le,
get_i32_le
);
fixed_width!(
i64,
8,
WireType::SixtyFourBit,
sfixed64,
put_i64_le,
get_i64_le
);
/// Macro which emits encoding functions for a length-delimited type.
macro_rules! length_delimited {
($ty:ty) => {
encode_repeated!($ty);
pub fn merge_repeated<B>(
wire_type: WireType,
values: &mut Vec<$ty>,
buf: &mut B,
ctx: DecodeContext,
) -> Result<(), DecodeError>
where
B: Buf,
{
check_wire_type(WireType::LengthDelimited, wire_type)?;
let mut value = Default::default();
merge(wire_type, &mut value, buf, ctx)?;
values.push(value);
Ok(())
}
#[inline]
pub fn encoded_len(tag: u32, value: &$ty) -> usize {
key_len(tag) + encoded_len_varint(value.len() as u64) + value.len()
}
#[inline]
pub fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
key_len(tag) * values.len()
+ values
.iter()
.map(|value| encoded_len_varint(value.len() as u64) + value.len())
.sum::<usize>()
}
};
}
pub mod string {
use super::*;
pub fn encode<B>(tag: u32, value: &String, buf: &mut B)
where
B: BufMut,
{
encode_key(tag, WireType::LengthDelimited, buf);
encode_varint(value.len() as u64, buf);
buf.put_slice(value.as_bytes());
}
pub fn merge<B>(
wire_type: WireType,
value: &mut String,
buf: &mut B,
ctx: DecodeContext,
) -> Result<(), DecodeError>
where
B: Buf,
{
// ## Unsafety
//
// `string::merge` reuses `bytes::merge`, with an additional check of utf-8
// well-formedness. If the utf-8 is not well-formed, or if any other error occurs, 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 `bytes::merge` or
// in the buf implementation, a drop guard is used.
unsafe {
struct DropGuard<'a>(&'a mut Vec<u8>);
impl<'a> Drop for DropGuard<'a> {
#[inline]
fn drop(&mut self) {
self.0.clear();
}
}
let drop_guard = DropGuard(value.as_mut_vec());
bytes::merge(wire_type, drop_guard.0, buf, ctx)?;
match str::from_utf8(drop_guard.0) {
Ok(_) => {
// Success; do not clear the bytes.
mem::forget(drop_guard);
Ok(())
}
Err(_) => Err(DecodeError::new(
"invalid string value: data is not UTF-8 encoded",
)),
}
}
}
length_delimited!(String);
#[cfg(test)]
mod test {
use proptest::prelude::*;
use super::super::test::{check_collection_type, check_type};
use super::*;
proptest! {
#[test]
fn check(value: String, tag in MIN_TAG..=MAX_TAG) {
super::test::check_type(value, tag, WireType::LengthDelimited,
encode, merge, encoded_len)?;
}
#[test]
fn check_repeated(value: Vec<String>, tag in MIN_TAG..=MAX_TAG) {
super::test::check_collection_type(value, tag, WireType::LengthDelimited,
encode_repeated, merge_repeated,
encoded_len_repeated)?;
}
}
}
}
pub trait BytesAdapter: sealed::BytesAdapter {}
mod sealed {
use super::{Buf, BufMut};
pub trait BytesAdapter: Default + Sized + 'static {
fn len(&self) -> usize;
/// Replace contents of this buffer with the contents of another buffer.
fn replace_with<B>(&mut self, buf: B)
where
B: Buf;
/// Appends this buffer to the (contents of) other buffer.
fn append_to<B>(&self, buf: &mut B)
where
B: BufMut;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
}
impl BytesAdapter for Bytes {}
impl sealed::BytesAdapter for Bytes {
fn len(&self) -> usize {
Buf::remaining(self)
}
fn replace_with<B>(&mut self, mut buf: B)
where
B: Buf,
{
*self = buf.copy_to_bytes(buf.remaining());
}
fn append_to<B>(&self, buf: &mut B)
where
B: BufMut,
{
buf.put(self.clone())
}
}
impl BytesAdapter for Vec<u8> {}
impl sealed::BytesAdapter for Vec<u8> {
fn len(&self) -> usize {
Vec::len(self)
}
fn replace_with<B>(&mut self, buf: B)
where
B: Buf,
{
self.clear();
self.reserve(buf.remaining());
self.put(buf);
}
fn append_to<B>(&self, buf: &mut B)
where
B: BufMut,
{
buf.put(self.as_slice())
}
}
pub mod bytes {
use super::*;
pub fn encode<A, B>(tag: u32, value: &A, buf: &mut B)
where
A: BytesAdapter,
B: BufMut,
{
encode_key(tag, WireType::LengthDelimited, buf);
encode_varint(value.len() as u64, buf);
value.append_to(buf);
}
pub fn merge<A, B>(
wire_type: WireType,
value: &mut A,
buf: &mut B,
_ctx: DecodeContext,
) -> Result<(), DecodeError>
where
A: BytesAdapter,
B: Buf,
{
check_wire_type(WireType::LengthDelimited, wire_type)?;
let len = decode_varint(buf)?;
if len > buf.remaining() as u64 {
return Err(DecodeError::new("buffer underflow"));
}
let len = len as usize;
// Clear the existing value. This follows from the following rule in the encoding guide[1]:
//
// > Normally, an encoded message would never have more than one instance of a non-repeated
// > field. However, parsers are expected to handle the case in which they do. For numeric
// > types and strings, if the same field appears multiple times, the parser accepts the
// > last value it sees.
//
// [1]: https://developers.google.com/protocol-buffers/docs/encoding#optional
value.replace_with(buf.copy_to_bytes(len));
Ok(())
}
length_delimited!(impl BytesAdapter);
#[cfg(test)]