Skip to main content

mln_wire/
lib.rs

1//! Port-only: a compact binary encoding for the values that cross between
2//! wasm instances (`mln_renderer`'s `tile/worker_codec`).
3//!
4//! A [`Wire`] type writes itself to a byte vector and reads itself from a
5//! [`Reader`] over a slice. Both are concrete, so each type compiles to one
6//! write function and one read function, without the visitors and error
7//! plumbing a serde format compiles for each type. The encoding is
8//! postcard's: unsigned integers as LEB128 varints, signed ones zigzagged
9//! first, floats as their little-endian bytes, a sequence as its length and
10//! its items, an `Option` as a byte 0 or 1, a struct as its fields in order
11//! and an enum as its variant index and then its fields.
12//!
13//! `#[derive(Wire)]` writes the impl for a struct or an enum
14//! ([`mln_wire_derive`]).
15//!
16//! A value that needs more than its bytes to cross, such as the registry
17//! that a name resolves against, gets it from the [`Context`] that the
18//! writer or reader was made with.
19
20extern crate self as mln_wire;
21
22use std::any::{Any, TypeId};
23use std::collections::{BTreeMap, BTreeSet};
24use std::fmt;
25use std::sync::Arc;
26use std::time::Duration;
27
28pub use mln_wire_derive::Wire;
29
30/// What values need beyond their bytes to cross: the tables of the values
31/// that crossed before, the registry that names resolve against. A value
32/// asks its writer or reader for the part it needs by the part's type
33/// ([`Writer::context`], [`Reader::context`]).
34///
35/// The parts' types belong to the crates that use them, which this crate
36/// can't name, and the writer and reader are concrete types, since trait
37/// objects write and read themselves through them. So a context gives out
38/// its parts by type, and [`Request`] is the one place that erases them.
39///
40/// Contexts combine as tuples, which ask each member in turn.
41pub trait Context {
42    /// Gives `request` the part it asks for, if this context has it.
43    fn provide<'a>(&'a mut self, request: &mut Request<'a>);
44}
45
46/// A request for the part of a [`Context`] of one type.
47pub struct Request<'a> {
48    wanted: TypeId,
49    exclusive: bool,
50    found: Option<Part<'a>>,
51}
52
53enum Part<'a> {
54    Shared(&'a dyn Any),
55    Exclusive(&'a mut dyn Any),
56}
57
58impl<'a> Request<'a> {
59    fn new<T: Any>(exclusive: bool) -> Self {
60        Request { wanted: TypeId::of::<T>(), exclusive, found: None }
61    }
62
63    /// Gives `part`, if the request is for a `T` it can share.
64    pub fn give<T: Any>(&mut self, part: &'a T) -> &mut Self {
65        if self.found.is_none() && !self.exclusive && self.wanted == TypeId::of::<T>() {
66            self.found = Some(Part::Shared(part));
67        }
68        self
69    }
70
71    /// Gives `part`, if the request is for a `T`.
72    pub fn give_mut<T: Any>(&mut self, part: &'a mut T) -> &mut Self {
73        if self.found.is_none() && self.wanted == TypeId::of::<T>() {
74            self.found = Some(Part::Exclusive(part));
75        }
76        self
77    }
78
79    fn shared<T: Any>(self) -> Option<&'a T> {
80        match self.found? {
81            Part::Shared(part) => part.downcast_ref(),
82            Part::Exclusive(part) => part.downcast_ref(),
83        }
84    }
85
86    fn exclusive<T: Any>(self) -> Option<&'a mut T> {
87        match self.found? {
88            Part::Shared(_) => None,
89            Part::Exclusive(part) => part.downcast_mut(),
90        }
91    }
92}
93
94/// The part of `cx` of type `T`.
95fn part<'a, T: Any>(cx: Option<&'a mut (dyn Context + '_)>) -> Option<&'a T> {
96    let mut request = Request::new::<T>(false);
97    cx?.provide(&mut request);
98    request.shared()
99}
100
101/// The part of `cx` of type `T`, to change.
102fn part_mut<'a, T: Any>(cx: Option<&'a mut (dyn Context + '_)>) -> Option<&'a mut T> {
103    let mut request = Request::new::<T>(true);
104    cx?.provide(&mut request);
105    request.exclusive()
106}
107
108/// No parts.
109impl Context for () {
110    fn provide<'a>(&'a mut self, _: &mut Request<'a>) {}
111}
112
113impl<C: Context + ?Sized> Context for &mut C {
114    fn provide<'a>(&'a mut self, request: &mut Request<'a>) {
115        (**self).provide(request);
116    }
117}
118
119impl<A: Context, B: Context> Context for (A, B) {
120    fn provide<'a>(&'a mut self, request: &mut Request<'a>) {
121        self.0.provide(request);
122        self.1.provide(request);
123    }
124}
125
126impl<A: Context, B: Context, C: Context> Context for (A, B, C) {
127    fn provide<'a>(&'a mut self, request: &mut Request<'a>) {
128        self.0.provide(request);
129        self.1.provide(request);
130        self.2.provide(request);
131    }
132}
133
134/// Where values are written: bytes, the first value that couldn't be, and
135/// the context they are written in.
136#[derive(Default)]
137pub struct Writer<'cx> {
138    bytes: Vec<u8>,
139    error: Option<String>,
140    context: Option<&'cx mut (dyn Context + 'cx)>,
141}
142
143impl Writer<'_> {
144    #[must_use]
145    pub fn new() -> Self {
146        Writer::default()
147    }
148
149    #[must_use]
150    pub fn with_capacity(capacity: usize) -> Self {
151        Writer { bytes: Vec::with_capacity(capacity), error: None, context: None }
152    }
153
154    /// A writer that appends to `bytes`.
155    #[must_use]
156    pub fn from_vec(bytes: Vec<u8>) -> Self {
157        Writer { bytes, error: None, context: None }
158    }
159
160    /// This writer, writing in `context`.
161    #[must_use]
162    pub fn with_context<'c>(self, context: &'c mut (dyn Context + 'c)) -> Writer<'c> {
163        Writer { bytes: self.bytes, error: self.error, context: Some(context) }
164    }
165
166    /// The context's part of type `T`, if it has one.
167    pub fn context<T: Any>(&mut self) -> Option<&T> {
168        part(self.context.as_deref_mut())
169    }
170
171    /// The context's part of type `T`, to change, if it has one.
172    pub fn context_mut<T: Any>(&mut self) -> Option<&mut T> {
173        part_mut(self.context.as_deref_mut())
174    }
175
176    #[inline]
177    pub fn push(&mut self, byte: u8) {
178        self.bytes.push(byte);
179    }
180
181    #[inline]
182    pub fn extend_from_slice(&mut self, bytes: &[u8]) {
183        self.bytes.extend_from_slice(bytes);
184    }
185
186    /// Records that a value can't be written; the first such error is what
187    /// [`Writer::finish`] returns.
188    #[cold]
189    pub fn fail(&mut self, error: String) {
190        self.error.get_or_insert(error);
191    }
192
193    /// The bytes written, or why a value couldn't be.
194    pub fn finish(self) -> Result<Vec<u8>, String> {
195        match self.error {
196            None => Ok(self.bytes),
197            Some(error) => Err(error),
198        }
199    }
200}
201
202/// Why a value couldn't be read.
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204pub struct Error(&'static str);
205
206impl fmt::Display for Error {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.write_str(self.0)
209    }
210}
211
212impl std::error::Error for Error {}
213
214/// A value that crosses between wasm instances.
215///
216/// `read` returns `None` when the value can't be read, after it records why
217/// in the reader ([`Reader::fail`]): an `Option` takes less code to pass up
218/// through the reads of a value's parts than a `Result` does.
219pub trait Wire: Sized {
220    fn write(&self, w: &mut Writer);
221    fn read(r: &mut Reader<'_>) -> Option<Self>;
222}
223
224/// Reads values from the start of a slice, in a context, and keeps why one
225/// couldn't be.
226pub struct Reader<'a> {
227    bytes: &'a [u8],
228    error: Option<&'static str>,
229    context: Option<&'a mut (dyn Context + 'a)>,
230}
231
232const END: &str = "unexpected end of input";
233
234impl<'a> Reader<'a> {
235    #[must_use]
236    pub fn new(bytes: &'a [u8]) -> Self {
237        Reader { bytes, error: None, context: None }
238    }
239
240    /// This reader, reading in `context`.
241    #[must_use]
242    pub fn with_context(self, context: &'a mut (dyn Context + 'a)) -> Self {
243        Reader { context: Some(context), ..self }
244    }
245
246    /// The context's part of type `T`, if it has one.
247    pub fn context<T: Any>(&mut self) -> Option<&T> {
248        part(self.context.as_deref_mut())
249    }
250
251    /// The context's part of type `T`, to change, if it has one.
252    pub fn context_mut<T: Any>(&mut self) -> Option<&mut T> {
253        part_mut(self.context.as_deref_mut())
254    }
255
256    /// The bytes not read yet.
257    #[must_use]
258    pub fn rest(&self) -> &'a [u8] {
259        self.bytes
260    }
261
262    /// Records why a value can't be read, and returns `None` for the read to
263    /// return.
264    #[cold]
265    pub fn fail<T>(&mut self, message: &'static str) -> Option<T> {
266        self.error.get_or_insert(message);
267        None
268    }
269
270    /// Why a read returned `None`.
271    #[must_use]
272    pub fn error(&self) -> Error {
273        Error(self.error.unwrap_or("malformed"))
274    }
275
276    #[inline]
277    pub fn byte(&mut self) -> Option<u8> {
278        match self.bytes.split_first() {
279            Some((&byte, rest)) => {
280                self.bytes = rest;
281                Some(byte)
282            }
283            None => self.fail(END),
284        }
285    }
286
287    /// The next `n` bytes.
288    pub fn take(&mut self, n: usize) -> Option<&'a [u8]> {
289        if n > self.bytes.len() {
290            return self.fail(END);
291        }
292        let (taken, rest) = self.bytes.split_at(n);
293        self.bytes = rest;
294        Some(taken)
295    }
296
297    fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
298        match self.bytes.split_first_chunk::<N>() {
299            Some((taken, rest)) => {
300                self.bytes = rest;
301                Some(*taken)
302            }
303            None => self.fail(END),
304        }
305    }
306
307    /// A varint.
308    #[inline(never)]
309    pub fn varint(&mut self) -> Option<u64> {
310        let mut value = 0u64;
311        for shift in (0..64).step_by(7) {
312            let byte = self.byte()?;
313            // The tenth byte holds the one bit left of a `u64`.
314            if shift == 63 && byte > 1 {
315                return self.fail("varint too long");
316            }
317            value |= u64::from(byte & 0x7f) << shift;
318            if byte & 0x80 == 0 {
319                return Some(value);
320            }
321        }
322        self.fail("varint too long")
323    }
324
325    /// An enum's variant index.
326    pub fn tag(&mut self) -> Option<u32> {
327        let tag = self.varint()?;
328        u32::try_from(tag).ok().or_else(|| self.fail_tag())
329    }
330
331    /// Records an enum variant index the enum doesn't have.
332    #[cold]
333    pub fn fail_tag<T>(&mut self) -> Option<T> {
334        self.fail("unknown variant")
335    }
336
337    /// A sequence's length.
338    pub fn length(&mut self) -> Option<usize> {
339        let len = self.varint()?;
340        usize::try_from(len).ok().or_else(|| self.fail("length too large"))
341    }
342}
343
344/// Reads a `T` into `slot`, dropping what it held. Not inlined, so that a
345/// struct of many fields (`#[wire(default)]`) calls it once per field rather
346/// than holding each field's read, move and drop.
347#[inline(never)]
348pub fn read_into<T: Wire>(slot: &mut T, r: &mut Reader<'_>) -> Option<()> {
349    *slot = T::read(r)?;
350    Some(())
351}
352
353/// Writes a varint.
354#[inline(never)]
355pub fn write_varint(w: &mut Writer, mut value: u64) {
356    while value >= 0x80 {
357        w.push((value as u8) | 0x80);
358        value >>= 7;
359    }
360    w.push(value as u8);
361}
362
363/// Writes an enum's variant index.
364#[inline]
365pub fn write_tag(w: &mut Writer, tag: u32) {
366    if tag < 0x80 {
367        w.push(tag as u8);
368    } else {
369        write_varint(w, u64::from(tag));
370    }
371}
372
373fn write_len(w: &mut Writer, len: usize) {
374    write_varint(w, len as u64);
375}
376
377/// `value` encoded, or why it can't be.
378pub fn to_vec<T: Wire>(value: &T) -> Result<Vec<u8>, String> {
379    let mut w = Writer::new();
380    value.write(&mut w);
381    w.finish()
382}
383
384/// `value` encoded in `context`, or why it can't be.
385pub fn to_vec_in<T: Wire>(value: &T, mut context: impl Context) -> Result<Vec<u8>, String> {
386    let mut w = Writer::new().with_context(&mut context);
387    value.write(&mut w);
388    w.finish()
389}
390
391/// The value that fills `bytes`.
392pub fn from_slice<T: Wire>(bytes: &[u8]) -> Result<T, Error> {
393    from_slice_in(bytes, ())
394}
395
396/// The value that fills `bytes`, read in `context`.
397pub fn from_slice_in<T: Wire>(bytes: &[u8], mut context: impl Context) -> Result<T, Error> {
398    let mut r = Reader::new(bytes).with_context(&mut context);
399    match T::read(&mut r) {
400        Some(_) if !r.rest().is_empty() => Err(Error("bytes after the end")),
401        Some(value) => Ok(value),
402        None => Err(r.error()),
403    }
404}
405
406impl Wire for u8 {
407    fn write(&self, w: &mut Writer) {
408        w.push(*self);
409    }
410    fn read(r: &mut Reader<'_>) -> Option<Self> {
411        r.byte()
412    }
413}
414
415impl Wire for i8 {
416    fn write(&self, w: &mut Writer) {
417        w.push(*self as u8);
418    }
419    fn read(r: &mut Reader<'_>) -> Option<Self> {
420        Some(r.byte()? as i8)
421    }
422}
423
424impl Wire for bool {
425    fn write(&self, w: &mut Writer) {
426        w.push(u8::from(*self));
427    }
428    fn read(r: &mut Reader<'_>) -> Option<Self> {
429        match r.byte()? {
430            0 => Some(false),
431            1 => Some(true),
432            _ => r.fail("invalid bool"),
433        }
434    }
435}
436
437macro_rules! unsigned {
438    ($($t:ty: $to_u64:expr),+) => {$(
439        impl Wire for $t {
440            fn write(&self, w: &mut Writer) {
441                write_varint(w, $to_u64(*self));
442            }
443            fn read(r: &mut Reader<'_>) -> Option<Self> {
444                let value = r.varint()?;
445                <$t>::try_from(value).ok().or_else(|| r.fail("integer out of range"))
446            }
447        }
448    )+};
449}
450unsigned!(u16: u64::from, u32: u64::from, u64: std::convert::identity, usize: |value: usize| value as u64);
451
452macro_rules! signed {
453    ($($t:ty: $to_i64:expr),+) => {$(
454        impl Wire for $t {
455            fn write(&self, w: &mut Writer) {
456                let value: i64 = $to_i64(*self);
457                write_varint(w, ((value << 1) ^ (value >> 63)) as u64);
458            }
459            fn read(r: &mut Reader<'_>) -> Option<Self> {
460                let value = r.varint()?;
461                let value = ((value >> 1) as i64) ^ -((value & 1) as i64);
462                <$t>::try_from(value).ok().or_else(|| r.fail("integer out of range"))
463            }
464        }
465    )+};
466}
467signed!(i16: i64::from, i32: i64::from, i64: std::convert::identity, isize: |value: isize| value as i64);
468
469macro_rules! non_zero {
470    ($($t:ty),+) => {$(
471        /// As the integer, which can't be zero.
472        impl Wire for std::num::NonZero<$t> {
473            fn write(&self, w: &mut Writer) {
474                self.get().write(w);
475            }
476            fn read(r: &mut Reader<'_>) -> Option<Self> {
477                let value = <$t>::read(r)?;
478                Self::new(value).or_else(|| r.fail("zero for a non-zero integer"))
479            }
480        }
481    )+};
482}
483non_zero!(u8, u16, u32, u64, usize);
484
485impl Wire for f32 {
486    fn write(&self, w: &mut Writer) {
487        w.extend_from_slice(&self.to_le_bytes());
488    }
489    fn read(r: &mut Reader<'_>) -> Option<Self> {
490        Some(f32::from_le_bytes(r.array()?))
491    }
492}
493
494impl Wire for f64 {
495    fn write(&self, w: &mut Writer) {
496        w.extend_from_slice(&self.to_le_bytes());
497    }
498    fn read(r: &mut Reader<'_>) -> Option<Self> {
499        Some(f64::from_le_bytes(r.array()?))
500    }
501}
502
503impl Wire for char {
504    fn write(&self, w: &mut Writer) {
505        write_varint(w, u64::from(u32::from(*self)));
506    }
507    fn read(r: &mut Reader<'_>) -> Option<Self> {
508        let value = r.varint()?;
509        u32::try_from(value).ok().and_then(char::from_u32).or_else(|| r.fail("invalid char"))
510    }
511}
512
513impl Wire for () {
514    fn write(&self, _: &mut Writer) {}
515    fn read(_: &mut Reader<'_>) -> Option<Self> {
516        Some(())
517    }
518}
519
520impl<T: ?Sized> Wire for std::marker::PhantomData<T> {
521    fn write(&self, _: &mut Writer) {}
522    fn read(_: &mut Reader<'_>) -> Option<Self> {
523        Some(std::marker::PhantomData)
524    }
525}
526
527/// Writes a string.
528pub fn write_str(w: &mut Writer, value: &str) {
529    write_len(w, value.len());
530    w.extend_from_slice(value.as_bytes());
531}
532
533/// Reads a string, borrowed from the input.
534pub fn read_str<'a>(r: &mut Reader<'a>) -> Option<&'a str> {
535    let len = r.length()?;
536    let bytes = r.take(len)?;
537    std::str::from_utf8(bytes).ok().or_else(|| r.fail("invalid UTF-8"))
538}
539
540impl Wire for String {
541    fn write(&self, w: &mut Writer) {
542        write_str(w, self);
543    }
544    fn read(r: &mut Reader<'_>) -> Option<Self> {
545        read_str(r).map(str::to_owned)
546    }
547}
548
549impl Wire for Box<str> {
550    fn write(&self, w: &mut Writer) {
551        write_str(w, self);
552    }
553    fn read(r: &mut Reader<'_>) -> Option<Self> {
554        read_str(r).map(Box::from)
555    }
556}
557
558impl Wire for Arc<str> {
559    fn write(&self, w: &mut Writer) {
560        write_str(w, self);
561    }
562    fn read(r: &mut Reader<'_>) -> Option<Self> {
563        read_str(r).map(Arc::from)
564    }
565}
566
567/// Writes a sequence's length and its items.
568pub fn write_seq<'a, T: Wire + 'a>(w: &mut Writer, items: &'a [T]) {
569    write_len(w, items.len());
570    for item in items {
571        item.write(w);
572    }
573}
574
575/// Reads a sequence's length and its items.
576pub fn read_seq<T: Wire>(r: &mut Reader<'_>) -> Option<Vec<T>> {
577    let len = r.length()?;
578    // A malformed length doesn't reserve more than the input could hold.
579    let mut items = Vec::with_capacity(len.min(r.rest().len()));
580    for _ in 0..len {
581        items.push(T::read(r)?);
582    }
583    Some(items)
584}
585
586impl<T: Wire> Wire for Vec<T> {
587    fn write(&self, w: &mut Writer) {
588        write_seq(w, self);
589    }
590    fn read(r: &mut Reader<'_>) -> Option<Self> {
591        read_seq(r)
592    }
593}
594
595impl<T: Wire> Wire for Box<[T]> {
596    fn write(&self, w: &mut Writer) {
597        write_seq(w, self);
598    }
599    fn read(r: &mut Reader<'_>) -> Option<Self> {
600        read_seq(r).map(Vec::into_boxed_slice)
601    }
602}
603
604impl<T: Wire> Wire for Box<T> {
605    fn write(&self, w: &mut Writer) {
606        (**self).write(w);
607    }
608    fn read(r: &mut Reader<'_>) -> Option<Self> {
609        T::read(r).map(Box::new)
610    }
611}
612
613/// In full: values that cross once and then by key opt in with
614/// `mln_util::serialization::shared`.
615impl<T: Wire> Wire for Arc<T> {
616    fn write(&self, w: &mut Writer) {
617        (**self).write(w);
618    }
619    fn read(r: &mut Reader<'_>) -> Option<Self> {
620        T::read(r).map(Arc::new)
621    }
622}
623
624impl<T: Wire> Wire for Option<T> {
625    fn write(&self, w: &mut Writer) {
626        match self {
627            None => w.push(0),
628            Some(value) => {
629                w.push(1);
630                value.write(w);
631            }
632        }
633    }
634    fn read(r: &mut Reader<'_>) -> Option<Self> {
635        match r.byte()? {
636            0 => Some(None),
637            1 => T::read(r).map(Some),
638            _ => r.fail("invalid option"),
639        }
640    }
641}
642
643impl<T: Wire + Default + Copy, const N: usize> Wire for [T; N] {
644    fn write(&self, w: &mut Writer) {
645        for item in self {
646            item.write(w);
647        }
648    }
649    fn read(r: &mut Reader<'_>) -> Option<Self> {
650        let mut items = [T::default(); N];
651        for item in &mut items {
652            *item = T::read(r)?;
653        }
654        Some(items)
655    }
656}
657
658macro_rules! tuple {
659    ($($name:ident $index:tt),+) => {
660        impl<$($name: Wire),+> Wire for ($($name,)+) {
661            fn write(&self, w: &mut Writer) {
662                $(self.$index.write(w);)+
663            }
664            fn read(r: &mut Reader<'_>) -> Option<Self> {
665                Some(($($name::read(r)?,)+))
666            }
667        }
668    };
669}
670tuple!(A 0);
671tuple!(A 0, B 1);
672tuple!(A 0, B 1, C 2);
673tuple!(A 0, B 1, C 2, D 3);
674
675impl<K: Wire + Ord, V: Wire> Wire for BTreeMap<K, V> {
676    fn write(&self, w: &mut Writer) {
677        write_len(w, self.len());
678        for (key, value) in self {
679            key.write(w);
680            value.write(w);
681        }
682    }
683    fn read(r: &mut Reader<'_>) -> Option<Self> {
684        let len = r.length()?;
685        let mut map = BTreeMap::new();
686        for _ in 0..len {
687            let key = K::read(r)?;
688            map.insert(key, V::read(r)?);
689        }
690        Some(map)
691    }
692}
693
694/// Hash maps and sets of any hasher, in iteration order, which differs
695/// between maps of the same entries: `mln_util::serialization::sorted` writes
696/// one in key order.
697mod hash {
698    #![expect(clippy::disallowed_types, reason = "impls for every hasher, mln_util's among them")]
699
700    use std::collections::{HashMap, HashSet};
701    use std::hash::{BuildHasher, Hash};
702
703    use super::{Reader, Wire, Writer, write_len};
704
705    impl<K: Wire + Eq + Hash, V: Wire, S: BuildHasher + Default> Wire for HashMap<K, V, S> {
706        fn write(&self, w: &mut Writer) {
707            write_len(w, self.len());
708            for (key, value) in self {
709                key.write(w);
710                value.write(w);
711            }
712        }
713        fn read(r: &mut Reader<'_>) -> Option<Self> {
714            let len = r.length()?;
715            let mut map = HashMap::with_capacity_and_hasher(len.min(r.rest().len()), S::default());
716            for _ in 0..len {
717                let key = K::read(r)?;
718                map.insert(key, V::read(r)?);
719            }
720            Some(map)
721        }
722    }
723
724    impl<T: Wire + Eq + Hash, S: BuildHasher + Default> Wire for HashSet<T, S> {
725        fn write(&self, w: &mut Writer) {
726            write_len(w, self.len());
727            for value in self {
728                value.write(w);
729            }
730        }
731        fn read(r: &mut Reader<'_>) -> Option<Self> {
732            let len = r.length()?;
733            let mut set = HashSet::with_capacity_and_hasher(len.min(r.rest().len()), S::default());
734            for _ in 0..len {
735                set.insert(T::read(r)?);
736            }
737            Some(set)
738        }
739    }
740}
741
742impl<T: Wire + Ord> Wire for BTreeSet<T> {
743    fn write(&self, w: &mut Writer) {
744        write_len(w, self.len());
745        for value in self {
746            value.write(w);
747        }
748    }
749    fn read(r: &mut Reader<'_>) -> Option<Self> {
750        let len = r.length()?;
751        let mut set = BTreeSet::new();
752        for _ in 0..len {
753            set.insert(T::read(r)?);
754        }
755        Some(set)
756    }
757}
758
759impl Wire for Duration {
760    fn write(&self, w: &mut Writer) {
761        self.as_secs().write(w);
762        self.subsec_nanos().write(w);
763    }
764    fn read(r: &mut Reader<'_>) -> Option<Self> {
765        let secs = u64::read(r)?;
766        let nanos = u32::read(r)?;
767        if nanos >= 1_000_000_000 {
768            return r.fail("invalid duration");
769        }
770        Some(Duration::new(secs, nanos))
771    }
772}
773
774#[cfg(feature = "glam")]
775impl Wire for glam::Vec2 {
776    fn write(&self, w: &mut Writer) {
777        self.x.write(w);
778        self.y.write(w);
779    }
780    fn read(r: &mut Reader<'_>) -> Option<Self> {
781        let x = f32::read(r)?;
782        Some(glam::Vec2::new(x, f32::read(r)?))
783    }
784}
785
786/// The value behind the lock, which writing locks.
787#[cfg(feature = "parking_lot")]
788impl<T: Wire> Wire for parking_lot::RwLock<T> {
789    fn write(&self, w: &mut Writer) {
790        self.read().write(w);
791    }
792    fn read(r: &mut Reader<'_>) -> Option<Self> {
793        T::read(r).map(parking_lot::RwLock::new)
794    }
795}
796
797/// The value behind the lock, which writing locks.
798#[cfg(feature = "parking_lot")]
799impl<T: Wire> Wire for parking_lot::Mutex<T> {
800    fn write(&self, w: &mut Writer) {
801        self.lock().write(w);
802    }
803    fn read(r: &mut Reader<'_>) -> Option<Self> {
804        T::read(r).map(parking_lot::Mutex::new)
805    }
806}
807
808/// `geo_types`' geometries, field by field.
809#[cfg(feature = "geo-types")]
810mod geo {
811    use geo_types::{
812        Coord, CoordNum, Geometry, GeometryCollection, Line, LineString, MultiLineString, MultiPoint, MultiPolygon,
813        Point, Polygon, Rect, Triangle,
814    };
815
816    use super::{Reader, Wire, Writer, write_tag};
817
818    impl<T: CoordNum + Wire> Wire for Coord<T> {
819        fn write(&self, w: &mut Writer) {
820            self.x.write(w);
821            self.y.write(w);
822        }
823        fn read(r: &mut Reader<'_>) -> Option<Self> {
824            let x = T::read(r)?;
825            Some(Coord { x, y: T::read(r)? })
826        }
827    }
828
829    impl<T: CoordNum + Wire> Wire for Point<T> {
830        fn write(&self, w: &mut Writer) {
831            self.0.write(w);
832        }
833        fn read(r: &mut Reader<'_>) -> Option<Self> {
834            Coord::read(r).map(Point)
835        }
836    }
837
838    impl<T: CoordNum + Wire> Wire for LineString<T> {
839        fn write(&self, w: &mut Writer) {
840            self.0.write(w);
841        }
842        fn read(r: &mut Reader<'_>) -> Option<Self> {
843            Vec::read(r).map(LineString)
844        }
845    }
846
847    impl<T: CoordNum + Wire> Wire for Polygon<T> {
848        fn write(&self, w: &mut Writer) {
849            self.exterior().write(w);
850            super::write_seq(w, self.interiors());
851        }
852        fn read(r: &mut Reader<'_>) -> Option<Self> {
853            let exterior = LineString::read(r)?;
854            Some(Polygon::new(exterior, Vec::read(r)?))
855        }
856    }
857
858    impl<T: CoordNum + Wire> Wire for Geometry<T> {
859        fn write(&self, w: &mut Writer) {
860            match self {
861                Geometry::Point(point) => {
862                    write_tag(w, 0);
863                    point.write(w);
864                }
865                Geometry::Line(line) => {
866                    write_tag(w, 1);
867                    line.start.write(w);
868                    line.end.write(w);
869                }
870                Geometry::LineString(line) => {
871                    write_tag(w, 2);
872                    line.write(w);
873                }
874                Geometry::Polygon(polygon) => {
875                    write_tag(w, 3);
876                    polygon.write(w);
877                }
878                Geometry::MultiPoint(points) => {
879                    write_tag(w, 4);
880                    points.0.write(w);
881                }
882                Geometry::MultiLineString(lines) => {
883                    write_tag(w, 5);
884                    lines.0.write(w);
885                }
886                Geometry::MultiPolygon(polygons) => {
887                    write_tag(w, 6);
888                    polygons.0.write(w);
889                }
890                Geometry::GeometryCollection(geometries) => {
891                    write_tag(w, 7);
892                    geometries.0.write(w);
893                }
894                Geometry::Rect(rect) => {
895                    write_tag(w, 8);
896                    rect.min().write(w);
897                    rect.max().write(w);
898                }
899                Geometry::Triangle(triangle) => {
900                    write_tag(w, 9);
901                    triangle.v1().write(w);
902                    triangle.v2().write(w);
903                    triangle.v3().write(w);
904                }
905            }
906        }
907        fn read(r: &mut Reader<'_>) -> Option<Self> {
908            Some(match r.tag()? {
909                0 => Geometry::Point(Point::read(r)?),
910                1 => {
911                    let start = Coord::read(r)?;
912                    Geometry::Line(Line::new(start, Coord::read(r)?))
913                }
914                2 => Geometry::LineString(LineString::read(r)?),
915                3 => Geometry::Polygon(Polygon::read(r)?),
916                4 => Geometry::MultiPoint(MultiPoint(Vec::read(r)?)),
917                5 => Geometry::MultiLineString(MultiLineString(Vec::read(r)?)),
918                6 => Geometry::MultiPolygon(MultiPolygon(Vec::read(r)?)),
919                7 => Geometry::GeometryCollection(GeometryCollection(Vec::read(r)?)),
920                8 => {
921                    let min = Coord::read(r)?;
922                    Geometry::Rect(Rect::new(min, Coord::read(r)?))
923                }
924                9 => {
925                    let a = Coord::read(r)?;
926                    let b = Coord::read(r)?;
927                    // As written: the writer's winding.
928                    Geometry::Triangle(Triangle::unchecked_winding(a, b, Coord::read(r)?))
929                }
930                _ => return r.fail_tag(),
931            })
932        }
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use super::*;
939
940    #[derive(Debug, PartialEq, Wire)]
941    struct Named<T> {
942        a: u32,
943        b: Option<T>,
944        #[wire(skip)]
945        c: u8,
946    }
947
948    #[derive(Debug, PartialEq, Wire)]
949    enum Shape {
950        Empty,
951        Point(f32, f32),
952        Named { name: String, sides: Vec<i32> },
953    }
954
955    #[test]
956    fn values_round_trip() {
957        let named = Named { a: 300, b: Some(Shape::Named { name: "x".into(), sides: vec![-1, 2, -300] }), c: 0 };
958        let bytes = to_vec(&named).unwrap();
959        assert_eq!(from_slice::<Named<Shape>>(&bytes).unwrap(), named);
960        for shape in [Shape::Empty, Shape::Point(1.0, -2.5)] {
961            assert_eq!(from_slice::<Shape>(&to_vec(&shape).unwrap()).unwrap(), shape);
962        }
963    }
964
965    #[test]
966    fn truncated_input_is_an_error() {
967        let bytes = to_vec(&Shape::Named { name: "abc".into(), sides: vec![1, 2] }).unwrap();
968        for end in 0..bytes.len() {
969            assert!(from_slice::<Shape>(&bytes[..end]).is_err());
970        }
971        assert_eq!(from_slice::<Shape>(&[9]), Err(Error("unknown variant")));
972    }
973
974    struct Count(u32);
975
976    impl Context for Count {
977        fn provide<'a>(&'a mut self, request: &mut Request<'a>) {
978            request.give_mut(self);
979        }
980    }
981
982    struct Name(&'static str);
983
984    impl Context for &Name {
985        fn provide<'a>(&'a mut self, request: &mut Request<'a>) {
986            request.give::<Name>(self);
987        }
988    }
989
990    /// Reads as how many it is in the context's count.
991    struct Counted(u32);
992
993    impl Wire for Counted {
994        fn write(&self, _: &mut Writer) {}
995        fn read(r: &mut Reader<'_>) -> Option<Self> {
996            let count = r.context_mut::<Count>()?;
997            count.0 += 1;
998            Some(Counted(count.0))
999        }
1000    }
1001
1002    /// Values get the context's parts by type, from any member of a tuple,
1003    /// and a shared part only to read.
1004    #[test]
1005    fn values_ask_the_context_for_their_parts() {
1006        let mut count = Count(0);
1007        let read: (Counted, Counted) = from_slice_in(&[], (&Name("name"), &mut count)).unwrap();
1008        assert_eq!((read.0.0, read.1.0, count.0), (1, 2, 2));
1009        assert!(from_slice::<Counted>(&[]).is_err());
1010
1011        let mut context = (&Name("name"), ());
1012        let mut w = Writer::new().with_context(&mut context);
1013        assert_eq!(w.context::<Name>().map(|name| name.0), Some("name"));
1014        assert!(w.context_mut::<Name>().is_none());
1015        assert!(w.context::<Count>().is_none());
1016    }
1017
1018    #[test]
1019    fn varints_past_64_bits_are_errors() {
1020        let mut max = vec![0xff; 9];
1021        max.push(0x01);
1022        assert_eq!(from_slice::<u64>(&max), Ok(u64::MAX));
1023        let mut over = vec![0x80; 9];
1024        over.push(0x02);
1025        assert!(from_slice::<u64>(&over).is_err());
1026    }
1027}