1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! A module to manage protobuf serialization

use crate::errors::{Error, Result};
use crate::message::MessageWrite;

use byteorder::{ByteOrder, LittleEndian as LE};

#[cfg(feature = "std")]
use byteorder::WriteBytesExt;

/// A struct to write protobuf messages
///
/// # Examples
///
/// ```rust
/// // an automatically generated module which is in a separate file in general
/// mod foo_bar {
///     # use quick_protobuf::{MessageWrite, Writer, WriterBackend, Result};
///     # use std::borrow::Cow;
///     pub struct Foo<'a> { pub name: Option<Cow<'a, str>>, }
///     pub struct Bar { pub id: Option<u32> }
///     pub struct FooBar<'a> { pub foos: Vec<Foo<'a>>, pub bars: Vec<Bar>, }
///     impl<'a> MessageWrite for FooBar<'a> {
///         // implements
///         // fn get_size(&self) -> usize { ... }
///         // fn write_message<W: WriterBackend>(&self, r: &mut Writer<W>) -> Result<()> { ... }
///         # fn get_size(&self) -> usize { 0 }
///         # fn write_message<W: WriterBackend>(&self, _: &mut Writer<W>) -> Result<()> { Ok(()) }
///     }
/// }
///
/// // FooBar is a message generated from a proto file
/// // in parcicular it contains a `write_message` function
/// use foo_bar::{FooBar, Foo, Bar};
/// use std::borrow::Cow;
/// use quick_protobuf::Writer;
///
/// fn main() {
///     // let mut r = File::create("...").expect("Cannot create file");
///     // for the sake of example, we'll use a simpler struct which impl `Write`
///     let mut r = Vec::new();
///     let mut writer = Writer::new(&mut r);
///
///     // manually generates a FooBar for the example
///     let foobar = FooBar {
///         foos: vec![Foo { name: Some(Cow::Borrowed("test!")) }, Foo { name: None }],
///         bars: vec![Bar { id: Some(43) }, Bar { id: None }],
///     };
///
///     // now using the generated module
///     writer.write_message(&foobar).expect("Cannot write FooBar");
/// }
/// ```
pub struct Writer<W: WriterBackend> {
    inner: W,
}

impl<W: WriterBackend> Writer<W> {
    /// Creates a new `ProtobufWriter`
    pub fn new(w: W) -> Writer<W> {
        Writer { inner: w }
    }

    /// Writes a byte which is NOT internally coded as a `varint`
    pub fn write_u8(&mut self, byte: u8) -> Result<()> {
        self.inner.pb_write_u8(byte)
    }

    /// Writes a `varint` (compacted `u64`)
    pub fn write_varint(&mut self, mut v: u64) -> Result<()> {
        while v > 0x7F {
            self.inner.pb_write_u8(((v as u8) & 0x7F) | 0x80)?;
            v >>= 7;
        }
        self.inner.pb_write_u8(v as u8)
    }

    /// Writes a tag, which represents both the field number and the wire type
    #[cfg_attr(std, inline(always))]
    pub fn write_tag(&mut self, tag: u32) -> Result<()> {
        self.write_varint(tag as u64)
    }

