netidx_core/
pack.rs

1use arcstr::ArcStr;
2use arrayvec::{ArrayString, ArrayVec};
3use bytes::{buf, Buf, BufMut, Bytes, BytesMut};
4use chrono::{
5    naive::{NaiveDate, NaiveDateTime},
6    prelude::*,
7};
8use compact_str::CompactString;
9use indexmap::{IndexMap, IndexSet};
10use poolshark::{take_t, Poolable, Pooled};
11use rust_decimal::Decimal;
12use std::{
13    any::Any,
14    boxed::Box,
15    cell::RefCell,
16    cmp::{self, Eq},
17    collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
18    default::Default,
19    error, fmt,
20    hash::{BuildHasher, Hash},
21    mem, net,
22    ops::{Deref, DerefMut},
23    result, str,
24    sync::Arc,
25    time::Duration,
26};
27
28#[derive(Debug, Clone, Copy)]
29pub enum PackError {
30    UnknownTag,
31    TooBig,
32    InvalidFormat,
33    BufferShort,
34    Application(u64),
35}
36
37impl fmt::Display for PackError {
38    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39        write!(f, "{:?}", self)
40    }
41}
42
43impl error::Error for PackError {}
44
45pub trait Pack {
46    fn const_encoded_len() -> Option<usize> {
47        None
48    }
49    fn encoded_len(&self) -> usize;
50    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError>;
51    fn decode(buf: &mut impl Buf) -> Result<Self, PackError>
52    where
53        Self: std::marker::Sized;
54
55    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError>
56    where
57        Self: std::marker::Sized,
58    {
59        Ok(*self = <Self as Pack>::decode(buf)?)
60    }
61}
62
63impl<T: Pack + Any + Send + Sync + Poolable> Pack for Pooled<T> {
64    fn encoded_len(&self) -> usize {
65        <T as Pack>::encoded_len(&**self)
66    }
67
68    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
69        <T as Pack>::encode(&**self, buf)
70    }
71
72    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
73        let mut t = take_t::<T>(1000, 1000);
74        <T as Pack>::decode_into(&mut *t, buf)?;
75        Ok(t)
76    }
77
78    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
79        <T as Pack>::decode_into(&mut **self, buf)
80    }
81}
82
83impl Pack for net::SocketAddr {
84    fn encoded_len(&self) -> usize {
85        match self {
86            net::SocketAddr::V4(_) => 7,
87            net::SocketAddr::V6(_) => 27,
88        }
89    }
90
91    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
92        match self {
93            net::SocketAddr::V4(v4) => {
94                buf.put_u8(0);
95                buf.put_u32(u32::from_be_bytes(v4.ip().octets()));
96                buf.put_u16(v4.port());
97            }
98            net::SocketAddr::V6(v6) => {
99                buf.put_u8(1);
100                for s in &v6.ip().segments() {
101                    buf.put_u16(*s);
102                }
103                buf.put_u16(v6.port());
104                buf.put_u32(v6.flowinfo());
105                buf.put_u32(v6.scope_id());
106            }
107        }
108        Ok(())
109    }
110
111    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
112        match <u8 as Pack>::decode(buf)? {
113            0 => {
114                let ip =
115                    net::Ipv4Addr::from(u32::to_be_bytes(<u32 as Pack>::decode(buf)?));
116                let port = <u16 as Pack>::decode(buf)?;
117                Ok(net::SocketAddr::V4(net::SocketAddrV4::new(ip, port)))
118            }
119            1 => {
120                let mut segments = [0u16; 8];
121                for i in 0..8 {
122                    segments[i] = <u16 as Pack>::decode(buf)?;
123                }
124                let port = <u16 as Pack>::decode(buf)?;
125                let flowinfo = <u32 as Pack>::decode(buf)?;
126                let scope_id = <u32 as Pack>::decode(buf)?;
127                let ip = net::Ipv6Addr::from(segments);
128                let v6 = net::SocketAddrV6::new(ip, port, flowinfo, scope_id);
129                Ok(net::SocketAddr::V6(v6))
130            }
131            _ => return Err(PackError::UnknownTag),
132        }
133    }
134}
135
136impl Pack for Bytes {
137    fn encoded_len(&self) -> usize {
138        let len = Bytes::len(self);
139        varint_len(len as u64) + len
140    }
141
142    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
143        encode_varint(Bytes::len(self) as u64, buf);
144        Ok(buf.put_slice(&*self))
145    }
146
147    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
148        let len = decode_varint(buf)?;
149        if len as usize > buf.remaining() {
150            Err(PackError::TooBig)
151        } else {
152            Ok(buf.copy_to_bytes(len as usize))
153        }
154    }
155}
156
157#[derive(Debug)]
158pub struct BoundedBytes<const L: usize>(pub Bytes);
159
160impl<const L: usize> Deref for BoundedBytes<L> {
161    type Target = Bytes;
162
163    fn deref(&self) -> &Self::Target {
164        &self.0
165    }
166}
167
168impl<const L: usize> DerefMut for BoundedBytes<L> {
169    fn deref_mut(&mut self) -> &mut Self::Target {
170        &mut self.0
171    }
172}
173
174impl<const L: usize> Pack for BoundedBytes<L> {
175    fn encoded_len(&self) -> usize {
176        let len = Bytes::len(&self.0);
177        varint_len(len as u64) + len
178    }
179
180    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
181        if Bytes::len(self) > L {
182            Err(PackError::TooBig)
183        } else {
184            <Bytes as Pack>::encode(self, buf)
185        }
186    }
187
188    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
189        let len = decode_varint(buf)? as usize;
190        if len > L || len > buf.remaining() {
191            Err(PackError::TooBig)
192        } else {
193            Ok(BoundedBytes(buf.copy_to_bytes(len)))
194        }
195    }
196}
197
198impl Pack for String {
199    fn encoded_len(&self) -> usize {
200        let len = String::len(self);
201        varint_len(len as u64) + len
202    }
203
204    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
205        encode_varint(String::len(self) as u64, buf);
206        Ok(buf.put_slice(self.as_bytes()))
207    }
208
209    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
210        let len = decode_varint(buf)? as usize;
211        if len > buf.remaining() {
212            return Err(PackError::TooBig);
213        }
214        let mut v = vec![0; len];
215        buf.copy_to_slice(&mut v);
216        match String::from_utf8(v) {
217            Ok(s) => Ok(s),
218            Err(_) => Err(PackError::InvalidFormat),
219        }
220    }
221}
222
223impl Pack for CompactString {
224    fn encoded_len(&self) -> usize {
225        let len = CompactString::len(self);
226        varint_len(len as u64) + len
227    }
228
229    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
230        encode_varint(CompactString::len(self) as u64, buf);
231        Ok(buf.put_slice(self.as_bytes()))
232    }
233
234    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
235        thread_local! {
236            static TMP: RefCell<Vec<u8>> = RefCell::new(Vec::new());
237        }
238        let len = decode_varint(buf)? as usize;
239        if len > buf.remaining() {
240            return Err(PackError::TooBig);
241        }
242        TMP.with(|tmp| {
243            let mut tmp = tmp.borrow_mut();
244            tmp.resize(len, 0);
245            buf.copy_to_slice(&mut tmp);
246            if tmp.capacity() > cmp::max(1024, tmp.len() << 2) {
247                tmp.shrink_to(1024)
248            }
249            match CompactString::from_utf8(&tmp[..]) {
250                Ok(s) => Ok(s),
251                Err(_) => Err(PackError::InvalidFormat),
252            }
253        })
254    }
255}
256
257impl<const C: usize> Pack for ArrayString<C> {
258    fn encoded_len(&self) -> usize {
259        let len = ArrayString::len(self);
260        varint_len(len as u64) + len
261    }
262
263    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
264        encode_varint(ArrayString::len(self) as u64, buf);
265        Ok(buf.put_slice(self.as_bytes()))
266    }
267
268    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
269        let len = decode_varint(buf)? as usize;
270        if len > buf.remaining() || len > C {
271            return Err(PackError::TooBig);
272        }
273        let mut v = [0u8; C];
274        buf.copy_to_slice(&mut v[..len]);
275        let mut res: ArrayString<C> = ArrayString::new();
276        match str::from_utf8(&v[..len]) {
277            Ok(s) => {
278                res.push_str(s);
279                Ok(res)
280            }
281            Err(_) => Err(PackError::InvalidFormat),
282        }
283    }
284}
285
286impl Pack for Arc<str> {
287    fn encoded_len(&self) -> usize {
288        let s: &str = &*self;
289        let len = s.len();
290        varint_len(len as u64) + len
291    }
292
293    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
294        let s: &str = &*self;
295        encode_varint(s.len() as u64, buf);
296        Ok(buf.put_slice(self.as_bytes()))
297    }
298
299    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
300        let len = decode_varint(buf)? as usize;
301        if len > buf.remaining() {
302            return Err(PackError::TooBig);
303        }
304        let mut v = vec![0; len];
305        buf.copy_to_slice(&mut v);
306        match String::from_utf8(v) {
307            Ok(s) => Ok(Arc::from(s)),
308            Err(_) => Err(PackError::InvalidFormat),
309        }
310    }
311}
312
313impl Pack for triomphe::Arc<str> {
314    fn encoded_len(&self) -> usize {
315        let s: &str = &*self;
316        let len = s.len();
317        varint_len(len as u64) + len
318    }
319
320    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
321        let s: &str = &*self;
322        encode_varint(s.len() as u64, buf);
323        Ok(buf.put_slice(self.as_bytes()))
324    }
325
326    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
327        let len = decode_varint(buf)? as usize;
328        if len > buf.remaining() {
329            return Err(PackError::TooBig);
330        }
331        let mut v = vec![0; len];
332        buf.copy_to_slice(&mut v);
333        match String::from_utf8(v) {
334            Ok(s) => Ok(triomphe::Arc::from(s)),
335            Err(_) => Err(PackError::InvalidFormat),
336        }
337    }
338}
339
340impl Pack for ArcStr {
341    fn encoded_len(&self) -> usize {
342        let s: &str = &*self;
343        let len = s.len();
344        varint_len(len as u64) + len
345    }
346
347    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
348        let s: &str = &*self;
349        encode_varint(s.len() as u64, buf);
350        Ok(buf.put_slice(self.as_bytes()))
351    }
352
353    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
354        let len = decode_varint(buf)? as usize;
355        if len > buf.remaining() {
356            Err(PackError::TooBig)
357        } else {
358            let res = match str::from_utf8(&buf.chunk()[0..len]) {
359                Ok(s) => Ok(ArcStr::from(s)),
360                Err(_) => Err(PackError::InvalidFormat),
361            };
362            buf.advance(len);
363            res
364        }
365    }
366}
367
368pub fn varint_len(value: u64) -> usize {
369    ((((value | 1).leading_zeros() ^ 63) * 9 + 73) >> 6) as usize
370}
371
372pub fn encode_varint(mut value: u64, buf: &mut impl BufMut) {
373    for _ in 0..10 {
374        if value < 0x80 {
375            buf.put_u8(value as u8);
376            break;
377        } else {
378            buf.put_u8(((value & 0x7F) | 0x80) as u8);
379            value >>= 7;
380        }
381    }
382}
383
384pub fn i32_zz(n: i32) -> u32 {
385    ((n << 1) ^ (n >> 31)) as u32
386}
387
388pub fn i32_uzz(n: u32) -> i32 {
389    ((n >> 1) as i32) ^ (((n as i32) << 31) >> 31)
390}
391
392pub fn i64_zz(n: i64) -> u64 {
393    ((n << 1) ^ (n >> 63)) as u64
394}
395
396pub fn i64_uzz(n: u64) -> i64 {
397    ((n >> 1) as i64) ^ (((n as i64) << 63) >> 63)
398}
399
400pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, PackError> {
401    let bytes = buf.chunk();
402    let mut value = 0;
403    for i in 0..10 {
404        if i >= bytes.len() {
405            return Err(PackError::BufferShort);
406        }
407        let byte = bytes[i];
408        value |= ((byte & 0x7F) as u64) << (i * 7);
409        if byte <= 0x7F {
410            buf.advance(i + 1);
411            return Ok(value);
412        }
413    }
414    buf.advance(10);
415    Err(PackError::InvalidFormat)
416}
417
418pub fn len_wrapped_len(len: usize) -> usize {
419    let vlen = varint_len((len + varint_len(len as u64)) as u64);
420    len + vlen
421}
422
423pub fn len_wrapped_encode<B, T, F>(buf: &mut B, t: &T, f: F) -> Result<(), PackError>
424where
425    B: BufMut,
426    T: Pack,
427    F: FnOnce(&mut B) -> Result<(), PackError>,
428{
429    encode_varint(t.encoded_len() as u64, buf);
430    f(buf)
431}
432
433pub fn len_wrapped_decode<B, T, F>(buf: &mut B, f: F) -> Result<T, PackError>
434where
435    B: Buf,
436    T: Pack + 'static,
437    F: FnOnce(&mut buf::Take<&mut B>) -> Result<T, PackError>,
438{
439    let len = decode_varint(buf)?;
440    // this has to be 1 not 2 because empty structs will be encoded as
441    // length 1
442    if len < 1 {
443        return Err(PackError::BufferShort);
444    }
445    let mut limited = buf.take((len - varint_len(len) as u64) as usize);
446    let r = f(&mut limited);
447    if limited.has_remaining() {
448        limited.advance(limited.remaining());
449    }
450    r
451}
452
453impl Pack for f32 {
454    fn const_encoded_len() -> Option<usize> {
455        Some(mem::size_of::<f32>())
456    }
457
458    fn encoded_len(&self) -> usize {
459        mem::size_of::<f32>()
460    }
461
462    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
463        Ok(buf.put_f32(*self))
464    }
465
466    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
467        if buf.remaining() < mem::size_of::<f32>() {
468            Err(PackError::BufferShort)
469        } else {
470            Ok(buf.get_f32())
471        }
472    }
473}
474
475impl Pack for f64 {
476    fn const_encoded_len() -> Option<usize> {
477        Some(mem::size_of::<f64>())
478    }
479
480    fn encoded_len(&self) -> usize {
481        mem::size_of::<f64>()
482    }
483
484    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
485        Ok(buf.put_f64(*self))
486    }
487
488    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
489        if buf.remaining() < mem::size_of::<f64>() {
490            Err(PackError::BufferShort)
491        } else {
492            Ok(buf.get_f64())
493        }
494    }
495}
496
497impl Pack for Decimal {
498    fn const_encoded_len() -> Option<usize> {
499        Some(16)
500    }
501
502    fn encoded_len(&self) -> usize {
503        Self::const_encoded_len().unwrap()
504    }
505
506    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
507        Ok(buf.put_slice(&self.serialize()[..]))
508    }
509
510    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
511        if buf.remaining() < Self::const_encoded_len().unwrap() {
512            Err(PackError::BufferShort)
513        } else {
514            let mut b = [0u8; 16];
515            buf.copy_to_slice(&mut b);
516            Ok(Decimal::deserialize(b))
517        }
518    }
519}
520
521impl Pack for u128 {
522    fn const_encoded_len() -> Option<usize> {
523        Some(mem::size_of::<u128>())
524    }
525
526    fn encoded_len(&self) -> usize {
527        mem::size_of::<u128>()
528    }
529
530    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
531        Ok(buf.put_u128(*self))
532    }
533
534    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
535        if buf.remaining() < mem::size_of::<u128>() {
536            Err(PackError::BufferShort)
537        } else {
538            Ok(buf.get_u128())
539        }
540    }
541}
542
543impl Pack for i128 {
544    fn const_encoded_len() -> Option<usize> {
545        Some(mem::size_of::<i128>())
546    }
547
548    fn encoded_len(&self) -> usize {
549        mem::size_of::<i128>()
550    }
551
552    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
553        Ok(buf.put_i128(*self))
554    }
555
556    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
557        if buf.remaining() < mem::size_of::<i128>() {
558            Err(PackError::BufferShort)
559        } else {
560            Ok(buf.get_i128())
561        }
562    }
563}
564
565impl Pack for u64 {
566    fn const_encoded_len() -> Option<usize> {
567        Some(mem::size_of::<u64>())
568    }
569
570    fn encoded_len(&self) -> usize {
571        mem::size_of::<u64>()
572    }
573
574    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
575        Ok(buf.put_u64(*self))
576    }
577
578    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
579        if buf.remaining() < mem::size_of::<u64>() {
580            Err(PackError::BufferShort)
581        } else {
582            Ok(buf.get_u64())
583        }
584    }
585}
586
587impl Pack for i64 {
588    fn const_encoded_len() -> Option<usize> {
589        Some(mem::size_of::<i64>())
590    }
591
592    fn encoded_len(&self) -> usize {
593        mem::size_of::<i64>()
594    }
595
596    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
597        Ok(buf.put_i64(*self))
598    }
599
600    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
601        if buf.remaining() < mem::size_of::<i64>() {
602            Err(PackError::BufferShort)
603        } else {
604            Ok(buf.get_i64())
605        }
606    }
607}
608
609#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default, Debug)]
610pub struct Z64(pub u64);
611
612impl Deref for Z64 {
613    type Target = u64;
614
615    fn deref(&self) -> &Self::Target {
616        &self.0
617    }
618}
619
620impl DerefMut for Z64 {
621    fn deref_mut(&mut self) -> &mut Self::Target {
622        &mut self.0
623    }
624}
625
626impl Pack for Z64 {
627    fn encoded_len(&self) -> usize {
628        varint_len(**self)
629    }
630
631    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
632        Ok(encode_varint(**self, buf))
633    }
634
635    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
636        Ok(Z64(decode_varint(buf)?))
637    }
638}
639
640impl Pack for u32 {
641    fn const_encoded_len() -> Option<usize> {
642        Some(mem::size_of::<u32>())
643    }
644
645    fn encoded_len(&self) -> usize {
646        mem::size_of::<u32>()
647    }
648
649    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
650        Ok(buf.put_u32(*self))
651    }
652
653    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
654        if buf.remaining() < mem::size_of::<u32>() {
655            Err(PackError::BufferShort)
656        } else {
657            Ok(buf.get_u32())
658        }
659    }
660}
661
662impl Pack for i32 {
663    fn const_encoded_len() -> Option<usize> {
664        Some(mem::size_of::<i32>())
665    }
666
667    fn encoded_len(&self) -> usize {
668        mem::size_of::<i32>()
669    }
670
671    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
672        Ok(buf.put_i32(*self))
673    }
674
675    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
676        if buf.remaining() < mem::size_of::<i32>() {
677            Err(PackError::BufferShort)
678        } else {
679            Ok(buf.get_i32())
680        }
681    }
682}
683
684impl Pack for u16 {
685    fn const_encoded_len() -> Option<usize> {
686        Some(mem::size_of::<u16>())
687    }
688
689    fn encoded_len(&self) -> usize {
690        mem::size_of::<u16>()
691    }
692
693    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
694        Ok(buf.put_u16(*self))
695    }
696
697    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
698        if buf.remaining() < mem::size_of::<u16>() {
699            Err(PackError::BufferShort)
700        } else {
701            Ok(buf.get_u16())
702        }
703    }
704}
705
706impl Pack for i16 {
707    fn const_encoded_len() -> Option<usize> {
708        Some(mem::size_of::<i16>())
709    }
710
711    fn encoded_len(&self) -> usize {
712        mem::size_of::<i16>()
713    }
714
715    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
716        Ok(buf.put_i16(*self))
717    }
718
719    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
720        if buf.remaining() < mem::size_of::<i16>() {
721            Err(PackError::BufferShort)
722        } else {
723            Ok(buf.get_i16())
724        }
725    }
726}
727
728impl Pack for u8 {
729    fn const_encoded_len() -> Option<usize> {
730        Some(mem::size_of::<u8>())
731    }
732
733    fn encoded_len(&self) -> usize {
734        mem::size_of::<u8>()
735    }
736
737    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
738        Ok(buf.put_u8(*self))
739    }
740
741    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
742        if buf.remaining() < mem::size_of::<u8>() {
743            Err(PackError::BufferShort)
744        } else {
745            Ok(buf.get_u8())
746        }
747    }
748}
749
750impl Pack for i8 {
751    fn const_encoded_len() -> Option<usize> {
752        Some(mem::size_of::<i8>())
753    }
754
755    fn encoded_len(&self) -> usize {
756        mem::size_of::<i8>()
757    }
758
759    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
760        Ok(buf.put_i8(*self))
761    }
762
763    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
764        if buf.remaining() < mem::size_of::<i8>() {
765            Err(PackError::BufferShort)
766        } else {
767            Ok(buf.get_i8())
768        }
769    }
770}
771
772impl<T: Pack, const S: usize> Pack for [T; S] {
773    fn encoded_len(&self) -> usize {
774        self.iter().fold(varint_len(S as u64), |len, t| len + <T as Pack>::encoded_len(t))
775    }
776
777    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
778        encode_varint(S as u64, buf);
779        for t in self {
780            <T as Pack>::encode(t, buf)?
781        }
782        Ok(())
783    }
784
785    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
786        use std::{
787            array,
788            panic::{self, AssertUnwindSafe},
789        };
790        let elts = decode_varint(buf)? as usize;
791        if elts != S {
792            return Err(PackError::InvalidFormat);
793        }
794        // CR estokes: once try_from_fn is stable replace this
795        panic::catch_unwind(AssertUnwindSafe(|| {
796            array::from_fn(|_| <T as Pack>::decode(buf).unwrap())
797        }))
798        .map_err(|_| PackError::InvalidFormat)
799    }
800
801    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
802        let elts = decode_varint(buf)? as usize;
803        if elts != S {
804            return Err(PackError::InvalidFormat);
805        }
806        for i in 0..S {
807            self[i] = <T as Pack>::decode(buf)?;
808        }
809        Ok(())
810    }
811}
812
813pub const MAX_VEC: usize = 2 * 1024 * 1024 * 1024;
814
815impl<T: Pack> Pack for Vec<T> {
816    fn encoded_len(&self) -> usize {
817        self.iter().fold(varint_len(Vec::len(self) as u64), |len, t| {
818            len + <T as Pack>::encoded_len(t)
819        })
820    }
821
822    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
823        encode_varint(Vec::len(self) as u64, buf);
824        for t in self {
825            <T as Pack>::encode(t, buf)?
826        }
827        Ok(())
828    }
829
830    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
831        let elts = decode_varint(buf)? as usize;
832        if elts > MAX_VEC {
833            return Err(PackError::TooBig);
834        }
835        let pre = if elts * mem::size_of::<T>() > MAX_VEC {
836            MAX_VEC / mem::size_of::<T>()
837        } else {
838            elts
839        };
840        let mut data = Vec::with_capacity(pre);
841        for _ in 0..elts {
842            data.push(<T as Pack>::decode(buf)?);
843        }
844        Ok(data)
845    }
846
847    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
848        let elts = decode_varint(buf)? as usize;
849        if elts > MAX_VEC {
850            return Err(PackError::TooBig);
851        }
852        let pre = if elts * mem::size_of::<T>() > MAX_VEC {
853            MAX_VEC / mem::size_of::<T>()
854        } else {
855            elts
856        };
857        if pre > self.capacity() {
858            self.reserve(pre - self.capacity());
859        }
860        for _ in 0..elts {
861            self.push(<T as Pack>::decode(buf)?);
862        }
863        Ok(())
864    }
865}
866
867impl<T: Pack> Pack for Arc<[T]> {
868    fn encoded_len(&self) -> usize {
869        self.iter().fold(varint_len(self.len() as u64), |len, t| {
870            len + <T as Pack>::encoded_len(t)
871        })
872    }
873
874    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
875        encode_varint(self.len() as u64, buf);
876        for t in &**self {
877            <T as Pack>::encode(t, buf)?
878        }
879        Ok(())
880    }
881
882    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
883        let v = <Vec<T> as Pack>::decode(buf)?;
884        Ok(Arc::from(v))
885    }
886}
887
888impl<T: Pack> Pack for triomphe::Arc<[T]> {
889    fn encoded_len(&self) -> usize {
890        self.iter().fold(varint_len(self.len() as u64), |len, t| {
891            len + <T as Pack>::encoded_len(t)
892        })
893    }
894
895    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
896        encode_varint(self.len() as u64, buf);
897        for t in &**self {
898            <T as Pack>::encode(t, buf)?
899        }
900        Ok(())
901    }
902
903    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
904        let v = <Vec<T> as Pack>::decode(buf)?;
905        Ok(triomphe::Arc::from(v))
906    }
907}
908
909impl<T: Pack, const C: usize> Pack for ArrayVec<T, C> {
910    fn encoded_len(&self) -> usize {
911        self.iter().fold(varint_len(ArrayVec::len(self) as u64), |len, t| {
912            len + <T as Pack>::encoded_len(t)
913        })
914    }
915
916    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
917        encode_varint(ArrayVec::len(self) as u64, buf);
918        for t in self {
919            <T as Pack>::encode(t, buf)?
920        }
921        Ok(())
922    }
923
924    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
925        let elts = decode_varint(buf)? as usize;
926        if elts > C {
927            return Err(PackError::TooBig);
928        }
929        let mut data = ArrayVec::new();
930        for _ in 0..elts {
931            data.push(<T as Pack>::decode(buf)?);
932        }
933        Ok(data)
934    }
935
936    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
937        let elts = decode_varint(buf)? as usize;
938        if elts > C - self.len() {
939            return Err(PackError::TooBig);
940        }
941        for _ in 0..elts {
942            self.push(<T as Pack>::decode(buf)?);
943        }
944        Ok(())
945    }
946}
947
948impl<T: Pack> Pack for VecDeque<T> {
949    fn encoded_len(&self) -> usize {
950        self.iter().fold(varint_len(VecDeque::len(self) as u64), |len, t| {
951            len + <T as Pack>::encoded_len(t)
952        })
953    }
954
955    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
956        encode_varint(VecDeque::len(self) as u64, buf);
957        for t in self {
958            <T as Pack>::encode(t, buf)?
959        }
960        Ok(())
961    }
962
963    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
964        let elts = decode_varint(buf)? as usize;
965        if elts > MAX_VEC {
966            return Err(PackError::TooBig);
967        }
968        let pre = if elts * mem::size_of::<T>() > MAX_VEC {
969            MAX_VEC / mem::size_of::<T>()
970        } else {
971            elts
972        };
973        let mut data = VecDeque::with_capacity(pre);
974        for _ in 0..elts {
975            data.push_back(<T as Pack>::decode(buf)?);
976        }
977        Ok(data)
978    }
979
980    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
981        let elts = decode_varint(buf)? as usize;
982        if elts > MAX_VEC {
983            return Err(PackError::TooBig);
984        }
985        let pre = if elts * mem::size_of::<T>() > MAX_VEC {
986            MAX_VEC / mem::size_of::<T>()
987        } else {
988            elts
989        };
990        if pre > self.capacity() {
991            self.reserve(pre - self.capacity());
992        }
993        for _ in 0..elts {
994            self.push_back(<T as Pack>::decode(buf)?);
995        }
996        Ok(())
997    }
998}
999
1000macro_rules! impl_hashmap {
1001    ($ty:ident) => {
1002        impl<K, V, R> Pack for $ty<K, V, R>
1003        where
1004            K: Pack + Hash + Eq,
1005            V: Pack,
1006            R: Default + BuildHasher,
1007        {
1008            fn encoded_len(&self) -> usize {
1009                self.iter().fold(varint_len(self.len() as u64), |len, (k, v)| {
1010                    len + <K as Pack>::encoded_len(k) + <V as Pack>::encoded_len(v)
1011                })
1012            }
1013
1014            fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1015                encode_varint(self.len() as u64, buf);
1016                for (k, v) in self {
1017                    <K as Pack>::encode(k, buf)?;
1018                    <V as Pack>::encode(v, buf)?;
1019                }
1020                Ok(())
1021            }
1022
1023            fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1024                let elts = decode_varint(buf)? as usize;
1025                if elts > MAX_VEC {
1026                    return Err(PackError::TooBig);
1027                }
1028                let pre = if elts * (mem::size_of::<K>() + mem::size_of::<V>()) > MAX_VEC
1029                {
1030                    MAX_VEC / (mem::size_of::<K>() + mem::size_of::<V>())
1031                } else {
1032                    elts
1033                };
1034                let mut data = $ty::with_capacity_and_hasher(pre, R::default());
1035                for _ in 0..elts {
1036                    let k = <K as Pack>::decode(buf)?;
1037                    let v = <V as Pack>::decode(buf)?;
1038                    data.insert(k, v);
1039                }
1040                Ok(data)
1041            }
1042
1043            fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
1044                let elts = decode_varint(buf)? as usize;
1045                if elts > MAX_VEC {
1046                    return Err(PackError::TooBig);
1047                }
1048                let pre = if elts * (mem::size_of::<K>() + mem::size_of::<V>()) > MAX_VEC
1049                {
1050                    MAX_VEC / (mem::size_of::<K>() + mem::size_of::<V>())
1051                } else {
1052                    elts
1053                };
1054                if pre > self.capacity() {
1055                    self.reserve(pre - self.capacity());
1056                }
1057                for _ in 0..elts {
1058                    let k = <K as Pack>::decode(buf)?;
1059                    let v = <V as Pack>::decode(buf)?;
1060                    self.insert(k, v);
1061                }
1062                Ok(())
1063            }
1064        }
1065    };
1066}
1067
1068impl_hashmap!(HashMap);
1069impl_hashmap!(IndexMap);
1070
1071impl<K: Ord + Pack, V: Pack> Pack for BTreeMap<K, V> {
1072    fn encoded_len(&self) -> usize {
1073        self.iter().fold(varint_len(self.len() as u64), |len, (k, v)| {
1074            len + <K as Pack>::encoded_len(k) + <V as Pack>::encoded_len(v)
1075        })
1076    }
1077
1078    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1079        encode_varint(self.len() as u64, buf);
1080        for (k, v) in self {
1081            <K as Pack>::encode(k, buf)?;
1082            <V as Pack>::encode(v, buf)?;
1083        }
1084        Ok(())
1085    }
1086
1087    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1088        let elts = decode_varint(buf)? as usize;
1089        if elts > MAX_VEC {
1090            return Err(PackError::TooBig);
1091        }
1092        let mut data = BTreeMap::default();
1093        for _ in 0..elts {
1094            let k = <K as Pack>::decode(buf)?;
1095            let v = <V as Pack>::decode(buf)?;
1096            data.insert(k, v);
1097        }
1098        Ok(data)
1099    }
1100
1101    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
1102        let elts = decode_varint(buf)? as usize;
1103        if elts > MAX_VEC {
1104            return Err(PackError::TooBig);
1105        }
1106        for _ in 0..elts {
1107            let k = <K as Pack>::decode(buf)?;
1108            let v = <V as Pack>::decode(buf)?;
1109            self.insert(k, v);
1110        }
1111        Ok(())
1112    }
1113}
1114
1115macro_rules! impl_hashset {
1116    ($ty:ident) => {
1117        impl<K, R> Pack for $ty<K, R>
1118        where
1119            K: Pack + Hash + Eq,
1120            R: Default + BuildHasher,
1121        {
1122            fn encoded_len(&self) -> usize {
1123                self.iter().fold(varint_len(self.len() as u64), |len, k| {
1124                    len + <K as Pack>::encoded_len(k)
1125                })
1126            }
1127
1128            fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1129                encode_varint(self.len() as u64, buf);
1130                for k in self {
1131                    <K as Pack>::encode(k, buf)?;
1132                }
1133                Ok(())
1134            }
1135
1136            fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1137                let elts = decode_varint(buf)? as usize;
1138                if elts > MAX_VEC {
1139                    return Err(PackError::TooBig);
1140                }
1141                let pre = if elts * mem::size_of::<K>() > MAX_VEC {
1142                    MAX_VEC / mem::size_of::<K>()
1143                } else {
1144                    elts
1145                };
1146                let mut data = $ty::with_capacity_and_hasher(pre, R::default());
1147                for _ in 0..elts {
1148                    data.insert(<K as Pack>::decode(buf)?);
1149                }
1150                Ok(data)
1151            }
1152
1153            fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
1154                let elts = decode_varint(buf)? as usize;
1155                if elts > MAX_VEC {
1156                    return Err(PackError::TooBig);
1157                }
1158                let pre = if elts * mem::size_of::<K>() > MAX_VEC {
1159                    MAX_VEC / mem::size_of::<K>()
1160                } else {
1161                    elts
1162                };
1163                if pre > self.capacity() {
1164                    self.reserve(pre - self.capacity());
1165                }
1166                for _ in 0..elts {
1167                    self.insert(<K as Pack>::decode(buf)?);
1168                }
1169                Ok(())
1170            }
1171        }
1172    };
1173}
1174
1175impl_hashset!(HashSet);
1176impl_hashset!(IndexSet);
1177
1178impl<K: Ord + Pack> Pack for BTreeSet<K> {
1179    fn encoded_len(&self) -> usize {
1180        self.iter().fold(varint_len(self.len() as u64), |len, k| {
1181            len + <K as Pack>::encoded_len(k)
1182        })
1183    }
1184
1185    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1186        encode_varint(self.len() as u64, buf);
1187        for k in self {
1188            <K as Pack>::encode(k, buf)?;
1189        }
1190        Ok(())
1191    }
1192
1193    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1194        let elts = decode_varint(buf)? as usize;
1195        if elts > MAX_VEC {
1196            return Err(PackError::TooBig);
1197        }
1198        let mut data = BTreeSet::default();
1199        for _ in 0..elts {
1200            data.insert(<K as Pack>::decode(buf)?);
1201        }
1202        Ok(data)
1203    }
1204
1205    fn decode_into(&mut self, buf: &mut impl Buf) -> Result<(), PackError> {
1206        let elts = decode_varint(buf)? as usize;
1207        if elts > MAX_VEC {
1208            return Err(PackError::TooBig);
1209        }
1210        for _ in 0..elts {
1211            self.insert(<K as Pack>::decode(buf)?);
1212        }
1213        Ok(())
1214    }
1215}
1216
1217impl<T: Pack> Pack for Option<T> {
1218    fn encoded_len(&self) -> usize {
1219        1 + match self {
1220            None => 0,
1221            Some(v) => <T as Pack>::encoded_len(v),
1222        }
1223    }
1224
1225    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1226        match self {
1227            None => Ok(buf.put_u8(0)),
1228            Some(v) => {
1229                buf.put_u8(1);
1230                <T as Pack>::encode(v, buf)
1231            }
1232        }
1233    }
1234
1235    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1236        match <u8 as Pack>::decode(buf)? {
1237            0 => Ok(None),
1238            1 => Ok(Some(<T as Pack>::decode(buf)?)),
1239            _ => return Err(PackError::UnknownTag),
1240        }
1241    }
1242}
1243
1244impl<T: Pack, U: Pack> Pack for (T, U) {
1245    fn encoded_len(&self) -> usize {
1246        <T as Pack>::encoded_len(&self.0) + <U as Pack>::encoded_len(&self.1)
1247    }
1248
1249    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1250        <T as Pack>::encode(&self.0, buf)?;
1251        Ok(<U as Pack>::encode(&self.1, buf)?)
1252    }
1253
1254    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1255        let fst = <T as Pack>::decode(buf)?;
1256        let snd = <U as Pack>::decode(buf)?;
1257        Ok((fst, snd))
1258    }
1259}
1260
1261impl<T: Pack, U: Pack, V: Pack> Pack for (T, U, V) {
1262    fn encoded_len(&self) -> usize {
1263        <T as Pack>::encoded_len(&self.0)
1264            + <U as Pack>::encoded_len(&self.1)
1265            + <V as Pack>::encoded_len(&self.2)
1266    }
1267
1268    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1269        <T as Pack>::encode(&self.0, buf)?;
1270        <U as Pack>::encode(&self.1, buf)?;
1271        Ok(<V as Pack>::encode(&self.2, buf)?)
1272    }
1273
1274    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1275        let fst = <T as Pack>::decode(buf)?;
1276        let snd = <U as Pack>::decode(buf)?;
1277        let trd = <V as Pack>::decode(buf)?;
1278        Ok((fst, snd, trd))
1279    }
1280}
1281
1282impl<T: Pack, U: Pack, V: Pack, W: Pack> Pack for (T, U, V, W) {
1283    fn encoded_len(&self) -> usize {
1284        <T as Pack>::encoded_len(&self.0)
1285            + <U as Pack>::encoded_len(&self.1)
1286            + <V as Pack>::encoded_len(&self.2)
1287            + <W as Pack>::encoded_len(&self.3)
1288    }
1289
1290    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1291        <T as Pack>::encode(&self.0, buf)?;
1292        <U as Pack>::encode(&self.1, buf)?;
1293        <V as Pack>::encode(&self.2, buf)?;
1294        Ok(<W as Pack>::encode(&self.3, buf)?)
1295    }
1296
1297    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1298        let fst = <T as Pack>::decode(buf)?;
1299        let snd = <U as Pack>::decode(buf)?;
1300        let trd = <V as Pack>::decode(buf)?;
1301        let fth = <W as Pack>::decode(buf)?;
1302        Ok((fst, snd, trd, fth))
1303    }
1304}
1305
1306impl Pack for bool {
1307    fn const_encoded_len() -> Option<usize> {
1308        Some(mem::size_of::<bool>())
1309    }
1310
1311    fn encoded_len(&self) -> usize {
1312        mem::size_of::<bool>()
1313    }
1314
1315    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1316        Ok(buf.put_u8(if *self { 1 } else { 0 }))
1317    }
1318
1319    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1320        match <u8 as Pack>::decode(buf)? {
1321            0 => Ok(false),
1322            1 => Ok(true),
1323            _ => Err(PackError::UnknownTag),
1324        }
1325    }
1326}
1327
1328const YEAR_MASK: u32 = 0xFFFF_FE00;
1329const MONTH_MASK: u32 = 0x0000_01E0;
1330const DAY_MASK: u32 = 0x0000_001F;
1331
1332impl Pack for NaiveDate {
1333    fn const_encoded_len() -> Option<usize> {
1334        Some(mem::size_of::<u32>())
1335    }
1336
1337    fn encoded_len(&self) -> usize {
1338        <Self as Pack>::const_encoded_len().unwrap()
1339    }
1340
1341    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1342        let i = (self.year() as u32) << 9;
1343        let i = i | self.month() << 5;
1344        let i = i | self.day();
1345        Ok(buf.put_u32(i))
1346    }
1347
1348    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1349        let i: u32 = Pack::decode(buf)?;
1350        let year = (i & YEAR_MASK) as i32 >> 9;
1351        let month = (i & MONTH_MASK) >> 5;
1352        let day = i & DAY_MASK;
1353        match Self::from_ymd_opt(year, month, day) {
1354            Some(d) => Ok(d),
1355            None => Err(PackError::InvalidFormat),
1356        }
1357    }
1358}
1359
1360impl Pack for NaiveDateTime {
1361    fn const_encoded_len() -> Option<usize> {
1362        Some(mem::size_of::<i64>() + mem::size_of::<u32>())
1363    }
1364
1365    fn encoded_len(&self) -> usize {
1366        <DateTime<Utc> as Pack>::const_encoded_len().unwrap()
1367    }
1368
1369    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1370        buf.put_i64(self.and_utc().timestamp());
1371        Ok(buf.put_u32(self.and_utc().timestamp_subsec_nanos()))
1372    }
1373
1374    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1375        let ts = Pack::decode(buf)?;
1376        let ns = Pack::decode(buf)?;
1377        let ndt =
1378            DateTime::from_timestamp(ts, ns).ok_or_else(|| PackError::InvalidFormat)?;
1379        Ok(ndt.naive_utc())
1380    }
1381}
1382
1383impl Pack for DateTime<Utc> {
1384    fn const_encoded_len() -> Option<usize> {
1385        Some(mem::size_of::<i64>() + mem::size_of::<u32>())
1386    }
1387
1388    fn encoded_len(&self) -> usize {
1389        <DateTime<Utc> as Pack>::const_encoded_len().unwrap()
1390    }
1391
1392    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1393        buf.put_i64(self.timestamp());
1394        Ok(buf.put_u32(self.timestamp_subsec_nanos()))
1395    }
1396
1397    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1398        let ts = Pack::decode(buf)?;
1399        let ns = Pack::decode(buf)?;
1400        let dt =
1401            DateTime::from_timestamp(ts, ns).ok_or_else(|| PackError::InvalidFormat)?;
1402        Ok(dt)
1403    }
1404}
1405
1406impl Pack for Duration {
1407    fn const_encoded_len() -> Option<usize> {
1408        Some(mem::size_of::<i64>() + mem::size_of::<u32>())
1409    }
1410
1411    fn encoded_len(&self) -> usize {
1412        <Duration as Pack>::const_encoded_len().unwrap()
1413    }
1414
1415    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1416        buf.put_u64(self.as_secs());
1417        Ok(buf.put_u32(self.subsec_nanos()))
1418    }
1419
1420    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1421        let secs = Pack::decode(buf)?;
1422        let ns = Pack::decode(buf)?;
1423        Ok(Duration::new(secs, ns))
1424    }
1425}
1426
1427impl Pack for chrono::Duration {
1428    fn encoded_len(&self) -> usize {
1429        mem::size_of::<i64>()
1430    }
1431
1432    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1433        match self.num_nanoseconds() {
1434            Some(i) => Pack::encode(&i, buf),
1435            None => Err(PackError::InvalidFormat),
1436        }
1437    }
1438
1439    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1440        Ok(chrono::Duration::nanoseconds(Pack::decode(buf)?))
1441    }
1442}
1443
1444impl Pack for () {
1445    fn const_encoded_len() -> Option<usize> {
1446        Some(0)
1447    }
1448
1449    fn encoded_len(&self) -> usize {
1450        <() as Pack>::const_encoded_len().unwrap()
1451    }
1452
1453    fn encode(&self, _buf: &mut impl BufMut) -> Result<(), PackError> {
1454        Ok(())
1455    }
1456
1457    fn decode(_buf: &mut impl Buf) -> Result<Self, PackError> {
1458        Ok(())
1459    }
1460}
1461
1462impl Pack for uuid::Uuid {
1463    fn const_encoded_len() -> Option<usize> {
1464        Some(mem::size_of::<u128>())
1465    }
1466
1467    fn encoded_len(&self) -> usize {
1468        Self::const_encoded_len().unwrap()
1469    }
1470
1471    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1472        Pack::encode(&self.as_u128(), buf)
1473    }
1474
1475    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1476        Ok(uuid::Uuid::from_u128(Pack::decode(buf)?))
1477    }
1478}
1479
1480impl Pack for usize {
1481    fn const_encoded_len() -> Option<usize> {
1482        Some(mem::size_of::<u64>())
1483    }
1484
1485    fn encoded_len(&self) -> usize {
1486        Self::const_encoded_len().unwrap()
1487    }
1488
1489    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1490        <u64 as Pack>::encode(&(*self as u64), buf)
1491    }
1492
1493    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1494        Ok(<u64 as Pack>::decode(buf)? as usize)
1495    }
1496}
1497
1498impl<T: Pack, U: Pack> Pack for result::Result<T, U> {
1499    fn encoded_len(&self) -> usize {
1500        1 + match self {
1501            Ok(t) => Pack::encoded_len(t),
1502            Err(u) => Pack::encoded_len(u),
1503        }
1504    }
1505
1506    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1507        match self {
1508            Ok(t) => {
1509                <u8 as Pack>::encode(&0, buf)?;
1510                Pack::encode(t, buf)
1511            }
1512            Err(u) => {
1513                <u8 as Pack>::encode(&1, buf)?;
1514                Pack::encode(u, buf)
1515            }
1516        }
1517    }
1518
1519    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1520        match <u8 as Pack>::decode(buf)? {
1521            0 => Ok(Ok(Pack::decode(buf)?)),
1522            1 => Ok(Err(Pack::decode(buf)?)),
1523            _ => Err(PackError::UnknownTag),
1524        }
1525    }
1526}
1527
1528impl<T: Pack> Pack for Arc<T> {
1529    fn encoded_len(&self) -> usize {
1530        Pack::encoded_len(&**self)
1531    }
1532
1533    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1534        Pack::encode(&**self, buf)
1535    }
1536
1537    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1538        Ok(Arc::new(Pack::decode(buf)?))
1539    }
1540}
1541
1542impl<T: Pack> Pack for triomphe::Arc<T> {
1543    fn encoded_len(&self) -> usize {
1544        Pack::encoded_len(&**self)
1545    }
1546
1547    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1548        Pack::encode(&**self, buf)
1549    }
1550
1551    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1552        Ok(triomphe::Arc::new(Pack::decode(buf)?))
1553    }
1554}
1555
1556thread_local! {
1557    static ERR: RefCell<BytesMut> = RefCell::new(BytesMut::new());
1558}
1559
1560fn write_anyhow(s: &mut BytesMut, e: &anyhow::Error) {
1561    use std::fmt::Write;
1562    s.clear();
1563    let _ = write!(s, "{}", e);
1564}
1565
1566// this won't round trip to exactly the same object
1567impl Pack for anyhow::Error {
1568    fn encoded_len(&self) -> usize {
1569        ERR.with(|s| {
1570            let mut s = s.borrow_mut();
1571            write_anyhow(&mut *s, self);
1572            let len = s.len();
1573            varint_len(len as u64) + len
1574        })
1575    }
1576
1577    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1578        ERR.with(|s| {
1579            let mut s = s.borrow_mut();
1580            write_anyhow(&mut *s, self);
1581            let len = s.len();
1582            encode_varint(len as u64, buf);
1583            Ok(buf.put_slice(&*s))
1584        })
1585    }
1586
1587    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1588        let len = decode_varint(buf)? as usize;
1589        if len > buf.remaining() {
1590            Err(PackError::BufferShort)
1591        } else {
1592            let b = buf.copy_to_bytes(len);
1593            let s = match str::from_utf8(&b[..]) {
1594                Ok(s) => s,
1595                Err(_) => return Err(PackError::InvalidFormat),
1596            };
1597            Ok(anyhow::anyhow!(ArcStr::from(s)))
1598        }
1599    }
1600}
1601
1602impl<T: Pack> Pack for Box<T> {
1603    fn encoded_len(&self) -> usize {
1604        Pack::encoded_len(&**self)
1605    }
1606
1607    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1608        Pack::encode(&**self, buf)
1609    }
1610
1611    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1612        Ok(Box::new(Pack::decode(buf)?))
1613    }
1614}
1615
1616use smallvec::{Array, SmallVec};
1617
1618impl<A> Pack for SmallVec<A>
1619where
1620    A: Array,
1621    <A as Array>::Item: Pack,
1622{
1623    fn encoded_len(&self) -> usize {
1624        self.iter().fold(varint_len(SmallVec::len(self) as u64), |len, t| {
1625            len + Pack::encoded_len(t)
1626        })
1627    }
1628
1629    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1630        encode_varint(SmallVec::len(self) as u64, buf);
1631        for t in self {
1632            Pack::encode(t, buf)?
1633        }
1634        Ok(())
1635    }
1636
1637    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1638        let elts = decode_varint(buf)? as usize;
1639        let mut data = SmallVec::new();
1640        for _ in 0..elts {
1641            data.push(Pack::decode(buf)?);
1642        }
1643        Ok(data)
1644    }
1645}
1646
1647use enumflags2::{BitFlag, BitFlags, _internal::RawBitFlags};
1648
1649impl<T> Pack for BitFlags<T>
1650where
1651    T: BitFlag,
1652    <T as RawBitFlags>::Numeric: Pack,
1653{
1654    fn encoded_len(&self) -> usize {
1655        <<T as RawBitFlags>::Numeric as Pack>::encoded_len(&self.bits())
1656    }
1657
1658    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1659        <<T as RawBitFlags>::Numeric as Pack>::encode(&self.bits(), buf)
1660    }
1661
1662    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1663        let bits = <<T as RawBitFlags>::Numeric as Pack>::decode(buf)?;
1664        Self::from_bits(bits).map_err(|_| PackError::InvalidFormat)
1665    }
1666}
1667
1668use std::ops::Bound;
1669
1670impl<T: Pack> Pack for Bound<T> {
1671    fn encoded_len(&self) -> usize {
1672        1 + match self {
1673            Bound::Excluded(t) | Bound::Included(t) => Pack::encoded_len(t),
1674            Bound::Unbounded => 0,
1675        }
1676    }
1677
1678    fn encode(&self, buf: &mut impl BufMut) -> Result<(), PackError> {
1679        match self {
1680            Bound::Unbounded => <u8 as Pack>::encode(&0, buf),
1681            Bound::Excluded(t) => {
1682                <u8 as Pack>::encode(&1, buf)?;
1683                Pack::encode(t, buf)
1684            }
1685            Bound::Included(t) => {
1686                <u8 as Pack>::encode(&2, buf)?;
1687                Pack::encode(t, buf)
1688            }
1689        }
1690    }
1691
1692    fn decode(buf: &mut impl Buf) -> Result<Self, PackError> {
1693        match <u8 as Pack>::decode(buf)? {
1694            0 => Ok(Bound::Unbounded),
1695            1 => Ok(Bound::Excluded(Pack::decode(buf)?)),
1696            2 => Ok(Bound::Included(Pack::decode(buf)?)),
1697            _ => Err(PackError::UnknownTag),
1698        }
1699    }
1700}