proto_rs 0.11.24

Rust-first gRPC macros collection for .proto/protobufs managment and more
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
use crate::bytes::Buf;
use crate::bytes::BufMut;
use crate::encoding::DecodeContext;
use crate::encoding::WireType;
use crate::encoding::check_wire_type;
use crate::encoding::decode_varint;
use crate::encoding::encode_key;
use crate::encoding::encode_varint;
use crate::encoding::encoded_len_varint;
use crate::encoding::key_len;

/// Helper macro which emits an `encode_repeated` function for the type.
macro_rules! encode_repeated {
    ($ty:ty, by_value) => {
        pub fn encode_repeated(tag: u32, values: &[$ty], buf: &mut impl BufMut) {
            for &value in values {
                encode_tagged(tag, value, buf);
            }
        }
    };
    ($ty:ty, by_ref) => {
        pub fn encode_repeated(tag: u32, values: &[$ty], buf: &mut impl BufMut) {
            for value in values {
                encode_tagged(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(
            wire_type: WireType,
            values: &mut Vec<$ty>,
            buf: &mut impl Buf,
            ctx: DecodeContext,
        ) -> Result<(), DecodeError> {
            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(v) { v as u64 },
            from_uint64(v) { v as $ty });
    };

    ($ty:ty,
     $proto_ty:ident,
     to_uint64($v:ident) $to_uint64:expr,
     from_uint64($fv:ident) $from_uint64:expr) => {
        pub mod $proto_ty {
            use crate::encoding::*;

            #[inline]
            pub fn encode_tagged(tag: u32, $v: $ty, buf: &mut impl BufMut) {
                encode_key(tag, WireType::Varint, buf);
                encode_varint($to_uint64, buf);
            }

            #[inline]
            pub fn encode($v: $ty, buf: &mut impl BufMut) {
                encode_varint($to_uint64, buf);
            }

            #[inline]
            pub(crate) fn _encode_by_ref_tagged(tag: u32, value: &$ty, buf: &mut impl BufMut) {
                encode_tagged(tag, *value, buf);
            }
            #[inline]
            pub fn merge(
                wire_type: WireType,
                value: &mut $ty,
                buf: &mut impl Buf,
                _ctx: DecodeContext,
            ) -> Result<(), DecodeError> {
                check_wire_type(WireType::Varint, wire_type)?;
                let $fv = decode_varint(buf)?;
                *value = $from_uint64;
                Ok(())
            }

            encode_repeated!($ty, by_value);
            #[inline]
            pub fn encode_packed(tag: u32, values: &[$ty], buf: &mut impl BufMut) {
                if values.is_empty() {
                    return;
                }

                encode_key(tag, WireType::LengthDelimited, buf);
                let len: usize = values.iter()
                    .map(|&$v| encoded_len_varint($to_uint64))
                    .sum();
                encode_varint(len as u64, buf);

                for &$v in values {
                    encode_varint($to_uint64, buf);
                }
            }

            merge_repeated_numeric!($ty, WireType::Varint, merge, merge_repeated);

            #[inline]
            pub const  fn encoded_len_tagged(tag: u32, $v: $ty) -> usize {
                key_len(tag) + encoded_len_varint($to_uint64)
            }

            #[inline]
            pub const  fn encoded_len($v: $ty) -> usize {
                encoded_len_varint($to_uint64)
            }

            #[inline]
            pub(crate)  const  fn _encoded_len_by_ref_tagged(tag: u32, value: &$ty) -> usize {
                encoded_len_tagged(tag, *value)
            }

            #[inline]
            pub fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
                key_len(tag) * values.len()
                    + values.iter().map(|&$v| 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(|&$v| encoded_len_varint($to_uint64)).sum::<usize>();
                    key_len(tag) + encoded_len_varint(len as u64) + len
                }
            }
        }
    };
}
varint!(bool, bool,
        to_uint64(value) value as u64,
        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::*;

            #[inline]
            pub fn encode_tagged(tag: u32, value: $ty, buf: &mut impl BufMut) {
                encode_key(tag, $wire_type, buf);
                buf.$put(value);
            }
            #[inline]
            pub fn encode(value: $ty, buf: &mut impl BufMut) {
                buf.$put(value);
            }

            #[inline]
            pub(crate) fn _encode_by_ref_tagged(tag: u32, value: &$ty, buf: &mut impl BufMut) {
                encode_tagged(tag, *value, buf);
            }
            #[inline]
            pub fn merge(wire_type: WireType, value: &mut $ty, buf: &mut impl Buf, _ctx: DecodeContext) -> Result<(), DecodeError> {
                check_wire_type($wire_type, wire_type)?;
                if buf.remaining() < $width {
                    return Err(DecodeError::new("buffer underflow"));
                }
                *value = buf.$get();
                Ok(())
            }

            encode_repeated!($ty, by_value);
            #[inline]
            pub fn encode_packed(tag: u32, values: &[$ty], buf: &mut impl BufMut) {
                if values.is_empty() {
                    return;
                }

                encode_key(tag, WireType::LengthDelimited, buf);
                let len = values.len() as u64 * $width;
                encode_varint(len, buf);

                for &v in values {
                    buf.$put(v);
                }
            }

            merge_repeated_numeric!($ty, $wire_type, merge, merge_repeated);

            #[inline]
            pub const fn encoded_len(_value: $ty) -> usize {
                $width
            }
            #[inline]
            pub const fn encoded_len_tagged(tag: u32, _value: $ty) -> usize {
                key_len(tag) + $width
            }
            #[inline]
            pub(crate) const fn _encoded_len_by_ref_tagged(tag: u32, _value: &$ty) -> usize {
                encoded_len_tagged(tag, *_value)
            }

            #[inline]
            pub const fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
                (key_len(tag) + $width) * values.len()
            }

            #[inline]
            pub const 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
                }
            }
        }
    };
}

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_rules! length_delimited_encode {
    ($ty:ty) => {
        encode_repeated!($ty, by_ref);
        #[allow(clippy::ptr_arg)]
        #[inline]
        pub fn encoded_len_tagged(tag: u32, value: &$ty) -> usize {
            let len = value.len();
            key_len(tag) + encoded_len_varint(len as u64) + len
        }

        #[allow(clippy::ptr_arg)]
        #[inline]
        pub fn encoded_len(value: &$ty) -> usize {
            let len = value.len();
            encoded_len_varint(len as u64) + len
        }

        #[inline]
        pub(crate) fn _encoded_len_by_ref_tagged(tag: u32, value: &$ty) -> usize {
            encoded_len_tagged(tag, value)
        }

        #[inline]
        pub fn encoded_len_repeated(tag: u32, values: &[$ty]) -> usize {
            key_len(tag) * values.len()
                + values
                    .iter()
                    .map(|v| {
                        let len = v.len();
                        encoded_len_varint(len as u64) + len
                    })
                    .sum::<usize>()
        }
    };
}