    /// Writes a `int32` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_int32(&mut self, v: i32) -> Result<()> {
        self.write_varint(v as u64)
    }

    /// Writes a `int64` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_int64(&mut self, v: i64) -> Result<()> {
        self.write_varint(v as u64)
    }

    /// Writes a `uint32` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_uint32(&mut self, v: u32) -> Result<()> {
        self.write_varint(v as u64)
    }

    /// Writes a `uint64` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_uint64(&mut self, v: u64) -> Result<()> {
        self.write_varint(v)
    }

    /// Writes a `sint32` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_sint32(&mut self, v: i32) -> Result<()> {
        self.write_varint(((v << 1) ^ (v >> 31)) as u64)
    }

    /// Writes a `sint64` which is internally coded as a `varint`
    #[cfg_attr(std, inline(always))]
    pub fn write_sint64(&mut self, v: i64) -> Result<()> {
        self.write_varint(((v << 1) ^ (v >> 63)) as u64)
    }

    /// Writes a `fixed64` which is little endian coded `u64`
    #[cfg_attr(std, inline(always))]
    pub fn write_fixed64(&mut self, v: u64) -> Result<()> {
        self.inner.pb_write_u64(v)
    }

    /// Writes a `fixed32` which is little endian coded `u32`
    #[cfg_attr(std, inline(always))]
    pub fn write_fixed32(&mut self, v: u32) -> Result<()> {
        self.inner.pb_write_u32(v)
    }

    /// Writes a `sfixed64` which is little endian coded `i64`
    #[cfg_attr(std, inline(always))]
    pub fn write_sfixed64(&mut self, v: i64) -> Result<()> {
        self.inner.pb_write_i64(v)
    }

    /// Writes a `sfixed32` which is little endian coded `i32`
    #[cfg_attr(std, inline(always))]
    pub fn write_sfixed32(&mut self, v: i32) -> Result<()> {
        self.inner.pb_write_i32(v)
    }

    /// Writes a `float`
    #[cfg_attr(std, inline(always))]
    pub fn write_float(&mut self, v: f32) -> Result<()> {
        self.inner.pb_write_f32(v)
    }

    /// Writes a `double`
    #[cfg_attr(std, inline(always))]
    pub fn write_double(&mut self, v: f64) -> Result<()> {
        self.inner.pb_write_f64(v)
    }

    /// Writes a `bool` 1 = true, 0 = false
    #[cfg_attr(std, inline(always))]
    pub fn write_bool(&mut self, v: bool) -> Result<()> {
        self.inner.pb_write_u8(if v { 1 } else { 0 })
    }

    /// Writes an `enum` converting it to a `i32` first
    #[cfg_attr(std, inline(always))]
    pub fn write_enum(&mut self, v: i32) -> Result<()> {
        self.write_int32(v)
    }

    /// Writes `bytes`: length first then the chunk of data
    #[cfg_attr(std, inline(always))]
    pub fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        self.write_varint(bytes.len() as u64)?;
        self.inner.pb_write_all(bytes)
    }

    /// Writes `string`: length first then the chunk of data
    #[cfg_attr(std, inline(always))]
    pub fn write_string(&mut self, s: &str) -> Result<()> {
        self.write_bytes(s.as_bytes())
    }

    /// Writes packed repeated field: length first then the chunk of data
    pub fn write_packed<M, F, S>(&mut self, v: &[M], mut write: F, size: &S) -> Result<()>
    where
        F: FnMut(&mut Self, &M) -> Result<()>,
        S: Fn(&M) -> usize,
    {
        if v.is_empty() {
            return Ok(());
        }
        let len: usize = v.iter().map(|m| size(m)).sum();
        self.write_varint(len as u64)?;
        for m in v {
            write(self, m)?;
        }
        Ok(())
    }

    /// Writes packed repeated field when we know the size of items
    ///
    /// `item_size` is internally used to compute the total length
    /// As the length is fixed (and the same as rust internal representation, we can directly dump
    /// all data at once
    #[cfg_attr(std, inline)]
    pub fn write_packed_fixed<M>(&mut self, v: &[M]) -> Result<()> {
        let len = v.len() * ::core::mem::size_of::<M>();
        let bytes = unsafe { ::core::slice::from_raw_parts(v.as_ptr() as *const u8, len) };
        self.write_bytes(bytes)
    }

    /// Writes a message which implements `MessageWrite`
    #[cfg_attr(std, inline)]
    pub fn write_message<M: MessageWrite>(&mut self, m: &M) -> Result<()> {
        let len = m.get_size();
        self.write_varint(len as u64)?;
        m.write_message(self)
    }

    /// Writes another item prefixed with tag
    #[cfg_attr(std, inline)]
    pub fn write_with_tag<F>(&mut self, tag: u32, mut write: F) -> Result<()>
    where
        F: FnMut(&mut Self) -> Result<()>,
    {
        self.write_tag(tag)?;
        write(self)
    }

    /// Writes tag then repeated field
    ///
    /// If array is empty, then do nothing (do not even write the tag)
    pub fn write_packed_with_tag<M, F, S>(
        &mut self,
        tag: u32,
        v: &[M],
        mut write: F,
        size: &S,
    ) -> Result<()>
    where
        F: FnMut(&mut Self, &M) -> Result<()>,
        S: Fn(&M) -> usize,
    {
        if v.is_empty() {
            return Ok(());
        }

        self.write_tag(tag)?;
        let len: usize = v.iter().map(|m| size(m)).sum();
        self.write_varint(len as u64)?;
        for m in v {
            write(self, m)?;
        }
        Ok(())
    }

    /// Writes tag then repeated field
    ///
    /// If array is empty, then do nothing (do not even write the tag)
    pub fn write_packed_fixed_with_tag<M>(&mut self, tag: u32, v: &[M]) -> Result<()> {
        if v.is_empty() {
            return Ok(());
        }

        self.write_tag(tag)?;
        let len = ::core::mem::size_of::<M>() * v.len();
        let bytes = unsafe { ::core::slice::from_raw_parts(v.as_ptr() as *const u8, len) };
        self.write_bytes(bytes)
    }

    /// Writes tag then repeated field with fixed length item size
    ///
    /// If array is empty, then do nothing (do not even write the tag)
    pub fn write_packed_fixed_size_with_tag<M>(
        &mut self,
        tag: u32,
        v: &[M],
        item_size: usize,
    ) -> Result<()> {
        if v.is_empty() {
            return Ok(());
        }
        self.write_tag(tag)?;
        let len = v.len() * item_size;
        let bytes =
            unsafe { ::core::slice::from_raw_parts(v as *const [M] as *const M as *const u8, len) };
        self.write_bytes(bytes)
    }

    /// Write entire map
    pub fn write_map<FK, FV>(
        &mut self,
        size: usize,
        tag_key: u32,
        mut write_key: FK,
        tag_val: u32,
        mut write_val: FV,
    ) -> Result<()>
    where
        FK: FnMut(&mut Self) -> Result<()>,
        FV: FnMut(&mut Self) -> Result<()>,
    {
        self.write_varint(size as u64)?;
        self.write_tag(tag_key)?;
        write_key(self)?;
        self.write_tag(tag_val)?;
        write_val(self)
    }
}

