1
#![doc(
2
    html_logo_url = "https://raw.githubusercontent.com/sevki/jetstream/main/logo/JetStream.png"
3
)]
4
#![doc(
5
    html_favicon_url = "https://raw.githubusercontent.com/sevki/jetstream/main/logo/JetStream.png"
6
)]
7
#![cfg_attr(docsrs, feature(doc_cfg))]
8
#[cfg(feature = "std")]
9
use std::collections::{BTreeMap, BinaryHeap};
10
// Copyright (c) 2024, Sevki <s@sevki.io>
11
// Copyright 2018 The ChromiumOS Authors
12
// Use of this source code is governed by a BSD-style license that can be
13
// found in the LICENSE file.
14
use std::{
15
    collections::{BTreeSet, VecDeque},
16
    ffi::{CStr, CString, OsStr},
17
    fmt,
18
    io::{self, ErrorKind, Read, Write},
19
    marker::PhantomData,
20
    mem,
21
    ops::{Deref, DerefMut},
22
    string::String,
23
    vec::Vec,
24
};
25

            
26
use bytes::Buf;
27
pub use jetstream_macros::JetStreamWireFormat;
28
use zerocopy::LittleEndian;
29
pub mod wire_format_extensions;
30

            
31
#[cfg(target_arch = "wasm32")]
32
pub mod wasm;
33

            
34
/// A type that can be encoded on the wire using the 9P protocol.
35
#[cfg(not(target_arch = "wasm32"))]
36
pub trait WireFormat: Send {
37
    /// Returns the number of bytes necessary to fully encode `self`.
38
    fn byte_size(&self) -> u32;
39

            
40
    /// Encodes `self` into `writer`.
41
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()>
42
    where
43
        Self: Sized;
44

            
45
    /// Decodes `Self` from `reader`.
46
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self>
47
    where
48
        Self: Sized;
49
}
50

            
51
/// A type that can be encoded on the wire using the 9P protocol.
52
/// WebAssembly doesn't fully support Send, so we don't require it.
53
#[cfg(target_arch = "wasm32")]
54
pub trait WireFormat: std::marker::Sized {
55
    /// Returns the number of bytes necessary to fully encode `self`.
56
    fn byte_size(&self) -> u32;
57

            
58
    /// Encodes `self` into `writer`.
59
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()>;
60

            
61
    /// Decodes `Self` from `reader`.
62
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self>;
63
}
64

            
65
/// A 9P protocol string.
66
///
67
/// The string is always valid UTF-8 and 65535 bytes or less (enforced by `P9String::new()`).
68
///
69
/// It is represented as a C string with a terminating 0 (NUL) character to allow it to be passed
70
/// directly to libc functions.
71
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
72
pub struct P9String {
73
    cstr: CString,
74
}
75

            
76
impl P9String {
77
    pub fn new(string_bytes: impl Into<Vec<u8>>) -> io::Result<Self> {
78
        let string_bytes: Vec<u8> = string_bytes.into();
79

            
80
        if string_bytes.len() > u16::MAX as usize {
81
            return Err(io::Error::new(
82
                ErrorKind::InvalidInput,
83
                "string is too long",
84
            ));
85
        }
86

            
87
        // 9p strings must be valid UTF-8.
88
        let _check_utf8 = std::str::from_utf8(&string_bytes)
89
            .map_err(|e| io::Error::new(ErrorKind::InvalidInput, e))?;
90

            
91
        let cstr = CString::new(string_bytes)
92
            .map_err(|e| io::Error::new(ErrorKind::InvalidInput, e))?;
93

            
94
        Ok(P9String { cstr })
95
    }
96

            
97
    pub fn len(&self) -> usize {
98
        self.cstr.as_bytes().len()
99
    }
100

            
101
    pub fn is_empty(&self) -> bool {
102
        self.cstr.as_bytes().is_empty()
103
    }
104

            
105
    pub fn as_c_str(&self) -> &CStr {
106
        self.cstr.as_c_str()
107
    }
108

            
109
    pub fn as_bytes(&self) -> &[u8] {
110
        self.cstr.as_bytes()
111
    }
112

            
113
    #[cfg(not(target_arch = "wasm32"))]
114
    /// Returns a raw pointer to the string's storage.
115
    ///
116
    /// The string bytes are always followed by a NUL terminator ('\0'), so the pointer can be
117
    /// passed directly to libc functions that expect a C string.
118
    pub fn as_ptr(&self) -> *const libc::c_char {
119
        self.cstr.as_ptr()
120
    }
121

            
122
    #[cfg(target_arch = "wasm32")]
123
    /// Returns a raw pointer to the string's storage.
124
    ///
125
    /// The string bytes are always followed by a NUL terminator ('\0').
126
    /// Note: In WebAssembly, returns a raw pointer but libc is not available.
127
    pub fn as_ptr(&self) -> *const std::os::raw::c_char {
128
        self.cstr.as_ptr()
129
    }
130
}
131

            
132
impl PartialEq<&str> for P9String {
133
    fn eq(&self, other: &&str) -> bool {
134
        self.cstr.as_bytes() == other.as_bytes()
135
    }
136
}
137

            
138
impl TryFrom<&OsStr> for P9String {
139
    type Error = io::Error;
140

            
141
    fn try_from(value: &OsStr) -> io::Result<Self> {
142
        let string_bytes = value.as_encoded_bytes();
143
        Self::new(string_bytes)
144
    }
145
}
146

            
147
// The 9P protocol requires that strings are UTF-8 encoded.  The wire format is a u16
148
// count |N|, encoded in little endian, followed by |N| bytes of UTF-8 data.
149
impl WireFormat for P9String {
150
    fn byte_size(&self) -> u32 {
151
        (mem::size_of::<u16>() + self.len()) as u32
152
    }
153

            
154
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
155
        (self.len() as u16).encode(writer)?;
156
        writer.write_all(self.cstr.as_bytes())
157
    }