macro_rules! length_delimited_decode {
    ($ty:ty) => {
        pub fn merge_repeated(
            wire_type: WireType,
            values: &mut Vec<$ty>,
            buf: &mut impl Buf,
            ctx: DecodeContext,
        ) -> Result<(), DecodeError> {
            check_wire_type(WireType::LengthDelimited, wire_type)?;
            let mut value = Default::default();
            merge(wire_type, &mut value, buf, ctx)?;
            values.push(value);
            Ok(())
        }
    };
}

pub mod string {
    use super::Buf;
    use super::BufMut;
    use super::DecodeContext;
    use super::WireType;
    use super::bytes;
    use super::check_wire_type;
    use super::encode_key;
    use super::encode_varint;
    use super::encoded_len_varint;
    use super::key_len;
    use crate::error::DecodeError;
    #[inline]
    pub fn encode_tagged(tag: u32, value: &String, buf: &mut impl BufMut) {
        encode_key(tag, WireType::LengthDelimited, buf);
        encode_varint(value.len() as u64, buf);
        buf.put_slice(value.as_bytes());
    }
    #[inline]
    pub fn encode(value: &String, buf: &mut impl BufMut) {
        buf.put_slice(value.as_bytes());
    }
    pub fn _encode_by_ref_tagged(tag: u32, value: &String, buf: &mut impl BufMut) {
        encode_tagged(tag, value, buf);
    }
    #[inline]
    pub fn merge(wire_type: WireType, value: &mut String, buf: &mut impl Buf, ctx: DecodeContext) -> Result<(), DecodeError> {
        // ## 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 Drop for DropGuard<'_> {
                #[inline]
                fn drop(&mut self) {
                    self.0.clear();
                }
            }