/// Serialize a `MessageWrite` into a `Vec`
#[cfg(feature = "std")]
pub fn serialize_into_vec<M: MessageWrite>(message: &M) -> Result<Vec<u8>> {
    let len = message.get_size();
    let mut v = Vec::with_capacity(crate::sizeofs::sizeof_len(len));
    {
        let mut writer = Writer::new(&mut v);
        writer.write_message(message)?;
    }
    Ok(v)
}

/// Serialize a `MessageWrite` into a byte slice
pub fn serialize_into_slice<M: MessageWrite>(message: &M, out: &mut [u8]) -> Result<()> {
    let len = message.get_size();
    if out.len() < crate::sizeofs::sizeof_len(len) {
        return Err(Error::OutputBufferTooSmall);
    }
    {
        let mut writer = Writer::new(BytesWriter::new(out));
        writer.write_message(message)?;
    }

    Ok(())
}

/// Writer backend abstraction
pub trait WriterBackend {
    /// Write a u8
    fn pb_write_u8(&mut self, x: u8) -> Result<()>;

    /// Write a u32
    fn pb_write_u32(&mut self, x: u32) -> Result<()>;

    /// Write a i32
    fn pb_write_i32(&mut self, x: i32) -> Result<()>;

    /// Write a f32
    fn pb_write_f32(&mut self, x: f32) -> Result<()>;

    /// Write a u64
    fn pb_write_u64(&mut self, x: u64) -> Result<()>;

    /// Write a i64
    fn pb_write_i64(&mut self, x: i64) -> Result<()>;

    /// Write a f64
    fn pb_write_f64(&mut self, x: f64) -> Result<()>;

    /// Write all bytes in buf
    fn pb_write_all(&mut self, buf: &[u8]) -> Result<()>;
}

/// A writer backend for byte buffers
pub struct BytesWriter<'a> {
    buf: &'a mut [u8],
    cursor: usize,
}