158

            
159
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
160
        let len: u16 = WireFormat::decode(reader)?;
161
        let mut string_bytes = vec![0u8; usize::from(len)];
162
        reader.read_exact(&mut string_bytes)?;
163
        Self::new(string_bytes)
164
    }
165
}
166

            
167
// This doesn't really _need_ to be a macro but unfortunately there is no trait bound to
168
// express "can be casted to another type", which means we can't write `T as u8` in a trait
169
// based implementation.  So instead we have this macro, which is implemented for all the
170
// stable unsigned types with the added benefit of not being implemented for the signed
171
// types which are not allowed by the protocol.
172
macro_rules! uint_wire_format_impl {
173
    ($Ty:ty) => {
174
        impl WireFormat for $Ty {
175
72
            fn byte_size(&self) -> u32 {
176
72
                mem::size_of::<$Ty>() as u32
177
72
            }
178

            
179
1146
            fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
180
1146
                writer.write_all(&self.to_le_bytes())
181
1146
            }
182

            
183
1590
            fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
184
1590
                let mut buf = [0; mem::size_of::<$Ty>()];
185
1590
                reader.read_exact(&mut buf)?;
186
                paste::expr! {
187
1590
                    let num: zerocopy::[<$Ty:snake:upper>]<LittleEndian> =  zerocopy::byteorder::[<$Ty:snake:upper>]::from_bytes(buf);
188
1590
                    Ok(num.get())
189
                }
190
1590
            }
191
        }
192
    };
193
}
194
// unsigned integers
195
uint_wire_format_impl!(u16);
196
uint_wire_format_impl!(u32);
197
uint_wire_format_impl!(u64);
198
uint_wire_format_impl!(u128);
199
// signed integers
200
uint_wire_format_impl!(i16);
201
uint_wire_format_impl!(i32);
202
uint_wire_format_impl!(i64);
203
uint_wire_format_impl!(i128);
204

            
205
macro_rules! float_wire_format_impl {
206
    ($Ty:ty) => {
207
        impl WireFormat for $Ty {
208
            fn byte_size(&self) -> u32 {
209
                mem::size_of::<$Ty>() as u32
210
            }
211

            
212
            fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
213
                paste::expr! {
214
                    writer.write_all(&self.to_le_bytes())
215
                }
216
            }
217

            
218
            fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
219
                let mut buf = [0; mem::size_of::<$Ty>()];
220
                reader.read_exact(&mut buf)?;
221
                paste::expr! {
222
                    let num: zerocopy::[<$Ty:snake:upper>]<LittleEndian> =  zerocopy::byteorder::[<$Ty:snake:upper>]::from_bytes(buf);
223
                    Ok(num.get())
224
                }
225
            }
226
        }
