1 // Copyright 2018 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::fmt;
6 use std::io;
7 use std::io::{ErrorKind, Read, Write};
8 use std::mem;
9 use std::ops::{Deref, DerefMut};
10 use std::string::String;
11 use std::vec::Vec;
12 
13 /// A type that can be encoded on the wire using the 9P protocol.
14 pub trait WireFormat: std::marker::Sized {
15     /// Returns the number of bytes necessary to fully encode `self`.
byte_size(&self) -> u3216     fn byte_size(&self) -> u32;
17 
18     /// Encodes `self` into `writer`.
encode<W: Write>(&self, writer: &mut W) -> io::Result<()>19     fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()>;
20 
21     /// Decodes `Self` from `reader`.
decode<R: Read>(reader: &mut R) -> io::Result<Self>22     fn decode<R: Read>(reader: &mut R) -> io::Result<Self>;
23 }
24 
25 // This doesn't really _need_ to be a macro but unfortunately there is no trait bound to
26 // express "can be casted to another type", which means we can't write `T as u8` in a trait
27 // based implementation.  So instead we have this macro, which is implemented for all the
28 // stable unsigned types with the added benefit of not being implemented for the signed
29 // types which are not allowed by the protocol.
30 macro_rules! uint_wire_format_impl {
31     ($Ty:ty) => {
32         impl WireFormat for $Ty {
33             fn byte_size(&self) -> u32 {
34                 mem::size_of::<$Ty>() as u32
35             }
36 
37             fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
38                 let mut buf = [0u8; mem::size_of::<$Ty>()];
39 
40                 // Encode the bytes into the buffer in little endian order.
41                 for idx in 0..mem::size_of::<$Ty>() {
42                     buf[idx] = (self >> (8 * idx)) as u8;
43                 }
44 
45                 writer.write_all(&buf)
46             }
47 
48             fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
49                 let mut buf = [0u8; mem::size_of::<$Ty>()];
50                 reader.read_exact(&mut buf)?;
51 
52                 // Read bytes from the buffer in little endian order.
53                 let mut result = 0;
54                 for idx in 0..mem::size_of::<$Ty>() {
55                     result |= (buf[idx] as $Ty) << (8 * idx);
56                 }
57 
58                 Ok(result)
59             }
60         }
61     };
62 }
63 uint_wire_format_impl!(u8);
64 uint_wire_format_impl!(u16);
65 uint_wire_format_impl!(u32);
66 uint_wire_format_impl!(u64);
67 
68 // The 9P protocol requires that strings are UTF-8 encoded.  The wire format is a u16
69 // count |N|, encoded in little endian, followed by |N| bytes of UTF-8 data.
70 impl WireFormat for String {
byte_size(&self) -> u3271     fn byte_size(&self) -> u32 {
72         (mem::size_of::<u16>() + self.len()) as u32
73     }
74 
encode<W: Write>(&self, writer: &mut W) -> io::Result<()>75     fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
76         if self.len() > std::u16::MAX as usize {
77             return Err(io::Error::new(
78                 ErrorKind::InvalidInput,
79                 "string is too long",
80             ));
81         }
82 
83         (self.len() as u16).encode(writer)?;
84         writer.write_all(self.as_bytes())
85     }
86 
decode<R: Read>(reader: &mut R) -> io::Result<Self>87     fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
88         let len: u16 = WireFormat::decode(reader)?;
89         let mut result = String::with_capacity(len as usize);
90         reader.take(len as u64).read_to_string(&mut result)?;
91         Ok(result)
92     }
93 }
94 
95 // The wire format for repeated types is similar to that of strings: a little endian
96 // encoded u16 |N|, followed by |N| instances of the given type.
97 impl<T: WireFormat> WireFormat for Vec<T> {
byte_size(&self) -> u3298     fn byte_size(&self) -> u32 {
99         mem::size_of::<u16>() as u32 + self.iter().map(|elem| elem.byte_size()).sum::<u32>()
100     }
101 
encode<W: Write>(&self, writer: &mut W) -> io::Result<()>102     fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
103         if self.len() > std::u16::MAX as usize {
104             return Err(io::Error::new(
105                 ErrorKind::InvalidInput,
106                 "too many elements in vector",
107             ));
108         }
109 
110         (self.len() as u16).encode(writer)?;
111         for elem in self {
112             elem.encode(writer)?;
113         }
114 
115         Ok(())
116     }
117 
decode<R: Read>(reader: &mut R) -> io::Result<Self>118     fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
119         let len: u16 = WireFormat::decode(reader)?;
120         let mut result = Vec::with_capacity(len as usize);
121 
122         for _ in 0..len {
123             result.push(WireFormat::decode(reader)?);
124         }
125 
126         Ok(result)
127     }
128 }
129 
130 /// A type that encodes an arbitrary number of bytes of data.  Typically used for Rread
131 /// Twrite messages.  This differs from a `Vec<u8>` in that it encodes the number of bytes
132 /// using a `u32` instead of a `u16`.
133 #[derive(PartialEq)]
134 pub struct Data(pub Vec<u8>);
135 
136 // The maximum length of a data buffer that we support.  In practice the server's max message
137 // size should prevent us from reading too much data so this check is mainly to ensure a
138 // malicious client cannot trick us into allocating massive amounts of memory.
139 const MAX_DATA_LENGTH: u32 = 32 * 1024 * 1024;
140 
141 impl fmt::Debug for Data {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result142     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143         // There may be a lot of data and we don't want to spew it all out in a trace.  Instead
144         // just print out the number of bytes in the buffer.
145         write!(f, "Data({} bytes)", self.len())
146     }
147 }
148 
149 // Implement Deref and DerefMut so that we don't have to use self.0 everywhere.
150 impl Deref for Data {
151     type Target = Vec<u8>;
deref(&self) -> &Self::Target152     fn deref(&self) -> &Self::Target {
153         &self.0
154     }
155 }
156 impl DerefMut for Data {
deref_mut(&mut self) -> &mut Self::Target157     fn deref_mut(&mut self) -> &mut Self::Target {
158         &mut self.0
159     }
160 }
161 
162 // Same as Vec<u8> except that it encodes the length as a u32 instead of a u16.
163 impl WireFormat for Data {
byte_size(&self) -> u32164     fn byte_size(&self) -> u32 {
165         mem::size_of::<u32>() as u32 + self.iter().map(|elem| elem.byte_size()).sum::<u32>()
166     }
167 
encode<W: Write>(&self, writer: &mut W) -> io::Result<()>168     fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
169         if self.len() > std::u32::MAX as usize {
170             return Err(io::Error::new(ErrorKind::InvalidInput, "data is too large"));
171         }
172         (self.len() as u32).encode(writer)?;
173         writer.write_all(self)
174     }
175 
decode<R: Read>(reader: &mut R) -> io::Result<Self>176     fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
177         let len: u32 = WireFormat::decode(reader)?;
178         if len > MAX_DATA_LENGTH {
179             return Err(io::Error::new(
180                 ErrorKind::InvalidData,
181                 format!("data length ({} bytes) is too large", len),
182             ));
183         }
184 
185         let mut buf = Vec::with_capacity(len as usize);
186         reader.take(len as u64).read_to_end(&mut buf)?;
187 
188         if buf.len() == len as usize {
189             Ok(Data(buf))
190         } else {
191             Err(io::Error::new(
192                 ErrorKind::UnexpectedEof,
193                 format!(
194                     "unexpected end of data: want: {} bytes, got: {} bytes",
195                     len,
196                     buf.len()
197                 ),
198             ))
199         }
200     }
201 }
202 
203 #[cfg(test)]
204 mod test {
205     use super::*;
206     use std::io::Cursor;
207     use std::mem;
208     use std::string::String;
209 
210     #[test]
integer_byte_size()211     fn integer_byte_size() {
212         assert_eq!(1, 0u8.byte_size());
213         assert_eq!(2, 0u16.byte_size());
214         assert_eq!(4, 0u32.byte_size());
215         assert_eq!(8, 0u64.byte_size());
216     }
217 
218     #[test]
integer_decode()219     fn integer_decode() {
220         let buf: [u8; 8] = [0xef, 0xbe, 0xad, 0xde, 0x0d, 0xf0, 0xad, 0x8b];
221 
222         assert_eq!(
223             0xef as u8,
224             WireFormat::decode(&mut Cursor::new(&buf)).unwrap()
225         );
226         assert_eq!(0xbeef as u16, u16::decode(&mut Cursor::new(&buf)).unwrap());
227         assert_eq!(
228             0xdeadbeef as u32,
229             u32::decode(&mut Cursor::new(&buf)).unwrap()
230         );
231         assert_eq!(
232             0x8badf00d_deadbeef as u64,
233             u64::decode(&mut Cursor::new(&buf)).unwrap()
234         );
235     }
236 
237     #[test]
integer_encode()238     fn integer_encode() {
239         let value: u64 = 0x8badf00d_deadbeef;
240         let expected: [u8; 8] = [0xef, 0xbe, 0xad, 0xde, 0x0d, 0xf0, 0xad, 0x8b];
241 
242         let mut buf = vec![0; 8];
243 
244         (value as u8).encode(&mut Cursor::new(&mut *buf)).unwrap();
245         assert_eq!(expected[0..1], buf[0..1]);
246 
247         (value as u16).encode(&mut Cursor::new(&mut *buf)).unwrap();
248         assert_eq!(expected[0..2], buf[0..2]);
249 
250         (value as u32).encode(&mut Cursor::new(&mut *buf)).unwrap();
251         assert_eq!(expected[0..4], buf[0..4]);
252 
253         value.encode(&mut Cursor::new(&mut *buf)).unwrap();
254         assert_eq!(expected[0..8], buf[0..8]);
255     }
256 
257     #[test]
string_byte_size()258     fn string_byte_size() {
259         let values = [
260             String::from("Google Video"),
261             String::from("网页 图片 资讯更多 »"),
262             String::from("Παγκόσμιος Ιστός"),
263             String::from("Поиск страниц на русском"),
264             String::from("전체서비스"),
265         ];
266 
267         let exp = values
268             .iter()
269             .map(|v| (mem::size_of::<u16>() + v.len()) as u32);
270 
271         for (value, expected) in values.iter().zip(exp) {
272             assert_eq!(expected, value.byte_size());
273         }
274     }
275 
276     #[test]
zero_length_string()277     fn zero_length_string() {
278         let s = String::from("");
279         assert_eq!(s.byte_size(), mem::size_of::<u16>() as u32);
280 
281         let mut buf = [0xffu8; 4];
282 
283         s.encode(&mut Cursor::new(&mut buf[..]))
284             .expect("failed to encode empty string");
285         assert_eq!(&[0, 0, 0xff, 0xff], &buf);
286 
287         assert_eq!(
288             s,
289             <String as WireFormat>::decode(&mut Cursor::new(&[0, 0, 0x61, 0x61][..]))
290                 .expect("failed to decode empty string")
291         );
292     }
293 
294     #[test]
string_encode()295     fn string_encode() {
296         let values = [
297             String::from("Google Video"),
298             String::from("网页 图片 资讯更多 »"),
299             String::from("Παγκόσμιος Ιστός"),
300             String::from("Поиск страниц на русском"),
301             String::from("전체서비스"),
302         ];
303 
304         let expected = values.iter().map(|v| {
305             let len = v.as_bytes().len();
306             let mut buf = Vec::with_capacity(len + mem::size_of::<u16>());
307 
308             buf.push(len as u8);
309             buf.push((len >> 8) as u8);
310 
311             buf.extend_from_slice(v.as_bytes());
312 
313             buf
314         });
315 
316         for (val, exp) in values.iter().zip(expected) {
317             let mut buf = vec![0; exp.len()];
318 
319             WireFormat::encode(val, &mut Cursor::new(&mut *buf)).unwrap();
320             assert_eq!(exp, buf);
321         }
322     }
323 
324     #[test]
string_decode()325     fn string_decode() {
326         assert_eq!(
327             String::from("Google Video"),
328             <String as WireFormat>::decode(&mut Cursor::new(
329                 &[
330                     0x0c, 0x00, 0x47, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x20, 0x56, 0x69, 0x64, 0x65,
331                     0x6F,
332                 ][..]
333             ))
334             .unwrap()
335         );
336         assert_eq!(
337             String::from("网页 图片 资讯更多 »"),
338             <String as WireFormat>::decode(&mut Cursor::new(
339                 &[
340                     0x1d, 0x00, 0xE7, 0xBD, 0x91, 0xE9, 0xA1, 0xB5, 0x20, 0xE5, 0x9B, 0xBE, 0xE7,
341                     0x89, 0x87, 0x20, 0xE8, 0xB5, 0x84, 0xE8, 0xAE, 0xAF, 0xE6, 0x9B, 0xB4, 0xE5,
342                     0xA4, 0x9A, 0x20, 0xC2, 0xBB,
343                 ][..]
344             ))
345             .unwrap()
346         );
347         assert_eq!(
348             String::from("Παγκόσμιος Ιστός"),
349             <String as WireFormat>::decode(&mut Cursor::new(
350                 &[
351                     0x1f, 0x00, 0xCE, 0xA0, 0xCE, 0xB1, 0xCE, 0xB3, 0xCE, 0xBA, 0xCF, 0x8C, 0xCF,
352                     0x83, 0xCE, 0xBC, 0xCE, 0xB9, 0xCE, 0xBF, 0xCF, 0x82, 0x20, 0xCE, 0x99, 0xCF,
353                     0x83, 0xCF, 0x84, 0xCF, 0x8C, 0xCF, 0x82,
354                 ][..]
355             ))
356             .unwrap()
357         );
358         assert_eq!(
359             String::from("Поиск страниц на русском"),
360             <String as WireFormat>::decode(&mut Cursor::new(
361                 &[
362                     0x2d, 0x00, 0xD0, 0x9F, 0xD0, 0xBE, 0xD0, 0xB8, 0xD1, 0x81, 0xD0, 0xBA, 0x20,
363                     0xD1, 0x81, 0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xBD, 0xD0, 0xB8, 0xD1,
364                     0x86, 0x20, 0xD0, 0xBD, 0xD0, 0xB0, 0x20, 0xD1, 0x80, 0xD1, 0x83, 0xD1, 0x81,
365                     0xD1, 0x81, 0xD0, 0xBA, 0xD0, 0xBE, 0xD0, 0xBC,
366                 ][..]
367             ))
368             .unwrap()
369         );
370         assert_eq!(
371             String::from("전체서비스"),
372             <String as WireFormat>::decode(&mut Cursor::new(
373                 &[
374                     0x0f, 0x00, 0xEC, 0xA0, 0x84, 0xEC, 0xB2, 0xB4, 0xEC, 0x84, 0x9C, 0xEB, 0xB9,
375                     0x84, 0xEC, 0x8A, 0xA4,
376                 ][..]
377             ))
378             .unwrap()
379         );
380     }
381 
382     #[test]
invalid_string_decode()383     fn invalid_string_decode() {
384         let _ = <String as WireFormat>::decode(&mut Cursor::new(&[
385             0x06, 0x00, 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf,
386         ]))
387         .expect_err("surrogate code point");
388 
389         let _ = <String as WireFormat>::decode(&mut Cursor::new(&[
390             0x05, 0x00, 0xf8, 0x80, 0x80, 0x80, 0xbf,
391         ]))
392         .expect_err("overlong sequence");
393 
394         let _ =
395             <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xf4, 0x90, 0x80, 0x80]))
396                 .expect_err("out of range");
397 
398         let _ =
399             <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0x63, 0x61, 0x66, 0xe9]))
400                 .expect_err("ISO-8859-1");
401 
402         let _ =
403             <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xb0, 0xa1, 0xb0, 0xa2]))
404                 .expect_err("EUC-KR");
405     }
406 
407     #[test]
vector_encode()408     fn vector_encode() {
409         let values: Vec<u32> = vec![291, 18_916, 2_497, 22, 797_162, 2_119_732, 3_213_929_716];
410         let mut expected: Vec<u8> =
411             Vec::with_capacity(values.len() * mem::size_of::<u32>() + mem::size_of::<u16>());
412         expected.push(values.len() as u8);
413         expected.push((values.len() >> 8) as u8);
414 
415         const MASK: u32 = 0xff;
416         for val in &values {
417             expected.push((val & MASK) as u8);
418             expected.push(((val >> 8) & MASK) as u8);
419             expected.push(((val >> 16) & MASK) as u8);
420             expected.push(((val >> 24) & MASK) as u8);
421         }
422 
423         let mut actual: Vec<u8> = vec![0; expected.len()];
424 
425         WireFormat::encode(&values, &mut Cursor::new(&mut *actual))
426             .expect("failed to encode vector");
427         assert_eq!(expected, actual);
428     }
429 
430     #[test]
vector_decode()431     fn vector_decode() {
432         let expected: Vec<u32> = vec![
433             2_498,
434             24,
435             897,
436             4_097_789_579,
437             8_498_119,
438             684_279,
439             961_189_198,
440             7,
441         ];
442         let mut input: Vec<u8> =
443             Vec::with_capacity(expected.len() * mem::size_of::<u32>() + mem::size_of::<u16>());
444         input.push(expected.len() as u8);
445         input.push((expected.len() >> 8) as u8);
446 
447         const MASK: u32 = 0xff;
448         for val in &expected {
449             input.push((val & MASK) as u8);
450             input.push(((val >> 8) & MASK) as u8);
451             input.push(((val >> 16) & MASK) as u8);
452             input.push(((val >> 24) & MASK) as u8);
453         }
454 
455         assert_eq!(
456             expected,
457             <Vec<u32> as WireFormat>::decode(&mut Cursor::new(&*input))
458                 .expect("failed to decode vector")
459         );
460     }
461 
462     #[test]
data_encode()463     fn data_encode() {
464         let values = Data(vec![169, 155, 79, 67, 182, 199, 25, 73, 129, 200]);
465         let mut expected: Vec<u8> =
466             Vec::with_capacity(values.len() * mem::size_of::<u8>() + mem::size_of::<u32>());
467         expected.push(values.len() as u8);
468         expected.push((values.len() >> 8) as u8);
469         expected.push((values.len() >> 16) as u8);
470         expected.push((values.len() >> 24) as u8);
471         expected.extend_from_slice(&values);
472 
473         let mut actual: Vec<u8> = vec![0; expected.len()];
474 
475         WireFormat::encode(&values, &mut Cursor::new(&mut *actual))
476             .expect("failed to encode datar");
477         assert_eq!(expected, actual);
478     }
479 
480     #[test]
data_decode()481     fn data_decode() {
482         let expected = Data(vec![219, 15, 8, 155, 194, 129, 79, 91, 46, 53, 173]);
483         let mut input: Vec<u8> =
484             Vec::with_capacity(expected.len() * mem::size_of::<u8>() + mem::size_of::<u32>());
485         input.push(expected.len() as u8);
486         input.push((expected.len() >> 8) as u8);
487         input.push((expected.len() >> 16) as u8);
488         input.push((expected.len() >> 24) as u8);
489         input.extend_from_slice(&expected);
490 
491         assert_eq!(
492             expected,
493             <Data as WireFormat>::decode(&mut Cursor::new(&mut *input))
494                 .expect("failed to decode data")
495         );
496     }
497 
498     #[test]
error_cases()499     fn error_cases() {
500         // string is too long.
501         let mut long_str = String::with_capacity(std::u16::MAX as usize);
502         while long_str.len() < std::u16::MAX as usize {
503             long_str.push_str("long");
504         }
505         long_str.push_str("!");
506 
507         let count = long_str.len() + mem::size_of::<u16>();
508         let mut buf = vec![0; count];
509 
510         long_str
511             .encode(&mut Cursor::new(&mut *buf))
512             .expect_err("long string");
513 
514         // vector is too long.
515         let mut long_vec: Vec<u32> = Vec::with_capacity(std::u16::MAX as usize);
516         while long_vec.len() < std::u16::MAX as usize {
517             long_vec.push(0x8bad_f00d);
518         }
519         long_vec.push(0x00ba_b10c);
520 
521         let count = long_vec.len() * mem::size_of::<u32>();
522         let mut buf = vec![0; count];
523 
524         WireFormat::encode(&long_vec, &mut Cursor::new(&mut *buf)).expect_err("long vector");
525     }
526 
527     #[derive(Debug, PartialEq, P9WireFormat)]
528     struct Item {
529         a: u64,
530         b: String,
531         c: Vec<u16>,
532         buf: Data,
533     }
534 
535     #[test]
struct_encode()536     fn struct_encode() {
537         let item = Item {
538             a: 0xdead10cc_00bab10c,
539             b: String::from("冻住,不许走!"),
540             c: vec![359, 492, 8891],
541             buf: Data(vec![254, 129, 0, 62, 49, 172]),
542         };
543 
544         let mut expected: Vec<u8> = vec![0x0c, 0xb1, 0xba, 0x00, 0xcc, 0x10, 0xad, 0xde];
545         let strlen = item.b.len() as u16;
546         expected.push(strlen as u8);
547         expected.push((strlen >> 8) as u8);
548         expected.extend_from_slice(item.b.as_bytes());
549 
550         let veclen = item.c.len() as u16;
551         expected.push(veclen as u8);
552         expected.push((veclen >> 8) as u8);
553         for val in &item.c {
554             expected.push(*val as u8);
555             expected.push((val >> 8) as u8);
556         }
557 
558         let buflen = item.buf.len() as u32;
559         expected.push(buflen as u8);
560         expected.push((buflen >> 8) as u8);
561         expected.push((buflen >> 16) as u8);
562         expected.push((buflen >> 24) as u8);
563         expected.extend_from_slice(&item.buf);
564 
565         let mut actual = vec![0; expected.len()];
566 
567         WireFormat::encode(&item, &mut Cursor::new(&mut *actual)).expect("failed to encode item");
568 
569         assert_eq!(expected, actual);
570     }
571 
572     #[test]
struct_decode()573     fn struct_decode() {
574         let expected = Item {
575             a: 0xface_b00c_0404_4b1d,
576             b: String::from("Огонь по готовности!"),
577             c: vec![20067, 32449, 549, 4972, 77, 1987],
578             buf: Data(vec![126, 236, 79, 59, 6, 159]),
579         };
580 
581         let mut input: Vec<u8> = vec![0x1d, 0x4b, 0x04, 0x04, 0x0c, 0xb0, 0xce, 0xfa];
582         let strlen = expected.b.len() as u16;
583         input.push(strlen as u8);
584         input.push((strlen >> 8) as u8);
585         input.extend_from_slice(expected.b.as_bytes());
586 
587         let veclen = expected.c.len() as u16;
588         input.push(veclen as u8);
589         input.push((veclen >> 8) as u8);
590         for val in &expected.c {
591             input.push(*val as u8);
592             input.push((val >> 8) as u8);
593         }
594 
595         let buflen = expected.buf.len() as u32;
596         input.push(buflen as u8);
597         input.push((buflen >> 8) as u8);
598         input.push((buflen >> 16) as u8);
599         input.push((buflen >> 24) as u8);
600         input.extend_from_slice(&expected.buf);
601 
602         let actual: Item =
603             WireFormat::decode(&mut Cursor::new(input)).expect("failed to decode item");
604 
605         assert_eq!(expected, actual);
606     }
607 
608     #[derive(Debug, PartialEq, P9WireFormat)]
609     struct Nested {
610         item: Item,
611         val: Vec<u64>,
612     }
613 
build_encoded_buffer(value: &Nested) -> Vec<u8>614     fn build_encoded_buffer(value: &Nested) -> Vec<u8> {
615         let mut result: Vec<u8> = Vec::new();
616 
617         // encode a
618         result.push(value.item.a as u8);
619         result.push((value.item.a >> 8) as u8);
620         result.push((value.item.a >> 16) as u8);
621         result.push((value.item.a >> 24) as u8);
622         result.push((value.item.a >> 32) as u8);
623         result.push((value.item.a >> 40) as u8);
624         result.push((value.item.a >> 48) as u8);
625         result.push((value.item.a >> 56) as u8);
626 
627         // encode b
628         result.push(value.item.b.len() as u8);
629         result.push((value.item.b.len() >> 8) as u8);
630         result.extend_from_slice(value.item.b.as_bytes());
631 
632         // encode c
633         result.push(value.item.c.len() as u8);
634         result.push((value.item.c.len() >> 8) as u8);
635         for val in &value.item.c {
636             result.push((val & 0xffu16) as u8);
637             result.push(((val >> 8) & 0xffu16) as u8);
638         }
639 
640         // encode buf
641         result.push(value.item.buf.len() as u8);
642         result.push((value.item.buf.len() >> 8) as u8);
643         result.push((value.item.buf.len() >> 16) as u8);
644         result.push((value.item.buf.len() >> 24) as u8);
645         result.extend_from_slice(&value.item.buf);
646 
647         // encode val
648         result.push(value.val.len() as u8);
649         result.push((value.val.len() >> 8) as u8);
650         for val in &value.val {
651             result.push(*val as u8);
652             result.push((val >> 8) as u8);
653             result.push((val >> 16) as u8);
654             result.push((val >> 24) as u8);
655             result.push((val >> 32) as u8);
656             result.push((val >> 40) as u8);
657             result.push((val >> 48) as u8);
658             result.push((val >> 56) as u8);
659         }
660 
661         result
662     }
663 
664     #[test]
nested_encode()665     fn nested_encode() {
666         let value = Nested {
667             item: Item {
668                 a: 0xcafe_d00d_8bad_f00d,
669                 b: String::from("龍が我が敵を喰らう!"),
670                 c: vec![2679, 55_919, 44, 38_819, 792],
671                 buf: Data(vec![129, 55, 200, 93, 7, 68]),
672             },
673             val: vec![1954978, 59, 4519, 15679],
674         };
675 
676         let expected = build_encoded_buffer(&value);
677 
678         let mut actual = vec![0; expected.len()];
679 
680         WireFormat::encode(&value, &mut Cursor::new(&mut *actual)).expect("failed to encode value");
681         assert_eq!(expected, actual);
682     }
683 
684     #[test]
nested_decode()685     fn nested_decode() {
686         let expected = Nested {
687             item: Item {
688                 a: 0x0ff1ce,
689                 b: String::from("龍神の剣を喰らえ!"),
690                 c: vec![21687, 159, 55, 9217, 192],
691                 buf: Data(vec![189, 22, 7, 59, 235]),
692             },
693             val: vec![15679, 8619196, 319746, 123957, 77, 0, 492],
694         };
695 
696         let input = build_encoded_buffer(&expected);
697 
698         assert_eq!(
699             expected,
700             <Nested as WireFormat>::decode(&mut Cursor::new(&*input))
701                 .expect("failed to decode value")
702         );
703     }
704 }
705