impl<'a> BytesWriter<'a> {
    /// Create a new BytesWriter to write into `buf`
    pub fn new(buf: &'a mut [u8]) -> BytesWriter<'a> {
        BytesWriter { buf, cursor: 0 }
    }
}

impl<'a> WriterBackend for BytesWriter<'a> {
    #[cfg_attr(std, inline(always))]
    fn pb_write_u8(&mut self, x: u8) -> Result<()> {
        if self.buf.len() - self.cursor < 1 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            self.buf[self.cursor] = x;
            self.cursor += 1;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_u32(&mut self, x: u32) -> Result<()> {
        if self.buf.len() - self.cursor < 4 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_u32(&mut self.buf[self.cursor..], x);
            self.cursor += 4;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_i32(&mut self, x: i32) -> Result<()> {
        if self.buf.len() - self.cursor < 4 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_i32(&mut self.buf[self.cursor..], x);
            self.cursor += 4;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_f32(&mut self, x: f32) -> Result<()> {
        if self.buf.len() - self.cursor < 4 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_f32(&mut self.buf[self.cursor..], x);
            self.cursor += 4;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_u64(&mut self, x: u64) -> Result<()> {
        if self.buf.len() - self.cursor < 8 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_u64(&mut self.buf[self.cursor..], x);
            self.cursor += 8;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_i64(&mut self, x: i64) -> Result<()> {
        if self.buf.len() - self.cursor < 8 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_i64(&mut self.buf[self.cursor..], x);
            self.cursor += 8;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_f64(&mut self, x: f64) -> Result<()> {
        if self.buf.len() - self.cursor < 8 {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            LE::write_f64(&mut self.buf[self.cursor..], x);
            self.cursor += 8;
            Ok(())
        }
    }

    #[cfg_attr(std, inline(always))]
    fn pb_write_all(&mut self, buf: &[u8]) -> Result<()> {
        if self.buf.len() - self.cursor < buf.len() {
            Err(Error::UnexpectedEndOfBuffer)
        } else {
            self.buf[self.cursor..(self.cursor + buf.len())].copy_from_slice(buf);
            self.cursor += buf.len();
            Ok(())
        }
    }
}

#[cfg(feature = "std")]
impl<W: std::io::Write> WriterBackend for W {
    #[inline(always)]
    fn pb_write_u8(&mut self, x: u8) -> Result<()> {
        self.write_u8(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_u32(&mut self, x: u32) -> Result<()> {
        self.write_u32::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_i32(&mut self, x: i32) -> Result<()> {
        self.write_i32::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_f32(&mut self, x: f32) -> Result<()> {
        self.write_f32::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_u64(&mut self, x: u64) -> Result<()> {
        self.write_u64::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_i64(&mut self, x: i64) -> Result<()> {
        self.write_i64::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_f64(&mut self, x: f64) -> Result<()> {
        self.write_f64::<LE>(x).map_err(|e| e.into())
    }

    #[inline(always)]
    fn pb_write_all(&mut self, buf: &[u8]) -> Result<()> {
        self.write_all(buf).map_err(|e| e.into())
    }
}

#[test]
fn test_issue_222() {
    // remember that `serialize_into_vec()` and `serialize_into_slice()` add a
    // length prefix in addition to writing the message itself; important for
    // when you look at the buffer sizes and errors thrown in this test

    struct TestMsg {}

    impl MessageWrite for TestMsg {
        fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
            let bytes = [0x08u8, 0x96u8, 0x01u8];
            for b in bytes {
                // use `write_u8()` in loop because some other functions have
                // hidden writes (length prefixes etc.) inside them.
                w.write_u8(b)?;
            }
            Ok(())
        }

        fn get_size(&self) -> usize {
            3 // corresponding to `bytes` above
        }
    }

    let msg = TestMsg {};
    let v = serialize_into_vec(&msg).unwrap();
    // We would really like to assert that the vector `v` WITHIN
    // `serialize_into_vec()` does not get its capacity modified after
    // initializion with `with_capacity()`, but the only way to do that would be
    // to put an assert within `serialize_into_vec()` itself, which isn't a
    // pattern seen in this project.
    //
    // Instead, we do this. If this check fails, it definitely means that the
    // capacity setting in `serialize_into_vec()` is suboptimal, but passing
    // doesn't guarantee that it is optimal.
    assert_eq!(v.len(), v.capacity());

    let mut buf_len_2 = vec![0x00u8, 0x00u8];
    let mut buf_len_3 = vec![0x00u8, 0x00u8, 0x00u8];
    let mut buf_len_4 = vec![0x00u8, 0x00u8, 0x00u8, 0x00u8];

    assert!(matches!(
        serialize_into_slice(&msg, buf_len_2.as_mut_slice()),
        Err(Error::OutputBufferTooSmall)
    ));
    assert!(matches!(
        // the salient case in issue 222; before bugfix this would have been
        // Err(Error::UnexpectedEndOfBuffer)
        serialize_into_slice(&msg, buf_len_3.as_mut_slice()),
        Err(Error::OutputBufferTooSmall)
    ));
    assert!(matches!(
        serialize_into_slice(&msg, buf_len_4.as_mut_slice()),
        Ok(())
    ));
}