227
    };
228
}
229

            
230
float_wire_format_impl!(f32);
231
float_wire_format_impl!(f64);
232

            
233
impl WireFormat for u8 {
234
    fn byte_size(&self) -> u32 {
235
        1
236
    }
237

            
238
472
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
239
472
        writer.write_all(&[*self])
240
472
    }
241

            
242
20
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
243
20
        let mut byte = [0u8; 1];
244
20
        reader.read_exact(&mut byte)?;
245
20
        Ok(byte[0])
246
20
    }
247
}
248

            
249
impl WireFormat for usize {
250
    fn byte_size(&self) -> u32 {
251
        mem::size_of::<usize>() as u32
252
    }
253

            
254
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
255
        writer.write_all(&self.to_le_bytes())
256
    }
257

            
258
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
259
        let mut buf = [0; mem::size_of::<usize>()];
260
        reader.read_exact(&mut buf)?;
261
        Ok(usize::from_le_bytes(buf))
262
    }
263
}
264

            
265
impl WireFormat for isize {
266
    fn byte_size(&self) -> u32 {
267
        mem::size_of::<isize>() as u32
268
    }
269

            
270
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
271
        writer.write_all(&self.to_le_bytes())
272
    }
273

            
274
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
275
        let mut buf = [0; mem::size_of::<isize>()];
276
        reader.read_exact(&mut buf)?;
277
        Ok(isize::from_le_bytes(buf))
278
    }
279
}
280

            
281
// The 9P protocol requires that strings are UTF-8 encoded.  The wire format is a u16
282
// count |N|, encoded in little endian, followed by |N| bytes of UTF-8 data.
283
impl WireFormat for String {
284
1416
    fn byte_size(&self) -> u32 {
285
1416
        (mem::size_of::<u16>() + self.len()) as u32
286
1416
    }
287

            
288
232
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
289
232
        if self.len() > u16::MAX as usize {
290
            return Err(io::Error::new(
291
                ErrorKind::InvalidInput,
292
                "string is too long",
293
            ));
294
232
        }
295

            
296
232
        (self.len() as u16).encode(writer)?;
297
232
        writer.write_all(self.as_bytes())
298
232
    }
299

            
300
234
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
301
234
        let len: u16 = WireFormat::decode(reader)?;
302
234
        let mut result = String::with_capacity(len as usize);
303
234
        reader.take(len as u64).read_to_string(&mut result)?;
304
234
        Ok(result)
305
234
    }
306
}
307

            
308
// The wire format for repeated types is similar to that of strings: a little endian
309
// encoded u16 |N|, followed by |N| instances of the given type.
310
impl<T: WireFormat> WireFormat for Vec<T> {
311
    fn byte_size(&self) -> u32 {
312
        mem::size_of::<u16>() as u32
313
            + self.iter().map(|elem| elem.byte_size()).sum::<u32>()
314
    }
315

            
316
4
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
317
4
        if self.len() > u16::MAX as usize {
318
            return Err(std::io::Error::new(
319
                std::io::ErrorKind::InvalidInput,
320
                "too many elements in vector",
321
            ));
322
4
        }
323

            
324
4
        (self.len() as u16).encode(writer)?;
325
22
        for elem in self {
326
18
            elem.encode(writer)?;
327
        }
328

            
329
4
        Ok(())
330
4
    }
331

            
332
2
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
333
2
        let len: u16 = WireFormat::decode(reader)?;
334
2
        let mut result = Vec::with_capacity(len as usize);
335

            
336
2
        for _ in 0..len {
337
10
            result.push(WireFormat::decode(reader)?);
338
        }
339

            
340
2
        Ok(result)
341
2
    }
