Skip to main content

mln_wire/
lib.rs

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