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