342
}
343

            
344
/// A type that encodes an arbitrary number of bytes of data.  Typically used for Rread
345
/// Twrite messages.  This differs from a `Vec<u8>` in that it encodes the number of bytes
346
/// using a `u32` instead of a `u16`.
347
#[derive(PartialEq, Eq, Clone)]
348
#[repr(transparent)]
349
#[cfg_attr(feature = "testing", derive(serde::Serialize, serde::Deserialize))]
350
pub struct Data(pub Vec<u8>);
351

            
352
// The maximum length of a data buffer that we support.  In practice the server's max message
353
// size should prevent us from reading too much data so this check is mainly to ensure a
354
// malicious client cannot trick us into allocating massive amounts of memory.
355
const MAX_DATA_LENGTH: u32 = 32 * 1024 * 1024;
356

            
357
impl fmt::Debug for Data {
358
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
359
        // There may be a lot of data and we don't want to spew it all out in a trace.  Instead
360
        // just print out the number of bytes in the buffer.
361
        write!(f, "Data({} bytes)", self.len())
362
    }
363
}
364

            
365
// Implement Deref and DerefMut so that we don't have to use self.0 everywhere.
366
impl Deref for Data {
367
    type Target = Vec<u8>;
368

            
369
    fn deref(&self) -> &Self::Target {
370
        &self.0
371
    }
372
}
373
impl DerefMut for Data {
374
    fn deref_mut(&mut self) -> &mut Self::Target {
375
        &mut self.0
376
    }
377
}
378

            
379
// Same as Vec<u8> except that it encodes the length as a u32 instead of a u16.
380
impl WireFormat for Data {
381
    fn byte_size(&self) -> u32 {
382
        mem::size_of::<u32>() as u32
383
            + self.iter().map(|elem| elem.byte_size()).sum::<u32>()
384
    }
385

            
386
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
387
        if self.len() > u32::MAX as usize {
388
            return Err(std::io::Error::new(
389
                std::io::ErrorKind::InvalidInput,
390
                "data is too large",
391
            ));
392
        }
393
        (self.len() as u32).encode(writer)?;
394
        writer.write_all(self)
395
    }
396

            
397
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
398
        let len: u32 = WireFormat::decode(reader)?;
399
        if len > MAX_DATA_LENGTH {
400
            return Err(std::io::Error::new(
401
                std::io::ErrorKind::InvalidData,
402
                format!("data length ({} bytes) is too large", len),
403
            ));
404
        }
405

            
406
        let mut buf = Vec::with_capacity(len as usize);
407
        reader.take(len as u64).read_to_end(&mut buf)?;
408

            
409
        if buf.len() == len as usize {
410
            Ok(Data(buf))
411
        } else {
412
            Err(io::Error::new(
413
                std::io::ErrorKind::UnexpectedEof,
414
                format!(
415
                    "unexpected end of data: want: {} bytes, got: {} bytes",
416
                    len,
417
                    buf.len()
418
                ),
419
            ))
420
        }
421
    }
422
}
423

            
424
impl<T> WireFormat for Option<T>
425
where
426
    T: WireFormat,
427
{
428
    fn byte_size(&self) -> u32 {
429
        1 + match self {
430
            None => 0,
431
            Some(value) => value.byte_size(),
432
        }
433
    }
434

            
435
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
436
        match self {
437
            None => WireFormat::encode(&0u8, writer),
438
            Some(value) => {
439
                WireFormat::encode(&1u8, writer)?;
440
                WireFormat::encode(value, writer)
441
            }
442
        }
443
    }
444

            
445
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
446
        let tag: u8 = WireFormat::decode(reader)?;
447
        match tag {
448
            0 => Ok(None),
449
            1 => Ok(Some(WireFormat::decode(reader)?)),
450
            _ => Err(io::Error::new(
451
                io::ErrorKind::InvalidData,
452
                format!("Invalid Option tag: {}", tag),
453
            )),
454
        }
455
    }
456
}
457

            
458
impl WireFormat for () {
459
9
    fn byte_size(&self) -> u32 {
460
9
        0
461
9
    }
462

            
463
2
    fn encode<W: Write>(&self, _writer: &mut W) -> io::Result<()> {
464
2
        Ok(())
465
2
    }
466

            
467
2
    fn decode<R: Read>(_reader: &mut R) -> io::Result<Self> {
468
2
        Ok(())
469
2
    }
470
}
471

            
472
impl WireFormat for bool {
473
    fn byte_size(&self) -> u32 {
474
        1
475
    }
476

            
477
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
478
        writer.write_all(&[*self as u8])
479
    }
480

            
481
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
482
        let mut byte = [0u8; 1];
483
        reader.read_exact(&mut byte)?;