            let drop_guard = DropGuard(value.as_mut_vec());
            bytes::merge_one_copy(wire_type, drop_guard.0, buf, ctx)?;
            match str::from_utf8(drop_guard.0) {
                Ok(_) => {
                    // Success; do not clear the bytes.
                    core::mem::forget(drop_guard);
                    Ok(())
                }
                Err(_) => Err(DecodeError::new("invalid string value: data is not UTF-8 encoded")),
            }
        }
    }

    length_delimited_encode!(String);
    length_delimited_decode!(String);

    #[cfg(test)]
    mod test {
        use proptest::prelude::*;

        use super::*;
        use crate::encoding::MAX_TAG;
        use crate::encoding::MIN_TAG;
        use crate::encoding::test::check_type;

        proptest! {
            #[test]
            fn check(value: String, tag in MIN_TAG..=MAX_TAG) {
               check_type(value, tag, WireType::LengthDelimited,
                                        encode_tagged, merge, encoded_len_tagged)?;
            }
            #[test]
            fn check_repeated(value: Vec<String>, tag in MIN_TAG..=MAX_TAG) {
               crate::encoding::test::check_collection_type(value, tag, WireType::LengthDelimited,
                                                   encode_repeated, merge_repeated,
                                                   encoded_len_repeated)?;
            }
        }
    }
}

pub mod bytes {

    use super::Buf;
    use super::BufMut;
    use super::DecodeContext;
    use super::WireType;
    use super::check_wire_type;
    use super::decode_varint;
    use super::encode_key;
    use super::encode_varint;
    use super::encoded_len_varint;
    use super::key_len;
    use crate::encoding::BytesAdapterDecode;
    use crate::encoding::BytesAdapterEncode;
    use crate::error::DecodeError;

    #[inline]
    pub fn encode_tagged(tag: u32, value: &impl BytesAdapterEncode, buf: &mut impl BufMut) {
        encode_key(tag, WireType::LengthDelimited, buf);
        encode_varint(value.len() as u64, buf);
        value.append_to(buf);
    }

    #[inline]
    pub fn encode(value: &impl BytesAdapterEncode, buf: &mut impl BufMut) {
        value.append_to(buf);
    }
    #[inline]
    pub fn _encode_by_ref_tagged(tag: u32, value: &impl BytesAdapterEncode, buf: &mut impl BufMut) {
        encode_tagged(tag, value, buf);
    }
    #[inline]
    pub fn merge(
        wire_type: WireType,
        value: &mut impl BytesAdapterDecode,
        buf: &mut impl Buf,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        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://protobuf.dev/programming-guides/encoding/#last-one-wins
        //
        // This is intended for A and B both being Bytes so it is zero-copy.
        // Some combinations of A and B types may cause a double-copy,
        // in which case merge_one_copy() should be used instead.
        value.replace_with(buf.copy_to_bytes(len));
        Ok(())
    }
    #[inline]
    pub(super) fn merge_one_copy(
        wire_type: WireType,
        value: &mut impl BytesAdapterDecode,
        buf: &mut impl Buf,
        _ctx: DecodeContext,
    ) -> Result<(), DecodeError> {
        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;

        // If we must copy, make sure to copy only once.
        value.replace_with(buf.take(len));
        Ok(())
    }

    length_delimited_encode!(impl BytesAdapterEncode + std::default::Default);
    length_delimited_decode!(impl BytesAdapterDecode + std::default::Default);

    #[cfg(test)]
    mod test {
        use ::bytes::Bytes;
        use proptest::prelude::*;

        use super::*;
        use crate::encoding::MAX_TAG;
        use crate::encoding::MIN_TAG;
        proptest! {
            #[test]
            fn check_vec(value: Vec<u8>, tag in MIN_TAG..=MAX_TAG) {
                crate::encoding::test::check_type::<Vec<u8>, Vec<u8>>(value, tag, WireType::LengthDelimited,
                                                            encode_tagged, merge, encoded_len_tagged)?;
            }

            #[test]
            fn check_bytes(value: Vec<u8>, tag in MIN_TAG..=MAX_TAG) {
                let value = Bytes::from(value);
                crate::encoding::test::check_type::<Bytes, Bytes>(value, tag, WireType::LengthDelimited,
                                                        encode_tagged, merge, encoded_len_tagged)?;
            }

            #[test]
            fn check_repeated_vec(value: Vec<Vec<u8>>, tag in MIN_TAG..=MAX_TAG) {
                crate::encoding::test::check_collection_type(value, tag, WireType::LengthDelimited,
                                                   encode_repeated, merge_repeated,
                                                   encoded_len_repeated)?;
            }

            #[test]
            fn check_repeated_bytes(value: Vec<Vec<u8>>, tag in MIN_TAG..=MAX_TAG) {
                let value = value.into_iter().map(Bytes::from).collect();
                crate::encoding::test::check_collection_type(value, tag, WireType::LengthDelimited,
                                                   encode_repeated, merge_repeated,
                                                   encoded_len_repeated)?;
            }
        }
    }
}