1 #![doc(hidden)]
2 
3 //! `CodedInputStream` and `CodedOutputStream` implementations
4 
5 use std::io;
6 use std::io::Write;
7 use std::io::{BufRead, Read};
8 use std::mem;
9 use std::slice;
10 
11 #[cfg(feature = "bytes")]
12 use bytes::Bytes;
13 #[cfg(feature = "bytes")]
14 use chars::Chars;
15 
16 use buf_read_iter::BufReadIter;
17 use core::Message;
18 use enums::ProtobufEnum;
19 use error::ProtobufError;
20 use error::ProtobufResult;
21 use error::WireError;
22 use misc::remaining_capacity_as_slice_mut;
23 use misc::remove_lifetime_mut;
24 use unknown::UnknownFields;
25 use unknown::UnknownValue;
26 use unknown::UnknownValueRef;
27 use varint;
28 use zigzag::decode_zig_zag_32;
29 use zigzag::decode_zig_zag_64;
30 use zigzag::encode_zig_zag_32;
31 use zigzag::encode_zig_zag_64;
32 
33 /// Equal to the default buffer size of `BufWriter`, so when
34 /// `CodedOutputStream` wraps `BufWriter`, it often skips double buffering.
35 const OUTPUT_STREAM_BUFFER_SIZE: usize = 8 * 1024;
36 
37 /// Default recursion level limit. 100 is the default value of C++'s implementation.
38 const DEFAULT_RECURSION_LIMIT: u32 = 100;
39 
40 /// Max allocated vec when reading length-delimited from unknown input stream
41 pub(crate) const READ_RAW_BYTES_MAX_ALLOC: usize = 10_000_000;
42 
43 /// Serialization constants.
44 pub mod wire_format {
45     // TODO: temporary
46     pub use self::WireType::*;
47 
48     /// Tag occupies 3 bits
49     pub const TAG_TYPE_BITS: u32 = 3;
50     /// Tag mask
51     pub const TAG_TYPE_MASK: u32 = (1u32 << TAG_TYPE_BITS as usize) - 1;
52     /// Max possible field number
53     pub const FIELD_NUMBER_MAX: u32 = 0x1fffffff;
54 
55     /// One of six defined protobuf wire types
56     #[derive(PartialEq, Eq, Clone, Debug)]
57     pub enum WireType {
58         /// Varint (e. g. `int32` or `sint64`)
59         WireTypeVarint = 0,
60         /// Fixed size 64 bit (e. g. `fixed64` or `double`)
61         WireTypeFixed64 = 1,
62         /// Length-delimited (e. g. `message` or `string`)
63         WireTypeLengthDelimited = 2,
64         /// Groups are not supported by rust-protobuf
65         WireTypeStartGroup = 3,
66         /// Groups are not supported by rust-protobuf
67         WireTypeEndGroup = 4,
68         /// Fixed size 64 bit (e. g. `fixed32` or `float`)
69         WireTypeFixed32 = 5,
70     }
71 
72     impl Copy for WireType {}
73 
74     impl WireType {
75         /// Parse wire type
new(n: u32) -> Option<WireType>76         pub fn new(n: u32) -> Option<WireType> {
77             match n {
78                 0 => Some(WireTypeVarint),
79                 1 => Some(WireTypeFixed64),
80                 2 => Some(WireTypeLengthDelimited),
81                 3 => Some(WireTypeStartGroup),
82                 4 => Some(WireTypeEndGroup),
83                 5 => Some(WireTypeFixed32),
84                 _ => None,
85             }
86         }
87     }
88 
89     /// Parsed protobuf tag, which is a pair of field number and wire type
90     #[derive(Clone)]
91     pub struct Tag {
92         field_number: u32,
93         wire_type: WireType,
94     }
95 
96     impl Copy for Tag {}
97 
98     impl Tag {
99         /// Pack a tag to integer
value(self) -> u32100         pub fn value(self) -> u32 {
101             (self.field_number << TAG_TYPE_BITS) | (self.wire_type as u32)
102         }
103 
104         /// Parse integer into `Tag` object
105         // TODO: should return Result instead of Option
new(value: u32) -> Option<Tag>106         pub fn new(value: u32) -> Option<Tag> {
107             let wire_type = WireType::new(value & TAG_TYPE_MASK);
108             if wire_type.is_none() {
109                 return None;
110             }
111             let field_number = value >> TAG_TYPE_BITS;
112             if field_number == 0 {
113                 return None;
114             }
115             Some(Tag {
116                 field_number: field_number,
117                 wire_type: wire_type.unwrap(),
118             })
119         }
120 
121         /// Create a tag from a field number and wire type.
122         ///
123         /// # Panics
124         ///
125         /// If field number is outside of allowed range.
make(field_number: u32, wire_type: WireType) -> Tag126         pub fn make(field_number: u32, wire_type: WireType) -> Tag {
127             assert!(field_number > 0 && field_number <= FIELD_NUMBER_MAX);
128             Tag {
129                 field_number: field_number,
130                 wire_type: wire_type,
131             }
132         }
133 
134         /// Tag as pair of (field number, wire type)
unpack(self) -> (u32, WireType)135         pub fn unpack(self) -> (u32, WireType) {
136             (self.field_number(), self.wire_type())
137         }
138 
wire_type(self) -> WireType139         fn wire_type(self) -> WireType {
140             self.wire_type
141         }
142 
143         /// Protobuf field number
field_number(self) -> u32144         pub fn field_number(self) -> u32 {
145             self.field_number
146         }
147     }
148 }
149 
150 /// Buffered read with handy utilities.
151 pub struct CodedInputStream<'a> {
152     source: BufReadIter<'a>,
153     recursion_level: u32,
154     recursion_limit: u32,
155 }
156 
157 impl<'a> CodedInputStream<'a> {
158     /// Wrap a `Read`.
159     ///
160     /// Note resulting `CodedInputStream` is buffered even if `Read` is not.
new(read: &'a mut Read) -> CodedInputStream<'a>161     pub fn new(read: &'a mut Read) -> CodedInputStream<'a> {
162         CodedInputStream::from_buf_read_iter(BufReadIter::from_read(read))
163     }
164 
165     /// Create from `BufRead`.
166     ///
167     /// `CodedInputStream` will utilize `BufRead` buffer.
from_buffered_reader(buf_read: &'a mut BufRead) -> CodedInputStream<'a>168     pub fn from_buffered_reader(buf_read: &'a mut BufRead) -> CodedInputStream<'a> {
169         CodedInputStream::from_buf_read_iter(BufReadIter::from_buf_read(buf_read))
170     }
171 
172     /// Read from byte slice
from_bytes(bytes: &'a [u8]) -> CodedInputStream<'a>173     pub fn from_bytes(bytes: &'a [u8]) -> CodedInputStream<'a> {
174         CodedInputStream::from_buf_read_iter(BufReadIter::from_byte_slice(bytes))
175     }
176 
177     /// Read from `Bytes`.
178     ///
179     /// `CodedInputStream` operations like
180     /// [`read_carllerche_bytes`](crate::CodedInputStream::read_carllerche_bytes)
181     /// will return a shared copy of this bytes object.
182     #[cfg(feature = "bytes")]
from_carllerche_bytes(bytes: &'a Bytes) -> CodedInputStream<'a>183     pub fn from_carllerche_bytes(bytes: &'a Bytes) -> CodedInputStream<'a> {
184         CodedInputStream::from_buf_read_iter(BufReadIter::from_bytes(bytes))
185     }
186 
from_buf_read_iter(source: BufReadIter<'a>) -> CodedInputStream<'a>187     fn from_buf_read_iter(source: BufReadIter<'a>) -> CodedInputStream<'a> {
188         CodedInputStream {
189             source: source,
190             recursion_level: 0,
191             recursion_limit: DEFAULT_RECURSION_LIMIT,
192         }
193     }
194 
195     /// Set the recursion limit.
set_recursion_limit(&mut self, limit: u32)196     pub fn set_recursion_limit(&mut self, limit: u32) {
197         self.recursion_limit = limit;
198     }
199 
200     #[inline]
incr_recursion(&mut self) -> ProtobufResult<()>201     pub(crate) fn incr_recursion(&mut self) -> ProtobufResult<()> {
202         if self.recursion_level >= self.recursion_limit {
203             return Err(ProtobufError::WireError(WireError::OverRecursionLimit));
204         }
205         self.recursion_level += 1;
206         Ok(())
207     }
208 
209     #[inline]
decr_recursion(&mut self)210     pub(crate) fn decr_recursion(&mut self) {
211         self.recursion_level -= 1;
212     }
213 
214     /// How many bytes processed
pos(&self) -> u64215     pub fn pos(&self) -> u64 {
216         self.source.pos()
217     }
218 
219     /// How many bytes until current limit
bytes_until_limit(&self) -> u64220     pub fn bytes_until_limit(&self) -> u64 {
221         self.source.bytes_until_limit()
222     }
223 
224     /// Read bytes into given `buf`.
225     ///
226     /// Return `0` on EOF.
227     // TODO: overload with `Read::read`
read(&mut self, buf: &mut [u8]) -> ProtobufResult<()>228     pub fn read(&mut self, buf: &mut [u8]) -> ProtobufResult<()> {
229         self.source.read_exact(buf)?;
230         Ok(())
231     }
232 
233     /// Read exact number of bytes as `Bytes` object.
234     ///
235     /// This operation returns a shared view if `CodedInputStream` is
236     /// constructed with `Bytes` parameter.
237     #[cfg(feature = "bytes")]
read_raw_callerche_bytes(&mut self, count: usize) -> ProtobufResult<Bytes>238     fn read_raw_callerche_bytes(&mut self, count: usize) -> ProtobufResult<Bytes> {
239         self.source.read_exact_bytes(count)
240     }
241 
242     /// Read one byte
243     #[inline(always)]
read_raw_byte(&mut self) -> ProtobufResult<u8>244     pub fn read_raw_byte(&mut self) -> ProtobufResult<u8> {
245         self.source.read_byte()
246     }
247 
248     /// Push new limit, return previous limit.
push_limit(&mut self, limit: u64) -> ProtobufResult<u64>249     pub fn push_limit(&mut self, limit: u64) -> ProtobufResult<u64> {
250         self.source.push_limit(limit)
251     }
252 
253     /// Restore previous limit.
pop_limit(&mut self, old_limit: u64)254     pub fn pop_limit(&mut self, old_limit: u64) {
255         self.source.pop_limit(old_limit);
256     }
257 
258     /// Are we at EOF?
259     #[inline(always)]
eof(&mut self) -> ProtobufResult<bool>260     pub fn eof(&mut self) -> ProtobufResult<bool> {
261         self.source.eof()
262     }
263 
264     /// Check we are at EOF.
265     ///
266     /// Return error if we are not at EOF.
check_eof(&mut self) -> ProtobufResult<()>267     pub fn check_eof(&mut self) -> ProtobufResult<()> {
268         let eof = self.eof()?;
269         if !eof {
270             return Err(ProtobufError::WireError(WireError::UnexpectedEof));
271         }
272         Ok(())
273     }
274 
read_raw_varint64_slow(&mut self) -> ProtobufResult<u64>275     fn read_raw_varint64_slow(&mut self) -> ProtobufResult<u64> {
276         let mut r: u64 = 0;
277         let mut i = 0;
278         loop {
279             if i == 10 {
280                 return Err(ProtobufError::WireError(WireError::IncorrectVarint));
281             }
282             let b = self.read_raw_byte()?;
283             // TODO: may overflow if i == 9
284             r = r | (((b & 0x7f) as u64) << (i * 7));
285             i += 1;
286             if b < 0x80 {
287                 return Ok(r);
288             }
289         }
290     }
291 
292     /// Read varint
293     #[inline(always)]
read_raw_varint64(&mut self) -> ProtobufResult<u64>294     pub fn read_raw_varint64(&mut self) -> ProtobufResult<u64> {
295         'slow: loop {
296             let ret;
297             let consume;
298 
299             loop {
300                 let rem = self.source.remaining_in_buf();
301 
302                 if rem.len() >= 1 {
303                     // most varints are in practice fit in 1 byte
304                     if rem[0] < 0x80 {
305                         ret = rem[0] as u64;
306                         consume = 1;
307                     } else {
308                         // handle case of two bytes too
309                         if rem.len() >= 2 && rem[1] < 0x80 {
310                             ret = (rem[0] & 0x7f) as u64 | (rem[1] as u64) << 7;
311                             consume = 2;
312                         } else if rem.len() >= 10 {
313                             // Read from array when buf at at least 10 bytes,
314                             // max len for varint.
315                             let mut r: u64 = 0;
316                             let mut i: usize = 0;
317                             {
318                                 let rem = rem;
319                                 loop {
320                                     if i == 10 {
321                                         return Err(ProtobufError::WireError(
322                                             WireError::IncorrectVarint,
323                                         ));
324                                     }
325 
326                                     let b = if true {
327                                         // skip range check
328                                         unsafe { *rem.get_unchecked(i) }
329                                     } else {
330                                         rem[i]
331                                     };
332 
333                                     // TODO: may overflow if i == 9
334                                     r = r | (((b & 0x7f) as u64) << (i * 7));
335                                     i += 1;
336                                     if b < 0x80 {
337                                         break;
338                                     }
339                                 }
340                             }
341                             consume = i;
342                             ret = r;
343                         } else {
344                             break 'slow;
345                         }
346                     }
347                 } else {
348                     break 'slow;
349                 }
350                 break;
351             }
352 
353             self.source.consume(consume);
354             return Ok(ret);
355         }
356 
357         self.read_raw_varint64_slow()
358     }
359 
360     /// Read varint
361     #[inline(always)]
read_raw_varint32(&mut self) -> ProtobufResult<u32>362     pub fn read_raw_varint32(&mut self) -> ProtobufResult<u32> {
363         self.read_raw_varint64().map(|v| v as u32)
364     }
365 
366     /// Read little-endian 32-bit integer
read_raw_little_endian32(&mut self) -> ProtobufResult<u32>367     pub fn read_raw_little_endian32(&mut self) -> ProtobufResult<u32> {
368         let mut r = 0u32;
369         let bytes: &mut [u8] = unsafe {
370             let p: *mut u8 = mem::transmute(&mut r);
371             slice::from_raw_parts_mut(p, mem::size_of::<u32>())
372         };
373         self.read(bytes)?;
374         Ok(r.to_le())
375     }
376 
377     /// Read little-endian 64-bit integer
read_raw_little_endian64(&mut self) -> ProtobufResult<u64>378     pub fn read_raw_little_endian64(&mut self) -> ProtobufResult<u64> {
379         let mut r = 0u64;
380         let bytes: &mut [u8] = unsafe {
381             let p: *mut u8 = mem::transmute(&mut r);
382             slice::from_raw_parts_mut(p, mem::size_of::<u64>())
383         };
384         self.read(bytes)?;
385         Ok(r.to_le())
386     }
387 
388     /// Read tag
389     #[inline]
read_tag(&mut self) -> ProtobufResult<wire_format::Tag>390     pub fn read_tag(&mut self) -> ProtobufResult<wire_format::Tag> {
391         let v = self.read_raw_varint32()?;
392         match wire_format::Tag::new(v) {
393             Some(tag) => Ok(tag),
394             None => Err(ProtobufError::WireError(WireError::IncorrectTag(v))),
395         }
396     }
397 
398     /// Read tag, return it is pair (field number, wire type)
399     #[inline]
read_tag_unpack(&mut self) -> ProtobufResult<(u32, wire_format::WireType)>400     pub fn read_tag_unpack(&mut self) -> ProtobufResult<(u32, wire_format::WireType)> {
401         self.read_tag().map(|t| t.unpack())
402     }
403 
404     /// Read `double`
read_double(&mut self) -> ProtobufResult<f64>405     pub fn read_double(&mut self) -> ProtobufResult<f64> {
406         let bits = self.read_raw_little_endian64()?;
407         unsafe { Ok(mem::transmute::<u64, f64>(bits)) }
408     }
409 
410     /// Read `float`
read_float(&mut self) -> ProtobufResult<f32>411     pub fn read_float(&mut self) -> ProtobufResult<f32> {
412         let bits = self.read_raw_little_endian32()?;
413         unsafe { Ok(mem::transmute::<u32, f32>(bits)) }
414     }
415 
416     /// Read `int64`
read_int64(&mut self) -> ProtobufResult<i64>417     pub fn read_int64(&mut self) -> ProtobufResult<i64> {
418         self.read_raw_varint64().map(|v| v as i64)
419     }
420 
421     /// Read `int32`
read_int32(&mut self) -> ProtobufResult<i32>422     pub fn read_int32(&mut self) -> ProtobufResult<i32> {
423         self.read_raw_varint32().map(|v| v as i32)
424     }
425 
426     /// Read `uint64`
read_uint64(&mut self) -> ProtobufResult<u64>427     pub fn read_uint64(&mut self) -> ProtobufResult<u64> {
428         self.read_raw_varint64()
429     }
430 
431     /// Read `uint32`
read_uint32(&mut self) -> ProtobufResult<u32>432     pub fn read_uint32(&mut self) -> ProtobufResult<u32> {
433         self.read_raw_varint32()
434     }
435 
436     /// Read `sint64`
read_sint64(&mut self) -> ProtobufResult<i64>437     pub fn read_sint64(&mut self) -> ProtobufResult<i64> {
438         self.read_uint64().map(decode_zig_zag_64)
439     }
440 
441     /// Read `sint32`
read_sint32(&mut self) -> ProtobufResult<i32>442     pub fn read_sint32(&mut self) -> ProtobufResult<i32> {
443         self.read_uint32().map(decode_zig_zag_32)
444     }
445 
446     /// Read `fixed64`
read_fixed64(&mut self) -> ProtobufResult<u64>447     pub fn read_fixed64(&mut self) -> ProtobufResult<u64> {
448         self.read_raw_little_endian64()
449     }
450 
451     /// Read `fixed32`
read_fixed32(&mut self) -> ProtobufResult<u32>452     pub fn read_fixed32(&mut self) -> ProtobufResult<u32> {
453         self.read_raw_little_endian32()
454     }
455 
456     /// Read `sfixed64`
read_sfixed64(&mut self) -> ProtobufResult<i64>457     pub fn read_sfixed64(&mut self) -> ProtobufResult<i64> {
458         self.read_raw_little_endian64().map(|v| v as i64)
459     }
460 
461     /// Read `sfixed32`
read_sfixed32(&mut self) -> ProtobufResult<i32>462     pub fn read_sfixed32(&mut self) -> ProtobufResult<i32> {
463         self.read_raw_little_endian32().map(|v| v as i32)
464     }
465 
466     /// Read `bool`
read_bool(&mut self) -> ProtobufResult<bool>467     pub fn read_bool(&mut self) -> ProtobufResult<bool> {
468         self.read_raw_varint32().map(|v| v != 0)
469     }
470 
471     /// Read `enum` as `ProtobufEnum`
read_enum<E: ProtobufEnum>(&mut self) -> ProtobufResult<E>472     pub fn read_enum<E: ProtobufEnum>(&mut self) -> ProtobufResult<E> {
473         let i = self.read_int32()?;
474         match ProtobufEnum::from_i32(i) {
475             Some(e) => Ok(e),
476             None => Err(ProtobufError::WireError(WireError::InvalidEnumValue(i))),
477         }
478     }
479 
480     /// Read `repeated` packed `double`
read_repeated_packed_double_into( &mut self, target: &mut Vec<f64>, ) -> ProtobufResult<()>481     pub fn read_repeated_packed_double_into(
482         &mut self,
483         target: &mut Vec<f64>,
484     ) -> ProtobufResult<()> {
485         let len = self.read_raw_varint64()?;
486 
487         target.reserve((len / 4) as usize);
488 
489         let old_limit = self.push_limit(len)?;
490         while !self.eof()? {
491             target.push(self.read_double()?);
492         }
493         self.pop_limit(old_limit);
494         Ok(())
495     }
496 
497     /// Read `repeated` packed `float`
read_repeated_packed_float_into(&mut self, target: &mut Vec<f32>) -> ProtobufResult<()>498     pub fn read_repeated_packed_float_into(&mut self, target: &mut Vec<f32>) -> ProtobufResult<()> {
499         let len = self.read_raw_varint64()?;
500 
501         target.reserve((len / 4) as usize);
502 
503         let old_limit = self.push_limit(len)?;
504         while !self.eof()? {
505             target.push(self.read_float()?);
506         }
507         self.pop_limit(old_limit);
508         Ok(())
509     }
510 
511     /// Read `repeated` packed `int64`
read_repeated_packed_int64_into(&mut self, target: &mut Vec<i64>) -> ProtobufResult<()>512     pub fn read_repeated_packed_int64_into(&mut self, target: &mut Vec<i64>) -> ProtobufResult<()> {
513         let len = self.read_raw_varint64()?;
514         let old_limit = self.push_limit(len as u64)?;
515         while !self.eof()? {
516             target.push(self.read_int64()?);
517         }
518         self.pop_limit(old_limit);
519         Ok(())
520     }
521 
522     /// Read repeated packed `int32`
read_repeated_packed_int32_into(&mut self, target: &mut Vec<i32>) -> ProtobufResult<()>523     pub fn read_repeated_packed_int32_into(&mut self, target: &mut Vec<i32>) -> ProtobufResult<()> {
524         let len = self.read_raw_varint64()?;
525         let old_limit = self.push_limit(len)?;
526         while !self.eof()? {
527             target.push(self.read_int32()?);
528         }
529         self.pop_limit(old_limit);
530         Ok(())
531     }
532 
533     /// Read repeated packed `uint64`
read_repeated_packed_uint64_into( &mut self, target: &mut Vec<u64>, ) -> ProtobufResult<()>534     pub fn read_repeated_packed_uint64_into(
535         &mut self,
536         target: &mut Vec<u64>,
537     ) -> ProtobufResult<()> {
538         let len = self.read_raw_varint64()?;
539         let old_limit = self.push_limit(len)?;
540         while !self.eof()? {
541             target.push(self.read_uint64()?);
542         }
543         self.pop_limit(old_limit);
544         Ok(())
545     }
546 
547     /// Read repeated packed `uint32`
read_repeated_packed_uint32_into( &mut self, target: &mut Vec<u32>, ) -> ProtobufResult<()>548     pub fn read_repeated_packed_uint32_into(
549         &mut self,
550         target: &mut Vec<u32>,
551     ) -> ProtobufResult<()> {
552         let len = self.read_raw_varint64()?;
553         let old_limit = self.push_limit(len)?;
554         while !self.eof()? {
555             target.push(self.read_uint32()?);
556         }
557         self.pop_limit(old_limit);
558         Ok(())
559     }
560 
561     /// Read repeated packed `sint64`
read_repeated_packed_sint64_into( &mut self, target: &mut Vec<i64>, ) -> ProtobufResult<()>562     pub fn read_repeated_packed_sint64_into(
563         &mut self,
564         target: &mut Vec<i64>,
565     ) -> ProtobufResult<()> {
566         let len = self.read_raw_varint64()?;
567         let old_limit = self.push_limit(len)?;
568         while !self.eof()? {
569             target.push(self.read_sint64()?);
570         }
571         self.pop_limit(old_limit);
572         Ok(())
573     }
574 
575     /// Read repeated packed `sint32`
read_repeated_packed_sint32_into( &mut self, target: &mut Vec<i32>, ) -> ProtobufResult<()>576     pub fn read_repeated_packed_sint32_into(
577         &mut self,
578         target: &mut Vec<i32>,
579     ) -> ProtobufResult<()> {
580         let len = self.read_raw_varint64()?;
581         let old_limit = self.push_limit(len)?;
582         while !self.eof()? {
583             target.push(self.read_sint32()?);
584         }
585         self.pop_limit(old_limit);
586         Ok(())
587     }
588 
589     /// Read repeated packed `fixed64`
read_repeated_packed_fixed64_into( &mut self, target: &mut Vec<u64>, ) -> ProtobufResult<()>590     pub fn read_repeated_packed_fixed64_into(
591         &mut self,
592         target: &mut Vec<u64>,
593     ) -> ProtobufResult<()> {
594         let len = self.read_raw_varint64()?;
595 
596         target.reserve((len / 8) as usize);
597 
598         let old_limit = self.push_limit(len)?;
599         while !self.eof()? {
600             target.push(self.read_fixed64()?);
601         }
602         self.pop_limit(old_limit);
603         Ok(())
604     }
605 
606     /// Read repeated packed `fixed32`
read_repeated_packed_fixed32_into( &mut self, target: &mut Vec<u32>, ) -> ProtobufResult<()>607     pub fn read_repeated_packed_fixed32_into(
608         &mut self,
609         target: &mut Vec<u32>,
610     ) -> ProtobufResult<()> {
611         let len = self.read_raw_varint64()?;
612 
613         target.reserve((len / 4) as usize);
614 
615         let old_limit = self.push_limit(len)?;
616         while !self.eof()? {
617             target.push(self.read_fixed32()?);
618         }
619         self.pop_limit(old_limit);
620         Ok(())
621     }
622 
623     /// Read repeated packed `sfixed64`
read_repeated_packed_sfixed64_into( &mut self, target: &mut Vec<i64>, ) -> ProtobufResult<()>624     pub fn read_repeated_packed_sfixed64_into(
625         &mut self,
626         target: &mut Vec<i64>,
627     ) -> ProtobufResult<()> {
628         let len = self.read_raw_varint64()?;
629 
630         target.reserve((len / 8) as usize);
631 
632         let old_limit = self.push_limit(len)?;
633         while !self.eof()? {
634             target.push(self.read_sfixed64()?);
635         }
636         self.pop_limit(old_limit);
637         Ok(())
638     }
639 
640     /// Read repeated packed `sfixed32`
read_repeated_packed_sfixed32_into( &mut self, target: &mut Vec<i32>, ) -> ProtobufResult<()>641     pub fn read_repeated_packed_sfixed32_into(
642         &mut self,
643         target: &mut Vec<i32>,
644     ) -> ProtobufResult<()> {
645         let len = self.read_raw_varint64()?;
646 
647         target.reserve((len / 4) as usize);
648 
649         let old_limit = self.push_limit(len)?;
650         while !self.eof()? {
651             target.push(self.read_sfixed32()?);
652         }
653         self.pop_limit(old_limit);
654         Ok(())
655     }
656 
657     /// Read repeated packed `bool`
read_repeated_packed_bool_into(&mut self, target: &mut Vec<bool>) -> ProtobufResult<()>658     pub fn read_repeated_packed_bool_into(&mut self, target: &mut Vec<bool>) -> ProtobufResult<()> {
659         let len = self.read_raw_varint64()?;
660 
661         // regular bool value is 1-byte size
662         target.reserve(len as usize);
663 
664         let old_limit = self.push_limit(len)?;
665         while !self.eof()? {
666             target.push(self.read_bool()?);
667         }
668         self.pop_limit(old_limit);
669         Ok(())
670     }
671 
672     /// Read repeated packed `enum` into `ProtobufEnum`
read_repeated_packed_enum_into<E: ProtobufEnum>( &mut self, target: &mut Vec<E>, ) -> ProtobufResult<()>673     pub fn read_repeated_packed_enum_into<E: ProtobufEnum>(
674         &mut self,
675         target: &mut Vec<E>,
676     ) -> ProtobufResult<()> {
677         let len = self.read_raw_varint64()?;
678         let old_limit = self.push_limit(len)?;
679         while !self.eof()? {
680             target.push(self.read_enum()?);
681         }
682         self.pop_limit(old_limit);
683         Ok(())
684     }
685 
686     /// Read `UnknownValue`
read_unknown( &mut self, wire_type: wire_format::WireType, ) -> ProtobufResult<UnknownValue>687     pub fn read_unknown(
688         &mut self,
689         wire_type: wire_format::WireType,
690     ) -> ProtobufResult<UnknownValue> {
691         match wire_type {
692             wire_format::WireTypeVarint => {
693                 self.read_raw_varint64().map(|v| UnknownValue::Varint(v))
694             }
695             wire_format::WireTypeFixed64 => self.read_fixed64().map(|v| UnknownValue::Fixed64(v)),
696             wire_format::WireTypeFixed32 => self.read_fixed32().map(|v| UnknownValue::Fixed32(v)),
697             wire_format::WireTypeLengthDelimited => {
698                 let len = self.read_raw_varint32()?;
699                 self.read_raw_bytes(len)
700                     .map(|v| UnknownValue::LengthDelimited(v))
701             }
702             _ => Err(ProtobufError::WireError(WireError::UnexpectedWireType(
703                 wire_type,
704             ))),
705         }
706     }
707 
708     /// Skip field
skip_field(&mut self, wire_type: wire_format::WireType) -> ProtobufResult<()>709     pub fn skip_field(&mut self, wire_type: wire_format::WireType) -> ProtobufResult<()> {
710         self.read_unknown(wire_type).map(|_| ())
711     }
712 
713     /// Read raw bytes into the supplied vector.  The vector will be resized as needed and
714     /// overwritten.
read_raw_bytes_into(&mut self, count: u32, target: &mut Vec<u8>) -> ProtobufResult<()>715     pub fn read_raw_bytes_into(&mut self, count: u32, target: &mut Vec<u8>) -> ProtobufResult<()> {
716         if false {
717             // Master uses this version, but keep existing version for a while
718             // to avoid possible breakages.
719             return self.source.read_exact_to_vec(count as usize, target);
720         }
721 
722         let count = count as usize;
723 
724         // TODO: also do some limits when reading from unlimited source
725         if count as u64 > self.source.bytes_until_limit() {
726             return Err(ProtobufError::WireError(WireError::TruncatedMessage));
727         }
728 
729         unsafe {
730             target.set_len(0);
731         }
732 
733         if count >= READ_RAW_BYTES_MAX_ALLOC {
734             // avoid calling `reserve` on buf with very large buffer: could be a malformed message
735 
736             let mut take = self.by_ref().take(count as u64);
737             take.read_to_end(target)?;
738 
739             if target.len() != count {
740                 return Err(ProtobufError::WireError(WireError::TruncatedMessage));
741             }
742         } else {
743             target.reserve(count);
744             unsafe {
745                 target.set_len(count);
746             }
747 
748             self.source.read_exact(target)?;
749         }
750         Ok(())
751     }
752 
753     /// Read exact number of bytes
read_raw_bytes(&mut self, count: u32) -> ProtobufResult<Vec<u8>>754     pub fn read_raw_bytes(&mut self, count: u32) -> ProtobufResult<Vec<u8>> {
755         let mut r = Vec::new();
756         self.read_raw_bytes_into(count, &mut r)?;
757         Ok(r)
758     }
759 
760     /// Skip exact number of bytes
skip_raw_bytes(&mut self, count: u32) -> ProtobufResult<()>761     pub fn skip_raw_bytes(&mut self, count: u32) -> ProtobufResult<()> {
762         // TODO: make it more efficient
763         self.read_raw_bytes(count).map(|_| ())
764     }
765 
766     /// Read `bytes` field, length delimited
read_bytes(&mut self) -> ProtobufResult<Vec<u8>>767     pub fn read_bytes(&mut self) -> ProtobufResult<Vec<u8>> {
768         let mut r = Vec::new();
769         self.read_bytes_into(&mut r)?;
770         Ok(r)
771     }
772 
773     /// Read `bytes` field, length delimited
774     #[cfg(feature = "bytes")]
read_carllerche_bytes(&mut self) -> ProtobufResult<Bytes>775     pub fn read_carllerche_bytes(&mut self) -> ProtobufResult<Bytes> {
776         let len = self.read_raw_varint32()?;
777         self.read_raw_callerche_bytes(len as usize)
778     }
779 
780     /// Read `string` field, length delimited
781     #[cfg(feature = "bytes")]
read_carllerche_chars(&mut self) -> ProtobufResult<Chars>782     pub fn read_carllerche_chars(&mut self) -> ProtobufResult<Chars> {
783         let bytes = self.read_carllerche_bytes()?;
784         Ok(Chars::from_bytes(bytes)?)
785     }
786 
787     /// Read `bytes` field, length delimited
read_bytes_into(&mut self, target: &mut Vec<u8>) -> ProtobufResult<()>788     pub fn read_bytes_into(&mut self, target: &mut Vec<u8>) -> ProtobufResult<()> {
789         let len = self.read_raw_varint32()?;
790         self.read_raw_bytes_into(len, target)?;
791         Ok(())
792     }
793 
794     /// Read `string` field, length delimited
read_string(&mut self) -> ProtobufResult<String>795     pub fn read_string(&mut self) -> ProtobufResult<String> {
796         let mut r = String::new();
797         self.read_string_into(&mut r)?;
798         Ok(r)
799     }
800 
801     /// Read `string` field, length delimited
read_string_into(&mut self, target: &mut String) -> ProtobufResult<()>802     pub fn read_string_into(&mut self, target: &mut String) -> ProtobufResult<()> {
803         target.clear();
804         // take target's buffer
805         let mut vec = mem::replace(target, String::new()).into_bytes();
806         self.read_bytes_into(&mut vec)?;
807 
808         let s = match String::from_utf8(vec) {
809             Ok(t) => t,
810             Err(_) => return Err(ProtobufError::WireError(WireError::Utf8Error)),
811         };
812         mem::replace(target, s);
813         Ok(())
814     }
815 
816     /// Read message, do not check if message is initialized
merge_message<M: Message>(&mut self, message: &mut M) -> ProtobufResult<()>817     pub fn merge_message<M: Message>(&mut self, message: &mut M) -> ProtobufResult<()> {
818         let len = self.read_raw_varint64()?;
819         let old_limit = self.push_limit(len)?;
820         message.merge_from(self)?;
821         self.pop_limit(old_limit);
822         Ok(())
823     }
824 
825     /// Read message
read_message<M: Message>(&mut self) -> ProtobufResult<M>826     pub fn read_message<M: Message>(&mut self) -> ProtobufResult<M> {
827         let mut r: M = Message::new();
828         self.merge_message(&mut r)?;
829         r.check_initialized()?;
830         Ok(r)
831     }
832 }
833 
834 impl<'a> Read for CodedInputStream<'a> {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>835     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
836         self.source.read(buf).map_err(Into::into)
837     }
838 }
839 
840 impl<'a> BufRead for CodedInputStream<'a> {
fill_buf(&mut self) -> io::Result<&[u8]>841     fn fill_buf(&mut self) -> io::Result<&[u8]> {
842         self.source.fill_buf().map_err(Into::into)
843     }
844 
consume(&mut self, amt: usize)845     fn consume(&mut self, amt: usize) {
846         self.source.consume(amt)
847     }
848 }
849 
850 #[doc(hidden)]
851 pub trait WithCodedOutputStream {
with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>852     fn with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T>
853     where
854         F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>;
855 }
856 
857 impl<'a> WithCodedOutputStream for &'a mut (Write + 'a) {
with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>,858     fn with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T>
859     where
860         F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>,
861     {
862         let mut os = CodedOutputStream::new(self);
863         let r = cb(&mut os)?;
864         os.flush()?;
865         Ok(r)
866     }
867 }
868 
869 impl<'a> WithCodedOutputStream for &'a mut Vec<u8> {
with_coded_output_stream<T, F>(mut self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>,870     fn with_coded_output_stream<T, F>(mut self, cb: F) -> ProtobufResult<T>
871     where
872         F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>,
873     {
874         let mut os = CodedOutputStream::vec(&mut self);
875         let r = cb(&mut os)?;
876         os.flush()?;
877         Ok(r)
878     }
879 }
880 
881 #[doc(hidden)]
with_coded_output_stream_to_bytes<F>(cb: F) -> ProtobufResult<Vec<u8>> where F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<()>,882 pub fn with_coded_output_stream_to_bytes<F>(cb: F) -> ProtobufResult<Vec<u8>>
883 where
884     F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<()>,
885 {
886     let mut v = Vec::new();
887     v.with_coded_output_stream(cb)?;
888     Ok(v)
889 }
890 
891 /// Helper internal utility, should not be used directly
892 #[doc(hidden)]
893 pub trait WithCodedInputStream {
with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>894     fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T>
895     where
896         F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>;
897 }
898 
899 impl<'a> WithCodedInputStream for &'a mut (Read + 'a) {
with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,900     fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T>
901     where
902         F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,
903     {
904         let mut is = CodedInputStream::new(self);
905         let r = cb(&mut is)?;
906         is.check_eof()?;
907         Ok(r)
908     }
909 }
910 
911 impl<'a> WithCodedInputStream for &'a mut (BufRead + 'a) {
with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,912     fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T>
913     where
914         F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,
915     {
916         let mut is = CodedInputStream::from_buffered_reader(self);
917         let r = cb(&mut is)?;
918         is.check_eof()?;
919         Ok(r)
920     }
921 }
922 
923 impl<'a> WithCodedInputStream for &'a [u8] {
with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,924     fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T>
925     where
926         F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,
927     {
928         let mut is = CodedInputStream::from_bytes(self);
929         let r = cb(&mut is)?;
930         is.check_eof()?;
931         Ok(r)
932     }
933 }
934 
935 #[cfg(feature = "bytes")]
936 impl<'a> WithCodedInputStream for &'a Bytes {
with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> where F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,937     fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T>
938     where
939         F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>,
940     {
941         let mut is = CodedInputStream::from_carllerche_bytes(self);
942         let r = cb(&mut is)?;
943         is.check_eof()?;
944         Ok(r)
945     }
946 }
947 
948 enum OutputTarget<'a> {
949     Write(&'a mut Write, Vec<u8>),
950     Vec(&'a mut Vec<u8>),
951     Bytes,
952 }
953 
954 /// Buffered write with handy utilities
955 pub struct CodedOutputStream<'a> {
956     target: OutputTarget<'a>,
957     // alias to buf from target
958     buffer: &'a mut [u8],
959     // within buffer
960     position: usize,
961 }
962 
963 impl<'a> CodedOutputStream<'a> {
964     /// Construct from given `Write`.
965     ///
966     /// `CodedOutputStream` is buffered even if `Write` is not
new(writer: &'a mut Write) -> CodedOutputStream<'a>967     pub fn new(writer: &'a mut Write) -> CodedOutputStream<'a> {
968         let buffer_len = OUTPUT_STREAM_BUFFER_SIZE;
969 
970         let mut buffer_storage = Vec::with_capacity(buffer_len);
971         unsafe {
972             buffer_storage.set_len(buffer_len);
973         }
974 
975         let buffer = unsafe { remove_lifetime_mut(&mut buffer_storage as &mut [u8]) };
976 
977         CodedOutputStream {
978             target: OutputTarget::Write(writer, buffer_storage),
979             buffer: buffer,
980             position: 0,
981         }
982     }
983 
984     /// `CodedOutputStream` which writes directly to bytes.
985     ///
986     /// Attempt to write more than bytes capacity results in error.
bytes(bytes: &'a mut [u8]) -> CodedOutputStream<'a>987     pub fn bytes(bytes: &'a mut [u8]) -> CodedOutputStream<'a> {
988         CodedOutputStream {
989             target: OutputTarget::Bytes,
990             buffer: bytes,
991             position: 0,
992         }
993     }
994 
995     /// `CodedOutputStream` which writes directly to `Vec<u8>`.
996     ///
997     /// Caller should call `flush` at the end to guarantee vec contains
998     /// all written data.
vec(vec: &'a mut Vec<u8>) -> CodedOutputStream<'a>999     pub fn vec(vec: &'a mut Vec<u8>) -> CodedOutputStream<'a> {
1000         CodedOutputStream {
1001             target: OutputTarget::Vec(vec),
1002             buffer: &mut [],
1003             position: 0,
1004         }
1005     }
1006 
1007     /// Check if EOF is reached.
1008     ///
1009     /// # Panics
1010     ///
1011     /// If underlying write has no EOF
check_eof(&self)1012     pub fn check_eof(&self) {
1013         match self.target {
1014             OutputTarget::Bytes => {
1015                 assert_eq!(self.buffer.len() as u64, self.position as u64);
1016             }
1017             OutputTarget::Write(..) | OutputTarget::Vec(..) => {
1018                 panic!("must not be called with Writer or Vec");
1019             }
1020         }
1021     }
1022 
refresh_buffer(&mut self) -> ProtobufResult<()>1023     fn refresh_buffer(&mut self) -> ProtobufResult<()> {
1024         match self.target {
1025             OutputTarget::Write(ref mut write, _) => {
1026                 write.write_all(&self.buffer[0..self.position as usize])?;
1027                 self.position = 0;
1028             }
1029             OutputTarget::Vec(ref mut vec) => unsafe {
1030                 let vec_len = vec.len();
1031                 assert!(vec_len + self.position <= vec.capacity());
1032                 vec.set_len(vec_len + self.position);
1033                 vec.reserve(1);
1034                 self.buffer = remove_lifetime_mut(remaining_capacity_as_slice_mut(vec));
1035                 self.position = 0;
1036             },
1037             OutputTarget::Bytes => {
1038                 panic!("refresh_buffer must not be called on CodedOutputStream create from slice");
1039             }
1040         }
1041         Ok(())
1042     }
1043 
1044     /// Flush the buffer to underlying write
flush(&mut self) -> ProtobufResult<()>1045     pub fn flush(&mut self) -> ProtobufResult<()> {
1046         match self.target {
1047             OutputTarget::Bytes => Ok(()),
1048             OutputTarget::Write(..) | OutputTarget::Vec(..) => {
1049                 // TODO: must not reserve additional in Vec
1050                 self.refresh_buffer()
1051             }
1052         }
1053     }
1054 
1055     /// Write a byte
write_raw_byte(&mut self, byte: u8) -> ProtobufResult<()>1056     pub fn write_raw_byte(&mut self, byte: u8) -> ProtobufResult<()> {
1057         if self.position as usize == self.buffer.len() {
1058             self.refresh_buffer()?;
1059         }
1060         self.buffer[self.position as usize] = byte;
1061         self.position += 1;
1062         Ok(())
1063     }
1064 
1065     /// Write bytes
write_raw_bytes(&mut self, bytes: &[u8]) -> ProtobufResult<()>1066     pub fn write_raw_bytes(&mut self, bytes: &[u8]) -> ProtobufResult<()> {
1067         if bytes.len() <= self.buffer.len() - self.position {
1068             let bottom = self.position as usize;
1069             let top = bottom + (bytes.len() as usize);
1070             self.buffer[bottom..top].copy_from_slice(bytes);
1071             self.position += bytes.len();
1072             return Ok(());
1073         }
1074 
1075         self.refresh_buffer()?;
1076 
1077         assert!(self.position == 0);
1078 
1079         if self.position + bytes.len() < self.buffer.len() {
1080             &mut self.buffer[self.position..self.position + bytes.len()].copy_from_slice(bytes);
1081             self.position += bytes.len();
1082             return Ok(());
1083         }
1084 
1085         match self.target {
1086             OutputTarget::Bytes => {
1087                 unreachable!();
1088             }
1089             OutputTarget::Write(ref mut write, _) => {
1090                 write.write_all(bytes)?;
1091             }
1092             OutputTarget::Vec(ref mut vec) => {
1093                 vec.extend(bytes);
1094                 unsafe {
1095                     self.buffer = remove_lifetime_mut(remaining_capacity_as_slice_mut(vec));
1096                 }
1097             }
1098         }
1099         Ok(())
1100     }
1101 
1102     /// Write a tag
write_tag( &mut self, field_number: u32, wire_type: wire_format::WireType, ) -> ProtobufResult<()>1103     pub fn write_tag(
1104         &mut self,
1105         field_number: u32,
1106         wire_type: wire_format::WireType,
1107     ) -> ProtobufResult<()> {
1108         self.write_raw_varint32(wire_format::Tag::make(field_number, wire_type).value())
1109     }
1110 
1111     /// Write varint
write_raw_varint32(&mut self, value: u32) -> ProtobufResult<()>1112     pub fn write_raw_varint32(&mut self, value: u32) -> ProtobufResult<()> {
1113         if self.buffer.len() - self.position >= 5 {
1114             // fast path
1115             let len = varint::encode_varint32(value, &mut self.buffer[self.position..]);
1116             self.position += len;
1117             Ok(())
1118         } else {
1119             // slow path
1120             let buf = &mut [0u8; 5];
1121             let len = varint::encode_varint32(value, buf);
1122             self.write_raw_bytes(&buf[..len])
1123         }
1124     }
1125 
1126     /// Write varint
write_raw_varint64(&mut self, value: u64) -> ProtobufResult<()>1127     pub fn write_raw_varint64(&mut self, value: u64) -> ProtobufResult<()> {
1128         if self.buffer.len() - self.position >= 10 {
1129             // fast path
1130             let len = varint::encode_varint64(value, &mut self.buffer[self.position..]);
1131             self.position += len;
1132             Ok(())
1133         } else {
1134             // slow path
1135             let buf = &mut [0u8; 10];
1136             let len = varint::encode_varint64(value, buf);
1137             self.write_raw_bytes(&buf[..len])
1138         }
1139     }
1140 
1141     /// Write 32-bit integer little endian
write_raw_little_endian32(&mut self, value: u32) -> ProtobufResult<()>1142     pub fn write_raw_little_endian32(&mut self, value: u32) -> ProtobufResult<()> {
1143         let bytes = unsafe { mem::transmute::<_, [u8; 4]>(value.to_le()) };
1144         self.write_raw_bytes(&bytes)
1145     }
1146 
1147     /// Write 64-bit integer little endian
write_raw_little_endian64(&mut self, value: u64) -> ProtobufResult<()>1148     pub fn write_raw_little_endian64(&mut self, value: u64) -> ProtobufResult<()> {
1149         let bytes = unsafe { mem::transmute::<_, [u8; 8]>(value.to_le()) };
1150         self.write_raw_bytes(&bytes)
1151     }
1152 
1153     /// Write `float`
write_float_no_tag(&mut self, value: f32) -> ProtobufResult<()>1154     pub fn write_float_no_tag(&mut self, value: f32) -> ProtobufResult<()> {
1155         let bits = unsafe { mem::transmute::<f32, u32>(value) };
1156         self.write_raw_little_endian32(bits)
1157     }
1158 
1159     /// Write `double`
write_double_no_tag(&mut self, value: f64) -> ProtobufResult<()>1160     pub fn write_double_no_tag(&mut self, value: f64) -> ProtobufResult<()> {
1161         let bits = unsafe { mem::transmute::<f64, u64>(value) };
1162         self.write_raw_little_endian64(bits)
1163     }
1164 
1165     /// Write `float` field
write_float(&mut self, field_number: u32, value: f32) -> ProtobufResult<()>1166     pub fn write_float(&mut self, field_number: u32, value: f32) -> ProtobufResult<()> {
1167         self.write_tag(field_number, wire_format::WireTypeFixed32)?;
1168         self.write_float_no_tag(value)?;
1169         Ok(())
1170     }
1171 
1172     /// Write `double` field
write_double(&mut self, field_number: u32, value: f64) -> ProtobufResult<()>1173     pub fn write_double(&mut self, field_number: u32, value: f64) -> ProtobufResult<()> {
1174         self.write_tag(field_number, wire_format::WireTypeFixed64)?;
1175         self.write_double_no_tag(value)?;
1176         Ok(())
1177     }
1178 
1179     /// Write varint
write_uint64_no_tag(&mut self, value: u64) -> ProtobufResult<()>1180     pub fn write_uint64_no_tag(&mut self, value: u64) -> ProtobufResult<()> {
1181         self.write_raw_varint64(value)
1182     }
1183 
1184     /// Write varint
write_uint32_no_tag(&mut self, value: u32) -> ProtobufResult<()>1185     pub fn write_uint32_no_tag(&mut self, value: u32) -> ProtobufResult<()> {
1186         self.write_raw_varint32(value)
1187     }
1188 
1189     /// Write varint
write_int64_no_tag(&mut self, value: i64) -> ProtobufResult<()>1190     pub fn write_int64_no_tag(&mut self, value: i64) -> ProtobufResult<()> {
1191         self.write_raw_varint64(value as u64)
1192     }
1193 
1194     /// Write varint
write_int32_no_tag(&mut self, value: i32) -> ProtobufResult<()>1195     pub fn write_int32_no_tag(&mut self, value: i32) -> ProtobufResult<()> {
1196         self.write_raw_varint64(value as u64)
1197     }
1198 
1199     /// Write zigzag varint
write_sint64_no_tag(&mut self, value: i64) -> ProtobufResult<()>1200     pub fn write_sint64_no_tag(&mut self, value: i64) -> ProtobufResult<()> {
1201         self.write_uint64_no_tag(encode_zig_zag_64(value))
1202     }
1203 
1204     /// Write zigzag varint
write_sint32_no_tag(&mut self, value: i32) -> ProtobufResult<()>1205     pub fn write_sint32_no_tag(&mut self, value: i32) -> ProtobufResult<()> {
1206         self.write_uint32_no_tag(encode_zig_zag_32(value))
1207     }
1208 
1209     /// Write `fixed64`
write_fixed64_no_tag(&mut self, value: u64) -> ProtobufResult<()>1210     pub fn write_fixed64_no_tag(&mut self, value: u64) -> ProtobufResult<()> {
1211         self.write_raw_little_endian64(value)
1212     }
1213 
1214     /// Write `fixed32`
write_fixed32_no_tag(&mut self, value: u32) -> ProtobufResult<()>1215     pub fn write_fixed32_no_tag(&mut self, value: u32) -> ProtobufResult<()> {
1216         self.write_raw_little_endian32(value)
1217     }
1218 
1219     /// Write `sfixed64`
write_sfixed64_no_tag(&mut self, value: i64) -> ProtobufResult<()>1220     pub fn write_sfixed64_no_tag(&mut self, value: i64) -> ProtobufResult<()> {
1221         self.write_raw_little_endian64(value as u64)
1222     }
1223 
1224     /// Write `sfixed32`
write_sfixed32_no_tag(&mut self, value: i32) -> ProtobufResult<()>1225     pub fn write_sfixed32_no_tag(&mut self, value: i32) -> ProtobufResult<()> {
1226         self.write_raw_little_endian32(value as u32)
1227     }
1228 
1229     /// Write `bool`
write_bool_no_tag(&mut self, value: bool) -> ProtobufResult<()>1230     pub fn write_bool_no_tag(&mut self, value: bool) -> ProtobufResult<()> {
1231         self.write_raw_varint32(if value { 1 } else { 0 })
1232     }
1233 
1234     /// Write `enum`
write_enum_no_tag(&mut self, value: i32) -> ProtobufResult<()>1235     pub fn write_enum_no_tag(&mut self, value: i32) -> ProtobufResult<()> {
1236         self.write_int32_no_tag(value)
1237     }
1238 
1239     /// Write `enum`
write_enum_obj_no_tag<E>(&mut self, value: E) -> ProtobufResult<()> where E: ProtobufEnum,1240     pub fn write_enum_obj_no_tag<E>(&mut self, value: E) -> ProtobufResult<()>
1241     where
1242         E: ProtobufEnum,
1243     {
1244         self.write_enum_no_tag(value.value())
1245     }
1246 
1247     /// Write unknown value
write_unknown_no_tag(&mut self, unknown: UnknownValueRef) -> ProtobufResult<()>1248     pub fn write_unknown_no_tag(&mut self, unknown: UnknownValueRef) -> ProtobufResult<()> {
1249         match unknown {
1250             UnknownValueRef::Fixed64(fixed64) => self.write_raw_little_endian64(fixed64),
1251             UnknownValueRef::Fixed32(fixed32) => self.write_raw_little_endian32(fixed32),
1252             UnknownValueRef::Varint(varint) => self.write_raw_varint64(varint),
1253             UnknownValueRef::LengthDelimited(bytes) => self.write_bytes_no_tag(bytes),
1254         }
1255     }
1256 
1257     /// Write `uint64` field
write_uint64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()>1258     pub fn write_uint64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()> {
1259         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1260         self.write_uint64_no_tag(value)?;
1261         Ok(())
1262     }
1263 
1264     /// Write `uint32` field
write_uint32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()>1265     pub fn write_uint32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()> {
1266         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1267         self.write_uint32_no_tag(value)?;
1268         Ok(())
1269     }
1270 
1271     /// Write `int64` field
write_int64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()>1272     pub fn write_int64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> {
1273         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1274         self.write_int64_no_tag(value)?;
1275         Ok(())
1276     }
1277 
1278     /// Write `int32` field
write_int32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()>1279     pub fn write_int32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> {
1280         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1281         self.write_int32_no_tag(value)?;
1282         Ok(())
1283     }
1284 
1285     /// Write `sint64` field
write_sint64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()>1286     pub fn write_sint64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> {
1287         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1288         self.write_sint64_no_tag(value)?;
1289         Ok(())
1290     }
1291 
1292     /// Write `sint32` field
write_sint32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()>1293     pub fn write_sint32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> {
1294         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1295         self.write_sint32_no_tag(value)?;
1296         Ok(())
1297     }
1298 
1299     /// Write `fixed64` field
write_fixed64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()>1300     pub fn write_fixed64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()> {
1301         self.write_tag(field_number, wire_format::WireTypeFixed64)?;
1302         self.write_fixed64_no_tag(value)?;
1303         Ok(())
1304     }
1305 
1306     /// Write `fixed32` field
write_fixed32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()>1307     pub fn write_fixed32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()> {
1308         self.write_tag(field_number, wire_format::WireTypeFixed32)?;
1309         self.write_fixed32_no_tag(value)?;
1310         Ok(())
1311     }
1312 
1313     /// Write `sfixed64` field
write_sfixed64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()>1314     pub fn write_sfixed64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> {
1315         self.write_tag(field_number, wire_format::WireTypeFixed64)?;
1316         self.write_sfixed64_no_tag(value)?;
1317         Ok(())
1318     }
1319 
1320     /// Write `sfixed32` field
write_sfixed32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()>1321     pub fn write_sfixed32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> {
1322         self.write_tag(field_number, wire_format::WireTypeFixed32)?;
1323         self.write_sfixed32_no_tag(value)?;
1324         Ok(())
1325     }
1326 
1327     /// Write `bool` field
write_bool(&mut self, field_number: u32, value: bool) -> ProtobufResult<()>1328     pub fn write_bool(&mut self, field_number: u32, value: bool) -> ProtobufResult<()> {
1329         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1330         self.write_bool_no_tag(value)?;
1331         Ok(())
1332     }
1333 
1334     /// Write `enum` field
write_enum(&mut self, field_number: u32, value: i32) -> ProtobufResult<()>1335     pub fn write_enum(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> {
1336         self.write_tag(field_number, wire_format::WireTypeVarint)?;
1337         self.write_enum_no_tag(value)?;
1338         Ok(())
1339     }
1340 
1341     /// Write `enum` field
write_enum_obj<E>(&mut self, field_number: u32, value: E) -> ProtobufResult<()> where E: ProtobufEnum,1342     pub fn write_enum_obj<E>(&mut self, field_number: u32, value: E) -> ProtobufResult<()>
1343     where
1344         E: ProtobufEnum,
1345     {
1346         self.write_enum(field_number, value.value())
1347     }
1348 
1349     /// Write unknown field
write_unknown( &mut self, field_number: u32, value: UnknownValueRef, ) -> ProtobufResult<()>1350     pub fn write_unknown(
1351         &mut self,
1352         field_number: u32,
1353         value: UnknownValueRef,
1354     ) -> ProtobufResult<()> {
1355         self.write_tag(field_number, value.wire_type())?;
1356         self.write_unknown_no_tag(value)?;
1357         Ok(())
1358     }
1359 
1360     /// Write unknown fields
write_unknown_fields(&mut self, fields: &UnknownFields) -> ProtobufResult<()>1361     pub fn write_unknown_fields(&mut self, fields: &UnknownFields) -> ProtobufResult<()> {
1362         for (number, values) in fields {
1363             for value in values {
1364                 self.write_unknown(number, value)?;
1365             }
1366         }
1367         Ok(())
1368     }
1369 
1370     /// Write bytes
write_bytes_no_tag(&mut self, bytes: &[u8]) -> ProtobufResult<()>1371     pub fn write_bytes_no_tag(&mut self, bytes: &[u8]) -> ProtobufResult<()> {
1372         self.write_raw_varint32(bytes.len() as u32)?;
1373         self.write_raw_bytes(bytes)?;
1374         Ok(())
1375     }
1376 
1377     /// Write string
write_string_no_tag(&mut self, s: &str) -> ProtobufResult<()>1378     pub fn write_string_no_tag(&mut self, s: &str) -> ProtobufResult<()> {
1379         self.write_bytes_no_tag(s.as_bytes())
1380     }
1381 
1382     /// Write message
write_message_no_tag<M: Message>(&mut self, msg: &M) -> ProtobufResult<()>1383     pub fn write_message_no_tag<M: Message>(&mut self, msg: &M) -> ProtobufResult<()> {
1384         msg.write_length_delimited_to(self)
1385     }
1386 
1387     /// Write `bytes` field
write_bytes(&mut self, field_number: u32, bytes: &[u8]) -> ProtobufResult<()>1388     pub fn write_bytes(&mut self, field_number: u32, bytes: &[u8]) -> ProtobufResult<()> {
1389         self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?;
1390         self.write_bytes_no_tag(bytes)?;
1391         Ok(())
1392     }
1393 
1394     /// Write `string` field
write_string(&mut self, field_number: u32, s: &str) -> ProtobufResult<()>1395     pub fn write_string(&mut self, field_number: u32, s: &str) -> ProtobufResult<()> {
1396         self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?;
1397         self.write_string_no_tag(s)?;
1398         Ok(())
1399     }
1400 
1401     /// Write `message` field
write_message<M: Message>(&mut self, field_number: u32, msg: &M) -> ProtobufResult<()>1402     pub fn write_message<M: Message>(&mut self, field_number: u32, msg: &M) -> ProtobufResult<()> {
1403         self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?;
1404         self.write_message_no_tag(msg)?;
1405         Ok(())
1406     }
1407 }
1408 
1409 impl<'a> Write for CodedOutputStream<'a> {
write(&mut self, buf: &[u8]) -> io::Result<usize>1410     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1411         self.write_raw_bytes(buf)?;
1412         Ok(buf.len())
1413     }
1414 
flush(&mut self) -> io::Result<()>1415     fn flush(&mut self) -> io::Result<()> {
1416         CodedOutputStream::flush(self).map_err(Into::into)
1417     }
1418 }
1419 
1420 #[cfg(test)]
1421 mod test {
1422 
1423     use std::fmt::Debug;
1424     use std::io;
1425     use std::io::BufRead;
1426     use std::io::Read;
1427     use std::io::Write;
1428     use std::iter::repeat;
1429 
1430     use error::ProtobufError;
1431     use error::ProtobufResult;
1432     use hex::decode_hex;
1433     use hex::encode_hex;
1434 
1435     use super::wire_format;
1436     use super::CodedInputStream;
1437     use super::CodedOutputStream;
1438     use super::READ_RAW_BYTES_MAX_ALLOC;
1439 
test_read_partial<F>(hex: &str, mut callback: F) where F: FnMut(&mut CodedInputStream),1440     fn test_read_partial<F>(hex: &str, mut callback: F)
1441     where
1442         F: FnMut(&mut CodedInputStream),
1443     {
1444         let d = decode_hex(hex);
1445         let mut reader = io::Cursor::new(d);
1446         let mut is = CodedInputStream::from_buffered_reader(&mut reader as &mut dyn BufRead);
1447         assert_eq!(0, is.pos());
1448         callback(&mut is);
1449     }
1450 
test_read<F>(hex: &str, mut callback: F) where F: FnMut(&mut CodedInputStream),1451     fn test_read<F>(hex: &str, mut callback: F)
1452     where
1453         F: FnMut(&mut CodedInputStream),
1454     {
1455         let len = decode_hex(hex).len();
1456         test_read_partial(hex, |reader| {
1457             callback(reader);
1458             assert!(reader.eof().expect("eof"));
1459             assert_eq!(len as u64, reader.pos());
1460         });
1461     }
1462 
test_read_v<F, V>(hex: &str, v: V, mut callback: F) where F: FnMut(&mut CodedInputStream) -> ProtobufResult<V>, V: PartialEq + Debug,1463     fn test_read_v<F, V>(hex: &str, v: V, mut callback: F)
1464     where
1465         F: FnMut(&mut CodedInputStream) -> ProtobufResult<V>,
1466         V: PartialEq + Debug,
1467     {
1468         test_read(hex, |reader| {
1469             assert_eq!(v, callback(reader).unwrap());
1470         });
1471     }
1472 
1473     #[test]
test_input_stream_read_raw_byte()1474     fn test_input_stream_read_raw_byte() {
1475         test_read("17", |is| {
1476             assert_eq!(23, is.read_raw_byte().unwrap());
1477         });
1478     }
1479 
1480     #[test]
test_input_stream_read_raw_varint()1481     fn test_input_stream_read_raw_varint() {
1482         test_read_v("07", 7, |reader| reader.read_raw_varint32());
1483         test_read_v("07", 7, |reader| reader.read_raw_varint64());
1484 
1485         test_read_v("96 01", 150, |reader| reader.read_raw_varint32());
1486         test_read_v("96 01", 150, |reader| reader.read_raw_varint64());
1487 
1488         test_read_v(
1489             "ff ff ff ff ff ff ff ff ff 01",
1490             0xffffffffffffffff,
1491             |reader| reader.read_raw_varint64(),
1492         );
1493 
1494         test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| {
1495             reader.read_raw_varint32()
1496         });
1497         test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| {
1498             reader.read_raw_varint64()
1499         });
1500     }
1501 
1502     #[test]
test_input_stream_read_raw_vaint_malformed()1503     fn test_input_stream_read_raw_vaint_malformed() {
1504         // varint cannot have length > 10
1505         test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| {
1506             let result = reader.read_raw_varint64();
1507             match result {
1508                 // TODO: make an enum variant
1509                 Err(ProtobufError::WireError(..)) => (),
1510                 _ => panic!(),
1511             }
1512         });
1513         test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| {
1514             let result = reader.read_raw_varint32();
1515             match result {
1516                 // TODO: make an enum variant
1517                 Err(ProtobufError::WireError(..)) => (),
1518                 _ => panic!(),
1519             }
1520         });
1521     }
1522 
1523     #[test]
test_input_stream_read_raw_varint_unexpected_eof()1524     fn test_input_stream_read_raw_varint_unexpected_eof() {
1525         test_read_partial("96 97", |reader| {
1526             let result = reader.read_raw_varint32();
1527             match result {
1528                 Err(ProtobufError::WireError(..)) => (),
1529                 _ => panic!(),
1530             }
1531         });
1532     }
1533 
1534     #[test]
test_input_stream_read_raw_varint_pos()1535     fn test_input_stream_read_raw_varint_pos() {
1536         test_read_partial("95 01 98", |reader| {
1537             assert_eq!(149, reader.read_raw_varint32().unwrap());
1538             assert_eq!(2, reader.pos());
1539         });
1540     }
1541 
1542     #[test]
test_input_stream_read_int32()1543     fn test_input_stream_read_int32() {
1544         test_read_v("02", 2, |reader| reader.read_int32());
1545     }
1546 
1547     #[test]
test_input_stream_read_float()1548     fn test_input_stream_read_float() {
1549         test_read_v("95 73 13 61", 17e19, |is| is.read_float());
1550     }
1551 
1552     #[test]
test_input_stream_read_double()1553     fn test_input_stream_read_double() {
1554         test_read_v("40 d5 ab 68 b3 07 3d 46", 23e29, |is| is.read_double());
1555     }
1556 
1557     #[test]
test_input_stream_skip_raw_bytes()1558     fn test_input_stream_skip_raw_bytes() {
1559         test_read("", |reader| {
1560             reader.skip_raw_bytes(0).unwrap();
1561         });
1562         test_read("aa bb", |reader| {
1563             reader.skip_raw_bytes(2).unwrap();
1564         });
1565         test_read("aa bb cc dd ee ff", |reader| {
1566             reader.skip_raw_bytes(6).unwrap();
1567         });
1568     }
1569 
1570     #[test]
test_input_stream_read_raw_bytes()1571     fn test_input_stream_read_raw_bytes() {
1572         test_read("", |reader| {
1573             assert_eq!(
1574                 Vec::from(&b""[..]),
1575                 reader.read_raw_bytes(0).expect("read_raw_bytes")
1576             );
1577         })
1578     }
1579 
1580     #[test]
test_input_stream_limits()1581     fn test_input_stream_limits() {
1582         test_read("aa bb cc", |is| {
1583             let old_limit = is.push_limit(1).unwrap();
1584             assert_eq!(1, is.bytes_until_limit());
1585             let r1 = is.read_raw_bytes(1).unwrap();
1586             assert_eq!(&[0xaa as u8], &r1[..]);
1587             is.pop_limit(old_limit);
1588             let r2 = is.read_raw_bytes(2).unwrap();
1589             assert_eq!(&[0xbb as u8, 0xcc], &r2[..]);
1590         });
1591     }
1592 
1593     #[test]
test_input_stream_io_read()1594     fn test_input_stream_io_read() {
1595         test_read("aa bb cc", |is| {
1596             let mut buf = [0; 3];
1597             assert_eq!(Read::read(is, &mut buf).expect("io::Read"), 3);
1598             assert_eq!(buf, [0xaa, 0xbb, 0xcc]);
1599         });
1600     }
1601 
1602     #[test]
test_input_stream_io_bufread()1603     fn test_input_stream_io_bufread() {
1604         test_read("aa bb cc", |is| {
1605             assert_eq!(
1606                 BufRead::fill_buf(is).expect("io::BufRead::fill_buf"),
1607                 &[0xaa, 0xbb, 0xcc]
1608             );
1609             BufRead::consume(is, 3);
1610         });
1611     }
1612 
1613     #[test]
test_input_stream_read_raw_bytes_into_huge()1614     fn test_input_stream_read_raw_bytes_into_huge() {
1615         let mut v = Vec::new();
1616         for i in 0..READ_RAW_BYTES_MAX_ALLOC + 1000 {
1617             v.push((i % 10) as u8);
1618         }
1619 
1620         let mut slice: &[u8] = v.as_slice();
1621 
1622         let mut is = CodedInputStream::new(&mut slice);
1623 
1624         let mut buf = Vec::new();
1625 
1626         is.read_raw_bytes_into(READ_RAW_BYTES_MAX_ALLOC as u32 + 10, &mut buf)
1627             .expect("read");
1628 
1629         assert_eq!(READ_RAW_BYTES_MAX_ALLOC + 10, buf.len());
1630 
1631         buf.clear();
1632 
1633         is.read_raw_bytes_into(1000 - 10, &mut buf).expect("read");
1634 
1635         assert_eq!(1000 - 10, buf.len());
1636 
1637         assert!(is.eof().expect("eof"));
1638     }
1639 
test_write<F>(expected: &str, mut gen: F) where F: FnMut(&mut CodedOutputStream) -> ProtobufResult<()>,1640     fn test_write<F>(expected: &str, mut gen: F)
1641     where
1642         F: FnMut(&mut CodedOutputStream) -> ProtobufResult<()>,
1643     {
1644         let expected_bytes = decode_hex(expected);
1645 
1646         // write to Write
1647         {
1648             let mut v = Vec::new();
1649             {
1650                 let mut os = CodedOutputStream::new(&mut v as &mut dyn Write);
1651                 gen(&mut os).unwrap();
1652                 os.flush().unwrap();
1653             }
1654             assert_eq!(encode_hex(&expected_bytes), encode_hex(&v));
1655         }
1656 
1657         // write to &[u8]
1658         {
1659             let mut r = Vec::with_capacity(expected_bytes.len());
1660             r.resize(expected_bytes.len(), 0);
1661             {
1662                 let mut os = CodedOutputStream::bytes(&mut r);
1663                 gen(&mut os).unwrap();
1664                 os.check_eof();
1665             }
1666             assert_eq!(encode_hex(&expected_bytes), encode_hex(&r));
1667         }
1668 
1669         // write to Vec<u8>
1670         {
1671             let mut r = Vec::new();
1672             r.extend(&[11, 22, 33, 44, 55, 66, 77]);
1673             {
1674                 let mut os = CodedOutputStream::vec(&mut r);
1675                 gen(&mut os).unwrap();
1676                 os.flush().unwrap();
1677             }
1678 
1679             r.drain(..7);
1680             assert_eq!(encode_hex(&expected_bytes), encode_hex(&r));
1681         }
1682     }
1683 
1684     #[test]
test_output_stream_write_raw_byte()1685     fn test_output_stream_write_raw_byte() {
1686         test_write("a1", |os| os.write_raw_byte(0xa1));
1687     }
1688 
1689     #[test]
test_output_stream_write_tag()1690     fn test_output_stream_write_tag() {
1691         test_write("08", |os| os.write_tag(1, wire_format::WireTypeVarint));
1692     }
1693 
1694     #[test]
test_output_stream_write_raw_bytes()1695     fn test_output_stream_write_raw_bytes() {
1696         test_write("00 ab", |os| os.write_raw_bytes(&[0x00, 0xab]));
1697 
1698         let expected = repeat("01 02 03 04")
1699             .take(2048)
1700             .collect::<Vec<_>>()
1701             .join(" ");
1702         test_write(&expected, |os| {
1703             for _ in 0..2048 {
1704                 os.write_raw_bytes(&[0x01, 0x02, 0x03, 0x04])?;
1705             }
1706 
1707             Ok(())
1708         });
1709     }
1710 
1711     #[test]
test_output_stream_write_raw_varint32()1712     fn test_output_stream_write_raw_varint32() {
1713         test_write("96 01", |os| os.write_raw_varint32(150));
1714         test_write("ff ff ff ff 0f", |os| os.write_raw_varint32(0xffffffff));
1715     }
1716 
1717     #[test]
test_output_stream_write_raw_varint64()1718     fn test_output_stream_write_raw_varint64() {
1719         test_write("96 01", |os| os.write_raw_varint64(150));
1720         test_write("ff ff ff ff ff ff ff ff ff 01", |os| {
1721             os.write_raw_varint64(0xffffffffffffffff)
1722         });
1723     }
1724 
1725     #[test]
test_output_stream_write_int32_no_tag()1726     fn test_output_stream_write_int32_no_tag() {
1727         test_write("ff ff ff ff ff ff ff ff ff 01", |os| {
1728             os.write_int32_no_tag(-1)
1729         });
1730     }
1731 
1732     #[test]
test_output_stream_write_int64_no_tag()1733     fn test_output_stream_write_int64_no_tag() {
1734         test_write("ff ff ff ff ff ff ff ff ff 01", |os| {
1735             os.write_int64_no_tag(-1)
1736         });
1737     }
1738 
1739     #[test]
test_output_stream_write_raw_little_endian32()1740     fn test_output_stream_write_raw_little_endian32() {
1741         test_write("f1 e2 d3 c4", |os| os.write_raw_little_endian32(0xc4d3e2f1));
1742     }
1743 
1744     #[test]
test_output_stream_write_float_no_tag()1745     fn test_output_stream_write_float_no_tag() {
1746         test_write("95 73 13 61", |os| os.write_float_no_tag(17e19));
1747     }
1748 
1749     #[test]
test_output_stream_write_double_no_tag()1750     fn test_output_stream_write_double_no_tag() {
1751         test_write("40 d5 ab 68 b3 07 3d 46", |os| {
1752             os.write_double_no_tag(23e29)
1753         });
1754     }
1755 
1756     #[test]
test_output_stream_write_raw_little_endian64()1757     fn test_output_stream_write_raw_little_endian64() {
1758         test_write("f1 e2 d3 c4 b5 a6 07 f8", |os| {
1759             os.write_raw_little_endian64(0xf807a6b5c4d3e2f1)
1760         });
1761     }
1762 
1763     #[test]
test_output_stream_io_write()1764     fn test_output_stream_io_write() {
1765         let expected = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77];
1766 
1767         // write to Write
1768         {
1769             let mut v = Vec::new();
1770             {
1771                 let mut os = CodedOutputStream::new(&mut v as &mut dyn Write);
1772                 Write::write(&mut os, &expected).expect("io::Write::write");
1773                 Write::flush(&mut os).expect("io::Write::flush");
1774             }
1775             assert_eq!(expected, *v);
1776         }
1777 
1778         // write to &[u8]
1779         {
1780             let mut v = Vec::with_capacity(expected.len());
1781             v.resize(expected.len(), 0);
1782             {
1783                 let mut os = CodedOutputStream::bytes(&mut v);
1784                 Write::write(&mut os, &expected).expect("io::Write::write");
1785                 Write::flush(&mut os).expect("io::Write::flush");
1786                 os.check_eof();
1787             }
1788             assert_eq!(expected, *v);
1789         }
1790 
1791         // write to Vec<u8>
1792         {
1793             let mut v = Vec::new();
1794             {
1795                 let mut os = CodedOutputStream::vec(&mut v);
1796                 Write::write(&mut os, &expected).expect("io::Write::write");
1797                 Write::flush(&mut os).expect("io::Write::flush");
1798             }
1799             assert_eq!(expected, *v);
1800         }
1801     }
1802 }
1803