484
        match byte[0] {
485
            0 => Ok(false),
486
            1 => Ok(true),
487
            _ => Err(io::Error::new(
488
                io::ErrorKind::InvalidData,
489
                "invalid byte for bool",
490
            )),
491
        }
492
    }
493
}
494

            
495
impl io::Read for Data {
496
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
497
        self.0.reader().read(buf)
498
    }
499
}
500

            
501
#[repr(transparent)]
502
pub struct Wrapped<T, I>(pub T, PhantomData<I>);
503

            
504
impl<T, I> Wrapped<T, I> {
505
    pub fn new(value: T) -> Self {
506
        Wrapped(value, PhantomData)
507
    }
508
}
509

            
510
#[cfg(not(target_arch = "wasm32"))]
511
impl<T, I> WireFormat for Wrapped<T, I>
512
where
513
    T: Send + std::convert::AsRef<I>,
514
    I: WireFormat + std::convert::Into<T>,
515
{
516
    fn byte_size(&self) -> u32 {
517
        AsRef::<I>::as_ref(&self.0).byte_size()
518
    }
519

            
520
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
521
        AsRef::<I>::as_ref(&self.0).encode(writer)
522
    }
523

            
524
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
525
        let inner = I::decode(reader)?;
526
        Ok(Wrapped(inner.into(), PhantomData))
527
    }
528
}
529

            
530
#[cfg(target_arch = "wasm32")]
531
impl<T, I> WireFormat for Wrapped<T, I>
532
where
533
    T: std::convert::AsRef<I>,
534
    I: WireFormat + std::convert::Into<T>,
535
{
536
    fn byte_size(&self) -> u32 {
537
        AsRef::<I>::as_ref(&self.0).byte_size()
538
    }
539

            
540
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> {
541
        AsRef::<I>::as_ref(&self.0).encode(writer)
542
    }
543

            
544
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self> {
545
        let inner = I::decode(reader)?;
546
        Ok(Wrapped(inner.into(), PhantomData))
547
    }
548
}
549

            
550
impl<T: WireFormat> WireFormat for Box<T> {
551
    fn byte_size(&self) -> u32 {
552
        (**self).byte_size()
553
    }
554

            
555
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()>
556
    where
557
        Self: Sized,
558
    {
559
        (**self).encode(writer)
560
    }
561

            
562
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self>
563
    where
564
        Self: Sized,
565
    {
566
        let inner = T::decode(reader)?;
567
        Ok(Box::new(inner))
568
    }
569
}
570

            
571
#[cfg(feature = "std")]
572
impl<K: WireFormat + Send + Sync + Ord, V: WireFormat + Send + Sync> WireFormat
573
    for BTreeMap<K, V>
574
{
575
    fn byte_size(&self) -> u32 {
576
        self.iter()
577
            .fold(0, |acc, (k, v)| acc + k.byte_size() + v.byte_size())
578
            + 2
579
    }
580

            
581
    fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<()>
582
    where
583
        Self: Sized,
584
    {
585
        if self.len() > u16::MAX as usize {
586
            return Err(io::Error::new(
587
                io::ErrorKind::InvalidInput,
588
                "Map too large",
589
            ));
590
        }
591
        let len = self.len() as u16;
592
        len.encode(writer)?;
593
        for (k, v) in self {
594
            k.encode(writer)?;
595
            v.encode(writer)?;
596
        }
597
        Ok(())
598
    }
599

            
600
    fn decode<R: io::Read>(reader: &mut R) -> io::Result<Self>
601
    where
602
        Self: Sized,
603
    {
604
        let len: u16 = WireFormat::decode(reader)?;
605
        let mut map = BTreeMap::new();
606
        for _ in 0..len {
607
            let k = K::decode(reader)?;
608
            let v = V::decode(reader)?;
609
            map.insert(k, v);
610
        }
611
        Ok(map)
612
    }
613
}
614

            
615
#[cfg(feature = "std")]
616
impl<V: WireFormat + Send + Sync + Ord> WireFormat for BinaryHeap<V> {
617
    fn byte_size(&self) -> u32 {
618
        self.as_slice()
619
            .iter()
620
            .fold(0, |acc, elem| acc + elem.byte_size())
621
            + 2
622
    }
623

            
624
    fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<()>
625
    where
626
        Self: Sized,
627
    {
628
        if self.len() > u16::MAX as usize {
629
            return Err(io::Error::new(
630
                io::ErrorKind::InvalidInput,
631
                "Map too large",
632
            ));
633
        }
634
        let len = self.len() as u16;
635
        len.encode(writer)?;
636
        for elem in self {
637
            elem.encode(writer)?;
638
        }
639
        Ok(())
640
    }
641

            
642
    fn decode<R: io::Read>(reader: &mut R) -> io::Result<Self>
643
    where
644
        Self: Sized,
645
    {
646
        let len: u16 = WireFormat::decode(reader)?;
647
        let mut heap = BinaryHeap::new();
648
        for _ in 0..len {
649
            let elem = V::decode(reader)?;
650
            heap.push(elem);
651
        }
652
        Ok(heap)
653
    }
654
}
655

            
656
impl<V: WireFormat + Send + Sync + Ord> WireFormat for VecDeque<V> {
657
    fn byte_size(&self) -> u32 {
658
        self.iter().fold(0, |acc, elem| acc + elem.byte_size()) + 2
659
    }
660

            
661
    fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<()>
662
    where
663
        Self: Sized,
664
    {
665
        if self.len() > u16::MAX as usize {
666
            return Err(io::Error::new(
667
                io::ErrorKind::InvalidInput,
668
                "Map too large",
669
            ));
670
        }
671
        let len = self.len() as u16;
672
        len.encode(writer)?;
673
        for elem in self {
674
            elem.encode(writer)?;
675
        }
676
        Ok(())
677
    }
678

            
679
    fn decode<R: io::Read>(reader: &mut R) -> io::Result<Self>
680
    where
681
        Self: Sized,
682
    {
683
        let len: u16 = WireFormat::decode(reader)?;
684
        let mut deque = VecDeque::with_capacity(len as usize);
685
        for _ in 0..len {
686
            let elem = V::decode(reader)?;
687
            deque.push_back(elem);
688
        }
689
        Ok(deque)
690
    }
691
}
692

            
693
impl<V: WireFormat + Send + Sync + Ord> WireFormat for BTreeSet<V> {
694
    fn byte_size(&self) -> u32 {
695
        self.iter().fold(0, |acc, elem| acc + elem.byte_size()) + 2
696
    }
697

            
698
    fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<()>
699
    where
700
        Self: Sized,
701
    {
702
        if self.len() > u16::MAX as usize {
703
            return Err(io::Error::new(
704
                io::ErrorKind::InvalidInput,
705
                "Map too large",
706
            ));
707
        }
708
        let len = self.len() as u16;
709
        len.encode(writer)?;
710
        for elem in self {
711
            elem.encode(writer)?;
712
        }
713
        Ok(())
714
    }
715

            
716
    fn decode<R: io::Read>(reader: &mut R) -> io::Result<Self>
717
    where
718
        Self: Sized,
719
    {
720
        let len: u16 = WireFormat::decode(reader)?;
721
        let mut set = BTreeSet::new();
722
        for _ in 0..len {
723
            let elem = V::decode(reader)?;
724
            set.insert(elem);
725
        }
726
        Ok(set)
727
    }
728
}
729

            
730
impl<T: WireFormat> WireFormat for PhantomData<T> {
731
    fn byte_size(&self) -> u32 {
732
        0
733
    }
734

            
735
    fn encode<W: io::Write>(&self, _writer: &mut W) -> io::Result<()>
736
    where
737
        Self: Sized,
738
    {
739
        Ok(())
740
    }
741

            
742
    fn decode<R: io::Read>(_reader: &mut R) -> io::Result<Self>
743
    where
744
        Self: Sized,
745
    {
746
        Ok(PhantomData)
747
    }
748
}
749

            
750
impl WireFormat for url::Url {
751
    fn byte_size(&self) -> u32 {
752
        self.to_string().byte_size()
753
    }
754

            
755
    fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()>
756
    where
757
        Self: Sized,
758
    {
759
        self.to_string().encode(writer)
760
    }
761

            
762
    fn decode<R: Read>(reader: &mut R) -> io::Result<Self>
763
    where
764
        Self: Sized,
765
    {
766
        let string = String::decode(reader)?;
767
        url::Url::parse(&string)
768
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
769
    }
770
}