senax_encoder/
core.rs

1//! Type tags used in the senax binary format.
2//!
3//! These tags are written as the first byte of each encoded value to identify its type and optimize decoding.
4//! Most users do not need to use these directly.
5//!
6//! - Primitives, Option, String, Vec, arrays, maps, structs, enums, and feature types each have their own tag(s).
7//! - Tags are stable and part of the wire format.
8
9use crate::*;
10
11///< 0 for numbers, false for bool
12pub const TAG_ZERO: u8 = 0;
13///< 1 for numbers, true for bool
14// 5-130: Values 2-127 (compact encoding for small unsigned integers)
15pub const TAG_ONE: u8 = 1;
16pub const TAG_U8_127: u8 = 127; // 127
17pub const TAG_NONE: u8 = 128;
18pub const TAG_SOME: u8 = 129;
19pub const TAG_U8: u8 = 131;
20pub const TAG_U16: u8 = 132;
21pub const TAG_U32: u8 = 133;
22pub const TAG_U64: u8 = 134;
23pub const TAG_U128: u8 = 135;
24///< Negative signed integer (bit-inverted encoding)
25pub const TAG_NEGATIVE: u8 = 136;
26pub const TAG_F32: u8 = 137;
27pub const TAG_F64: u8 = 138;
28///< Short string (length in tag) - String, SmolStr
29pub const TAG_STRING_BASE: u8 = 139;
30///< Long string (length encoded) - String, SmolStr
31pub const TAG_STRING_LONG: u8 = 180;
32///< Bytes
33pub const TAG_BINARY: u8 = 181;
34///< Unit struct
35pub const TAG_STRUCT_UNIT: u8 = 182;
36///< Named struct
37pub const TAG_STRUCT_NAMED: u8 = 183;
38///< Tuple struct
39pub const TAG_STRUCT_UNNAMED: u8 = 184;
40pub const TAG_ENUM: u8 = 185;
41///< Enum with named fields
42pub const TAG_ENUM_NAMED: u8 = 186;
43///< Enum with tuple fields
44pub const TAG_ENUM_UNNAMED: u8 = 187;
45///< Short array/vec/set (length in tag) - includes HashSet, BTreeSet, IndexSet, FxHashSet, AHashSet
46pub const TAG_ARRAY_VEC_SET_BASE: u8 = 188;
47///< Long array/vec/set (length encoded) - includes HashSet, BTreeSet, IndexSet, FxHashSet, AHashSet
48pub const TAG_ARRAY_VEC_SET_LONG: u8 = 194;
49///< Tuple
50pub const TAG_TUPLE: u8 = 195;
51///< Map (HashMap, BTreeMap, IndexMap, FxHashMap, AHashMap)
52pub const TAG_MAP: u8 = 196;
53///< chrono::DateTime
54pub const TAG_CHRONO_DATETIME: u8 = 197;
55///< chrono::NaiveDate
56pub const TAG_CHRONO_NAIVE_DATE: u8 = 198;
57///< chrono::NaiveTime
58pub const TAG_CHRONO_NAIVE_TIME: u8 = 199;
59///< chrono::NaiveDateTime
60pub const TAG_CHRONO_NAIVE_DATETIME: u8 = 208;
61///< rust_decimal::Decimal
62pub const TAG_DECIMAL: u8 = 200;
63///< uuid::Uuid, ulid::Ulid
64pub const TAG_UUID: u8 = 201;
65pub const TAG_JSON_NULL: u8 = 202;
66pub const TAG_JSON_BOOL: u8 = 203; // Uses existing TAG_ZERO/TAG_ONE for value
67pub const TAG_JSON_NUMBER: u8 = 204;
68pub const TAG_JSON_STRING: u8 = 205; // Uses existing string encoding
69pub const TAG_JSON_ARRAY: u8 = 206;
70pub const TAG_JSON_OBJECT: u8 = 207;
71
72// --- bool ---
73/// Encodes a `bool` as a single tag byte: `TAG_ZERO` for `false`, `TAG_ONE` for `true`.
74impl Encoder for bool {
75    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
76        let tag = if !*self { TAG_ZERO } else { TAG_ONE }; // 0: false, 1: true
77        writer.put_u8(tag);
78        Ok(())
79    }
80
81    fn is_default(&self) -> bool {
82        !(*self)
83    }
84}
85
86/// Packs a `bool` as a single tag byte: `TAG_ZERO` for `false`, `TAG_ONE` for `true`.
87impl Packer for bool {
88    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
89        let tag = if !*self { TAG_ZERO } else { TAG_ONE }; // 0: false, 1: true
90        writer.put_u8(tag);
91        Ok(())
92    }
93}
94
95/// Decodes a `bool` from a single tag byte.
96///
97/// # Errors
98/// Returns an error if the tag is not `TAG_ZERO` or `TAG_ONE`.
99impl Decoder for bool {
100    fn decode(reader: &mut Bytes) -> Result<Self> {
101        if reader.remaining() == 0 {
102            return Err(EncoderError::InsufficientData);
103        }
104        let tag = reader.get_u8();
105        match tag {
106            TAG_ZERO => Ok(false),
107            TAG_ONE => Ok(true),
108            other => Err(EncoderError::Decode(format!(
109                "Expected bool tag ({} or {}), got {}",
110                TAG_ZERO, TAG_ONE, other
111            ))),
112        }
113    }
114}
115
116/// Unpacks a `bool` from a single byte with relaxed validation.
117///
118/// 0 is interpreted as `false`, any non-zero value is interpreted as `true`.
119/// No error checking is performed for invalid values.
120impl Unpacker for bool {
121    fn unpack(reader: &mut Bytes) -> Result<Self> {
122        if reader.remaining() == 0 {
123            return Err(EncoderError::InsufficientData);
124        }
125        let value = reader.get_u8();
126        Ok(value != TAG_ZERO)
127    }
128}
129
130// --- Common decode functions ---
131/// Decodes a `u8` value from a tag and buffer.
132/// Used internally for compact integer decoding.
133///
134/// # Errors
135/// Returns an error if the tag is not valid for a `u8`.
136#[inline]
137fn decode_u8_from_tag(tag: u8, reader: &mut Bytes) -> Result<u8> {
138    if (TAG_ZERO..=TAG_U8_127).contains(&tag) {
139        Ok(tag - TAG_ZERO)
140    } else if tag == TAG_U8 {
141        if reader.remaining() == 0 {
142            return Err(EncoderError::InsufficientData);
143        }
144        let stored_val = reader.get_u8();
145        stored_val.checked_add(128).ok_or_else(|| {
146            EncoderError::Decode(format!("u8 TAG_U8 value overflow: {}", stored_val))
147        })
148    } else {
149        Err(EncoderError::Decode(format!(
150            "Unexpected tag for u8: {}",
151            tag
152        )))
153    }
154}
155/// Decodes a `u16` value from a tag and buffer.
156/// Used internally for compact integer decoding.
157fn decode_u16_from_tag(tag: u8, reader: &mut Bytes) -> Result<u16> {
158    if (TAG_ZERO..=TAG_U8_127).contains(&tag) {
159        Ok((tag - TAG_ZERO) as u16)
160    } else if tag == TAG_U8 {
161        if reader.remaining() == 0 {
162            return Err(EncoderError::InsufficientData);
163        }
164        Ok(reader.get_u8() as u16 + 128)
165    } else if tag == TAG_U16 {
166        if reader.remaining() < 2 {
167            return Err(EncoderError::InsufficientData);
168        }
169        Ok(reader.get_u16_le())
170    } else {
171        Err(EncoderError::Decode(format!(
172            "Unexpected tag for u16: {}",
173            tag
174        )))
175    }
176}
177/// Decodes a `u32` value from a tag and buffer.
178/// Used internally for compact integer decoding.
179#[inline]
180fn decode_u32_from_tag(tag: u8, reader: &mut Bytes) -> Result<u32> {
181    if (TAG_ZERO..=TAG_U8_127).contains(&tag) {
182        Ok((tag - TAG_ZERO) as u32)
183    } else if tag == TAG_U8 {
184        if reader.remaining() == 0 {
185            return Err(EncoderError::InsufficientData);
186        }
187        Ok(reader.get_u8() as u32 + 128)
188    } else if tag == TAG_U16 {
189        if reader.remaining() < 2 {
190            return Err(EncoderError::InsufficientData);
191        }
192        Ok(reader.get_u16_le() as u32)
193    } else if tag == TAG_U32 {
194        if reader.remaining() < 4 {
195            return Err(EncoderError::InsufficientData);
196        }
197        Ok(reader.get_u32_le())
198    } else {
199        Err(EncoderError::Decode(format!(
200            "Unexpected tag for u32: {}",
201            tag
202        )))
203    }
204}
205/// Decodes a `u64` value from a tag and buffer.
206/// Used internally for compact integer decoding.
207#[inline]
208fn decode_u64_from_tag(tag: u8, reader: &mut Bytes) -> Result<u64> {
209    if (TAG_ZERO..=TAG_U8_127).contains(&tag) {
210        Ok((tag - TAG_ZERO) as u64)
211    } else if tag == TAG_U8 {
212        if reader.remaining() == 0 {
213            return Err(EncoderError::InsufficientData);
214        }
215        Ok(reader.get_u8() as u64 + 128)
216    } else if tag == TAG_U16 {
217        if reader.remaining() < 2 {
218            return Err(EncoderError::InsufficientData);
219        }
220        Ok(reader.get_u16_le() as u64)
221    } else if tag == TAG_U32 {
222        if reader.remaining() < 4 {
223            return Err(EncoderError::InsufficientData);
224        }
225        Ok(reader.get_u32_le() as u64)
226    } else if tag == TAG_U64 {
227        if reader.remaining() < 8 {
228            return Err(EncoderError::InsufficientData);
229        }
230        Ok(reader.get_u64_le())
231    } else {
232        Err(EncoderError::Decode(format!(
233            "Unexpected tag for u64: {}",
234            tag
235        )))
236    }
237}
238/// Decodes a `u128` value from a tag and buffer.
239/// Used internally for compact integer decoding.
240fn decode_u128_from_tag(tag: u8, reader: &mut Bytes) -> Result<u128> {
241    if (TAG_ZERO..=TAG_U8_127).contains(&tag) {
242        Ok((tag - TAG_ZERO) as u128)
243    } else if tag == TAG_U8 {
244        if reader.remaining() == 0 {
245            return Err(EncoderError::InsufficientData);
246        }
247        Ok(reader.get_u8() as u128 + 128)
248    } else if tag == TAG_U16 {
249        if reader.remaining() < 2 {
250            return Err(EncoderError::InsufficientData);
251        }
252        Ok(reader.get_u16_le() as u128)
253    } else if tag == TAG_U32 {
254        if reader.remaining() < 4 {
255            return Err(EncoderError::InsufficientData);
256        }
257        Ok(reader.get_u32_le() as u128)
258    } else if tag == TAG_U64 {
259        if reader.remaining() < 8 {
260            return Err(EncoderError::InsufficientData);
261        }
262        Ok(reader.get_u64_le() as u128)
263    } else if tag == TAG_U128 {
264        if reader.remaining() < 16 {
265            return Err(EncoderError::InsufficientData);
266        }
267        Ok(reader.get_u128_le())
268    } else {
269        Err(EncoderError::Decode(format!(
270            "Unexpected tag for u128: {}",
271            tag
272        )))
273    }
274}
275
276// --- Unsigned integer types ---
277/// Encodes unsigned integers using a compact variable-length format.
278///
279/// - Values 0/1 are encoded as `TAG_ZERO`/`TAG_ONE` (1 byte)
280/// - 2..=127 are encoded as a single tag byte (1 byte)
281/// - Larger values use `TAG_U8`, `TAG_U16`, `TAG_U32`, `TAG_U64`, or `TAG_U128` with the value in little-endian
282/// - The encoding is stable and compatible across platforms
283impl Encoder for u8 {
284    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
285        if *self <= 127 {
286            writer.put_u8(TAG_ZERO + *self);
287        } else {
288            writer.put_u8(TAG_U8);
289            writer.put_u8(*self - 128);
290        }
291        Ok(())
292    }
293
294    fn is_default(&self) -> bool {
295        *self == 0
296    }
297}
298
299impl Packer for u8 {
300    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
301        writer.put_u8(*self);
302        Ok(())
303    }
304}
305
306/// Decodes a `u8` from the compact format.
307impl Decoder for u8 {
308    fn decode(reader: &mut Bytes) -> Result<Self> {
309        if reader.remaining() == 0 {
310            return Err(EncoderError::InsufficientData);
311        }
312        let tag = reader.get_u8();
313        decode_u8_from_tag(tag, reader)
314    }
315}
316
317impl Unpacker for u8 {
318    fn unpack(reader: &mut Bytes) -> Result<Self> {
319        if reader.remaining() == 0 {
320            return Err(EncoderError::InsufficientData);
321        }
322        Ok(reader.get_u8())
323    }
324}
325
326/// See `u8` for format details.
327impl Encoder for u16 {
328    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
329        if *self <= 127 {
330            writer.put_u8(TAG_ZERO + (*self as u8));
331        } else if *self <= 255 + 128 {
332            writer.put_u8(TAG_U8);
333            writer.put_u8((*self - 128) as u8);
334        } else {
335            writer.put_u8(TAG_U16);
336            writer.put_u16_le(*self);
337        }
338        Ok(())
339    }
340
341    fn is_default(&self) -> bool {
342        *self == 0
343    }
344}
345
346impl Packer for u16 {
347    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
348        self.encode(writer)
349    }
350}
351
352impl Decoder for u16 {
353    fn decode(reader: &mut Bytes) -> Result<Self> {
354        if reader.remaining() == 0 {
355            return Err(EncoderError::InsufficientData);
356        }
357        let tag = reader.get_u8();
358        decode_u16_from_tag(tag, reader)
359    }
360}
361
362impl Unpacker for u16 {
363    fn unpack(reader: &mut Bytes) -> Result<Self> {
364        Self::decode(reader)
365    }
366}
367
368impl Encoder for u32 {
369    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
370        if *self <= 127 {
371            writer.put_u8(TAG_ZERO + (*self as u8));
372        } else if *self <= 255 + 128 {
373            writer.put_u8(TAG_U8);
374            writer.put_u8((*self - 128) as u8);
375        } else if *self <= 65535 {
376            writer.put_u8(TAG_U16);
377            writer.put_u16_le(*self as u16);
378        } else {
379            writer.put_u8(TAG_U32);
380            writer.put_u32_le(*self);
381        }
382        Ok(())
383    }
384
385    fn is_default(&self) -> bool {
386        *self == 0
387    }
388}
389
390impl Packer for u32 {
391    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
392        self.encode(writer)
393    }
394}
395
396/// Decodes a `u32` from the compact format.
397impl Decoder for u32 {
398    fn decode(reader: &mut Bytes) -> Result<Self> {
399        if reader.remaining() == 0 {
400            return Err(EncoderError::InsufficientData);
401        }
402        let tag = reader.get_u8();
403        decode_u32_from_tag(tag, reader)
404    }
405}
406
407impl Unpacker for u32 {
408    fn unpack(reader: &mut Bytes) -> Result<Self> {
409        Self::decode(reader)
410    }
411}
412
413/// See `u32` for format details.
414impl Encoder for u64 {
415    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
416        if *self <= 127 {
417            writer.put_u8(TAG_ZERO + (*self as u8));
418        } else if *self <= 255 + 128 {
419            writer.put_u8(TAG_U8);
420            writer.put_u8((*self - 128) as u8);
421        } else if *self <= 65535 {
422            writer.put_u8(TAG_U16);
423            writer.put_u16_le(*self as u16);
424        } else if *self <= 4294967295 {
425            writer.put_u8(TAG_U32);
426            writer.put_u32_le(*self as u32);
427        } else {
428            writer.put_u8(TAG_U64);
429            writer.put_u64_le(*self);
430        }
431        Ok(())
432    }
433
434    fn is_default(&self) -> bool {
435        *self == 0
436    }
437}
438
439impl Packer for u64 {
440    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
441        self.encode(writer)
442    }
443}
444
445/// Decodes a `u64` from the compact format.
446impl Decoder for u64 {
447    fn decode(reader: &mut Bytes) -> Result<Self> {
448        if reader.remaining() == 0 {
449            return Err(EncoderError::InsufficientData);
450        }
451        let tag = reader.get_u8();
452        decode_u64_from_tag(tag, reader)
453    }
454}
455
456impl Unpacker for u64 {
457    fn unpack(reader: &mut Bytes) -> Result<Self> {
458        Self::decode(reader)
459    }
460}
461
462/// See `u64` for format details.
463impl Encoder for u128 {
464    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
465        if *self <= 127 {
466            writer.put_u8(TAG_ZERO + (*self as u8));
467        } else if *self <= 255 + 128 {
468            writer.put_u8(TAG_U8);
469            writer.put_u8((*self - 128) as u8);
470        } else if *self <= 65535 {
471            writer.put_u8(TAG_U16);
472            writer.put_u16_le(*self as u16);
473        } else if *self <= 4294967295 {
474            writer.put_u8(TAG_U32);
475            writer.put_u32_le(*self as u32);
476        } else if *self <= 18446744073709551615 {
477            writer.put_u8(TAG_U64);
478            writer.put_u64_le(*self as u64);
479        } else {
480            writer.put_u8(TAG_U128);
481            writer.put_u128_le(*self);
482        }
483        Ok(())
484    }
485
486    fn is_default(&self) -> bool {
487        *self == 0
488    }
489}
490
491impl Packer for u128 {
492    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
493        self.encode(writer)
494    }
495}
496
497impl Decoder for u128 {
498    fn decode(reader: &mut Bytes) -> Result<Self> {
499        if reader.remaining() == 0 {
500            return Err(EncoderError::InsufficientData);
501        }
502        let tag = reader.get_u8();
503        decode_u128_from_tag(tag, reader)
504    }
505}
506
507impl Unpacker for u128 {
508    fn unpack(reader: &mut Bytes) -> Result<Self> {
509        Self::decode(reader)
510    }
511}
512
513/// Encodes `usize` using the platform's pointer width, but always as a portable integer format.
514impl Encoder for usize {
515    #[inline]
516    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
517        if usize::BITS == u64::BITS {
518            let v = *self as u64;
519            v.encode(writer)
520        } else if usize::BITS == u32::BITS {
521            let v = *self as u32;
522            v.encode(writer)
523        } else if usize::BITS == u16::BITS {
524            let v = *self as u16;
525            v.encode(writer)
526        } else {
527            let v = *self as u128;
528            v.encode(writer)
529        }
530    }
531
532    fn is_default(&self) -> bool {
533        *self == 0
534    }
535}
536
537impl Packer for usize {
538    #[inline]
539    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
540        self.encode(writer)
541    }
542}
543
544impl Decoder for usize {
545    fn decode(reader: &mut Bytes) -> Result<Self> {
546        if reader.remaining() == 0 {
547            return Err(EncoderError::InsufficientData);
548        }
549        let tag = reader.get_u8();
550        if usize::BITS == u64::BITS {
551            Ok(decode_u64_from_tag(tag, reader)? as usize)
552        } else if usize::BITS == u32::BITS {
553            Ok(decode_u32_from_tag(tag, reader)? as usize)
554        } else if usize::BITS == u16::BITS {
555            Ok(decode_u16_from_tag(tag, reader)? as usize)
556        } else {
557            Ok(decode_u128_from_tag(tag, reader)? as usize)
558        }
559    }
560}
561
562impl Unpacker for usize {
563    fn unpack(reader: &mut Bytes) -> Result<Self> {
564        Self::decode(reader)
565    }
566}
567
568// --- Signed integer types (bit-inverted encoding) ---
569/// Encodes signed integers using bit-inverted encoding for negative values.
570///
571/// - Non-negative values (>= 0) are encoded as unsigned integers
572/// - Negative values use `TAG_NEGATIVE` and bit-inverted encoding
573impl Encoder for i8 {
574    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
575        if *self >= 0 {
576            (*self as u8).encode(writer)
577        } else {
578            writer.put_u8(TAG_NEGATIVE);
579            let inv = !(*self as u8);
580            inv.encode(writer)
581        }
582    }
583
584    fn is_default(&self) -> bool {
585        *self == 0
586    }
587}
588
589impl Packer for i8 {
590    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
591        writer.put_i8(*self);
592        Ok(())
593    }
594}
595
596/// Decodes a `i8` from the bit-inverted encoding.
597///
598/// # Errors
599/// Returns an error if the tag is not valid for an `i8`.
600impl Decoder for i8 {
601    fn decode(reader: &mut Bytes) -> Result<Self> {
602        if reader.remaining() == 0 {
603            return Err(EncoderError::InsufficientData);
604        }
605        let tag = reader.get_u8();
606        match tag {
607            TAG_NEGATIVE => {
608                let inv = u8::decode(reader)?;
609                Ok(!inv as i8)
610            }
611            t => {
612                let v = decode_u8_from_tag(t, reader)?;
613                if v > i8::MAX as u8 {
614                    return Err(EncoderError::Decode(format!(
615                        "Value {} too large for i8",
616                        v
617                    )));
618                }
619                Ok(v as i8)
620            }
621        }
622    }
623}
624
625impl Unpacker for i8 {
626    fn unpack(reader: &mut Bytes) -> Result<Self> {
627        if reader.remaining() == 0 {
628            return Err(EncoderError::InsufficientData);
629        }
630        Ok(reader.get_i8())
631    }
632}
633// i16
634impl Encoder for i16 {
635    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
636        if *self >= 0 {
637            (*self as u16).encode(writer)
638        } else {
639            writer.put_u8(TAG_NEGATIVE);
640            let inv = !(*self as u16);
641            inv.encode(writer)
642        }
643    }
644
645    fn is_default(&self) -> bool {
646        *self == 0
647    }
648}
649
650impl Packer for i16 {
651    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
652        self.encode(writer)
653    }
654}
655
656impl Decoder for i16 {
657    fn decode(reader: &mut Bytes) -> Result<Self> {
658        if reader.remaining() == 0 {
659            return Err(EncoderError::InsufficientData);
660        }
661        let tag = reader.get_u8();
662        match tag {
663            TAG_NEGATIVE => {
664                let inv = u16::decode(reader)?;
665                Ok(!inv as i16)
666            }
667            t => {
668                let v = decode_u16_from_tag(t, reader)?;
669                if v > i16::MAX as u16 {
670                    return Err(EncoderError::Decode(format!(
671                        "Value {} too large for i16",
672                        v
673                    )));
674                }
675                Ok(v as i16)
676            }
677        }
678    }
679}
680
681impl Unpacker for i16 {
682    fn unpack(reader: &mut Bytes) -> Result<Self> {
683        Self::decode(reader)
684    }
685}
686// i32
687impl Encoder for i32 {
688    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
689        if *self >= 0 {
690            (*self as u32).encode(writer)
691        } else {
692            writer.put_u8(TAG_NEGATIVE);
693            let inv = !(*self as u32);
694            inv.encode(writer)
695        }
696    }
697
698    fn is_default(&self) -> bool {
699        *self == 0
700    }
701}
702
703impl Packer for i32 {
704    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
705        self.encode(writer)
706    }
707}
708
709impl Decoder for i32 {
710    fn decode(reader: &mut Bytes) -> Result<Self> {
711        if reader.remaining() == 0 {
712            return Err(EncoderError::InsufficientData);
713        }
714        let tag = reader.get_u8();
715        match tag {
716            TAG_NEGATIVE => {
717                let inv = u32::decode(reader)?;
718                Ok(!inv as i32)
719            }
720            t => {
721                let v = decode_u32_from_tag(t, reader)?;
722                if v > i32::MAX as u32 {
723                    return Err(EncoderError::Decode(format!(
724                        "Value {} too large for i32",
725                        v
726                    )));
727                }
728                Ok(v as i32)
729            }
730        }
731    }
732}
733
734impl Unpacker for i32 {
735    fn unpack(reader: &mut Bytes) -> Result<Self> {
736        Self::decode(reader)
737    }
738}
739
740// i64
741impl Encoder for i64 {
742    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
743        if *self >= 0 {
744            (*self as u64).encode(writer)
745        } else {
746            writer.put_u8(TAG_NEGATIVE);
747            let inv = !(*self as u64);
748            inv.encode(writer)
749        }
750    }
751
752    fn is_default(&self) -> bool {
753        *self == 0
754    }
755}
756
757impl Packer for i64 {
758    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
759        self.encode(writer)
760    }
761}
762
763impl Decoder for i64 {
764    fn decode(reader: &mut Bytes) -> Result<Self> {
765        if reader.remaining() == 0 {
766            return Err(EncoderError::InsufficientData);
767        }
768        let tag = reader.get_u8();
769        match tag {
770            TAG_NEGATIVE => {
771                let inv = u64::decode(reader)?;
772                Ok(!inv as i64)
773            }
774            t => {
775                let v = decode_u64_from_tag(t, reader)?;
776                if v > i64::MAX as u64 {
777                    return Err(EncoderError::Decode(format!(
778                        "Value {} too large for i64",
779                        v
780                    )));
781                }
782                Ok(v as i64)
783            }
784        }
785    }
786}
787
788impl Unpacker for i64 {
789    fn unpack(reader: &mut Bytes) -> Result<Self> {
790        Self::decode(reader)
791    }
792}
793
794// i128
795impl Encoder for i128 {
796    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
797        if *self >= 0 {
798            (*self as u128).encode(writer)
799        } else {
800            writer.put_u8(TAG_NEGATIVE);
801            let inv = !(*self as u128);
802            inv.encode(writer)
803        }
804    }
805
806    fn is_default(&self) -> bool {
807        *self == 0
808    }
809}
810
811impl Packer for i128 {
812    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
813        self.encode(writer)
814    }
815}
816
817impl Decoder for i128 {
818    fn decode(reader: &mut Bytes) -> Result<Self> {
819        if reader.remaining() == 0 {
820            return Err(EncoderError::InsufficientData);
821        }
822        let tag = reader.get_u8();
823        match tag {
824            TAG_NEGATIVE => {
825                let inv = u128::decode(reader)?;
826                Ok(!inv as i128)
827            }
828            t => {
829                let v = decode_u128_from_tag(t, reader)?;
830                if v > i128::MAX as u128 {
831                    return Err(EncoderError::Decode(format!(
832                        "Value {} too large for i128",
833                        v
834                    )));
835                }
836                Ok(v as i128)
837            }
838        }
839    }
840}
841
842impl Unpacker for i128 {
843    fn unpack(reader: &mut Bytes) -> Result<Self> {
844        Self::decode(reader)
845    }
846}
847
848// isize
849impl Encoder for isize {
850    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
851        if usize::BITS == u64::BITS {
852            let v = *self as i64;
853            v.encode(writer)
854        } else if usize::BITS == u32::BITS {
855            let v = *self as i32;
856            v.encode(writer)
857        } else if usize::BITS == u16::BITS {
858            let v = *self as i16;
859            v.encode(writer)
860        } else {
861            let v = *self as i128;
862            v.encode(writer)
863        }
864    }
865
866    fn is_default(&self) -> bool {
867        *self == 0
868    }
869}
870
871impl Packer for isize {
872    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
873        self.encode(writer)
874    }
875}
876
877impl Decoder for isize {
878    fn decode(reader: &mut Bytes) -> Result<Self> {
879        if reader.remaining() == 0 {
880            return Err(EncoderError::InsufficientData);
881        }
882        if usize::BITS == u64::BITS {
883            Ok(i64::decode(reader)? as isize)
884        } else if usize::BITS == u32::BITS {
885            Ok(i32::decode(reader)? as isize)
886        } else if usize::BITS == u16::BITS {
887            Ok(i16::decode(reader)? as isize)
888        } else {
889            Ok(i128::decode(reader)? as isize)
890        }
891    }
892}
893
894impl Unpacker for isize {
895    fn unpack(reader: &mut Bytes) -> Result<Self> {
896        Self::decode(reader)
897    }
898}
899
900// --- char ---
901/// Encodes a `char` as its Unicode code point using the same format as `u32`.
902impl Encoder for char {
903    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
904        let code_point = *self as u32;
905        code_point.encode(writer)
906    }
907
908    fn is_default(&self) -> bool {
909        *self == '\0'
910    }
911}
912
913impl Packer for char {
914    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
915        self.encode(writer)
916    }
917}
918
919/// Decodes a `char` from its Unicode code point.
920///
921/// # Errors
922/// Returns an error if the code point is not a valid Unicode scalar value.
923impl Decoder for char {
924    fn decode(reader: &mut Bytes) -> Result<Self> {
925        let code_point = u32::decode(reader)?;
926        char::from_u32(code_point).ok_or_else(|| {
927            EncoderError::Decode(format!("Invalid Unicode code point: {}", code_point))
928        })
929    }
930}
931
932impl Unpacker for char {
933    fn unpack(reader: &mut Bytes) -> Result<Self> {
934        Self::decode(reader)
935    }
936}
937
938// --- f32/f64 ---
939/// Encodes an `f32` as a scientific notation string.
940///
941/// Note: Pack/Unpack still uses binary format for efficiency.
942/// The string format provides better compatibility and readability for Encode/Decode.
943impl Encoder for f32 {
944    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
945        let s = format!("{:e}", self);
946        s.encode(writer)
947    }
948
949    fn is_default(&self) -> bool {
950        *self == 0.0
951    }
952}
953
954impl Packer for f32 {
955    /// Packs an `f32` as 4 bytes (little-endian IEEE 754) without a type tag.
956    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
957        if *self == 0.0 {
958            writer.put_u8(TAG_NONE);
959        } else {
960            writer.put_u8(TAG_F32);
961            writer.put_f32_le(*self);
962        }
963        Ok(())
964    }
965}
966
967/// Decodes an `f32` from a scientific notation string, legacy binary format, or i128.
968///
969/// This decoder supports:
970/// - New string format (TAG_STRING_BASE..TAG_STRING_LONG)
971/// - Legacy binary format (TAG_F32, TAG_F64)
972/// - i128 cross-decode (TAG_ZERO..TAG_U128, TAG_NEGATIVE)
973impl Decoder for f32 {
974    fn decode(reader: &mut Bytes) -> Result<Self> {
975        if reader.remaining() == 0 {
976            return Err(EncoderError::InsufficientData);
977        }
978
979        // Peek at the tag to determine format
980        let tag = reader.chunk()[0];
981
982        // Try string format first (new format)
983        if (TAG_STRING_BASE..=TAG_STRING_LONG).contains(&tag) {
984            let s = String::decode(reader)?;
985            return s
986                .parse::<f32>()
987                .map_err(|e| EncoderError::Decode(format!("Invalid f32 string '{}': {}", s, e)));
988        }
989
990        // Try i128 cross-decode
991        if tag == TAG_NEGATIVE || (TAG_ZERO..=TAG_U128).contains(&tag) {
992            let i128_val = i128::decode(reader)?;
993            return Ok(i128_val as f32);
994        }
995
996        // Fall back to legacy binary format for backward compatibility
997        reader.advance(1); // consume the tag
998        if tag == TAG_F32 {
999            if reader.remaining() < 4 {
1000                return Err(EncoderError::InsufficientData);
1001            }
1002            let mut bytes = [0u8; 4];
1003            reader.copy_to_slice(&mut bytes);
1004            Ok(f32::from_le_bytes(bytes))
1005        } else if tag == TAG_F64 {
1006            if reader.remaining() < 8 {
1007                return Err(EncoderError::InsufficientData);
1008            }
1009            let mut bytes = [0u8; 8];
1010            reader.copy_to_slice(&mut bytes);
1011            Ok(f64::from_le_bytes(bytes) as f32)
1012        } else {
1013            Err(EncoderError::Decode(format!(
1014                "Expected f32 string ({}..={}), binary tag ({}, {}), or integer tag, got {}",
1015                TAG_STRING_BASE, TAG_STRING_LONG, TAG_F32, TAG_F64, tag
1016            )))
1017        }
1018    }
1019}
1020
1021impl Unpacker for f32 {
1022    /// Unpacks an `f32` from either TAG_NONE (0.0) or TAG_F32 + 4 bytes (little-endian IEEE 754).
1023    fn unpack(reader: &mut Bytes) -> Result<Self> {
1024        if reader.remaining() == 0 {
1025            return Err(EncoderError::InsufficientData);
1026        }
1027        let tag = reader.get_u8();
1028        if tag == TAG_NONE {
1029            Ok(0.0)
1030        } else if tag == TAG_F32 {
1031            if reader.remaining() < 4 {
1032                return Err(EncoderError::InsufficientData);
1033            }
1034            let mut bytes = [0u8; 4];
1035            reader.copy_to_slice(&mut bytes);
1036            Ok(f32::from_le_bytes(bytes))
1037        } else {
1038            Err(EncoderError::Decode(format!(
1039                "Expected f32 tag ({} or {}), got {}",
1040                TAG_NONE, TAG_F32, tag
1041            )))
1042        }
1043    }
1044}
1045
1046/// Encodes an `f64` as a scientific notation string.
1047///
1048/// Note: Pack/Unpack still uses binary format for efficiency.
1049/// The string format provides better compatibility and readability for Encode/Decode.
1050impl Encoder for f64 {
1051    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1052        let s = format!("{:e}", self);
1053        s.encode(writer)
1054    }
1055
1056    fn is_default(&self) -> bool {
1057        *self == 0.0
1058    }
1059}
1060
1061impl Packer for f64 {
1062    /// Packs an `f64` as TAG_NONE (for 0.0) or TAG_F64 + 8 bytes (little-endian IEEE 754).
1063    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1064        if *self == 0.0 {
1065            writer.put_u8(TAG_NONE);
1066        } else {
1067            writer.put_u8(TAG_F64);
1068            writer.put_f64_le(*self);
1069        }
1070        Ok(())
1071    }
1072}
1073
1074/// Decodes an `f64` from a scientific notation string, legacy binary format, or i128.
1075///
1076/// This decoder supports:
1077/// - New string format (TAG_STRING_BASE..TAG_STRING_LONG)
1078/// - Legacy binary format (TAG_F64)
1079/// - i128 cross-decode (TAG_ZERO..TAG_U128, TAG_NEGATIVE)
1080impl Decoder for f64 {
1081    fn decode(reader: &mut Bytes) -> Result<Self> {
1082        if reader.remaining() == 0 {
1083            return Err(EncoderError::InsufficientData);
1084        }
1085
1086        // Peek at the tag to determine format
1087        let tag = reader.chunk()[0];
1088
1089        // Try string format first (new format)
1090        if (TAG_STRING_BASE..=TAG_STRING_LONG).contains(&tag) {
1091            let s = String::decode(reader)?;
1092            return s
1093                .parse::<f64>()
1094                .map_err(|e| EncoderError::Decode(format!("Invalid f64 string '{}': {}", s, e)));
1095        }
1096
1097        // Try i128 cross-decode
1098        if tag == TAG_NEGATIVE || (TAG_ZERO..=TAG_U128).contains(&tag) {
1099            let i128_val = i128::decode(reader)?;
1100            return Ok(i128_val as f64);
1101        }
1102
1103        // Fall back to legacy binary format for backward compatibility
1104        reader.advance(1); // consume the tag
1105        if tag == TAG_F64 {
1106            if reader.remaining() < 8 {
1107                return Err(EncoderError::InsufficientData);
1108            }
1109            let mut bytes = [0u8; 8];
1110            reader.copy_to_slice(&mut bytes);
1111            Ok(f64::from_le_bytes(bytes))
1112        } else {
1113            Err(EncoderError::Decode(format!(
1114                "Expected f64 string ({}..={}), binary tag ({}), or integer tag, got {}. f32 to f64 cross-decoding is not supported due to precision concerns.",
1115                TAG_STRING_BASE, TAG_STRING_LONG, TAG_F64, tag
1116            )))
1117        }
1118    }
1119}
1120
1121impl Unpacker for f64 {
1122    /// Unpacks an `f64` from either TAG_NONE (0.0) or TAG_F64 + 8 bytes (little-endian IEEE 754).
1123    fn unpack(reader: &mut Bytes) -> Result<Self> {
1124        if reader.remaining() == 0 {
1125            return Err(EncoderError::InsufficientData);
1126        }
1127        let tag = reader.get_u8();
1128        if tag == TAG_NONE {
1129            Ok(0.0)
1130        } else if tag == TAG_F64 {
1131            if reader.remaining() < 8 {
1132                return Err(EncoderError::InsufficientData);
1133            }
1134            let mut bytes = [0u8; 8];
1135            reader.copy_to_slice(&mut bytes);
1136            Ok(f64::from_le_bytes(bytes))
1137        } else {
1138            Err(EncoderError::Decode(format!(
1139                "Expected f64 tag ({} or {}), got {}",
1140                TAG_NONE, TAG_F64, tag
1141            )))
1142        }
1143    }
1144}
1145
1146// --- String ---
1147/// Encodes a `String` as UTF-8 with a length prefix (short strings use a single tag byte).
1148impl Encoder for String {
1149    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1150        let len = self.len();
1151        let max_short = (TAG_STRING_LONG - TAG_STRING_BASE - 1) as usize;
1152        if len <= max_short {
1153            let tag = TAG_STRING_BASE + len as u8; // 9..=29
1154            writer.put_u8(tag);
1155            writer.put_slice(self.as_bytes());
1156        } else {
1157            writer.put_u8(TAG_STRING_LONG);
1158            len.encode(writer)?;
1159            writer.put_slice(self.as_bytes());
1160        }
1161        Ok(())
1162    }
1163
1164    fn is_default(&self) -> bool {
1165        self.is_empty()
1166    }
1167}
1168
1169impl Packer for String {
1170    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1171        self.encode(writer)
1172    }
1173}
1174
1175/// Decodes a `String` from the senax binary format.
1176impl Decoder for String {
1177    fn decode(reader: &mut Bytes) -> Result<Self> {
1178        if reader.remaining() == 0 {
1179            return Err(EncoderError::InsufficientData);
1180        }
1181        let tag = reader.get_u8();
1182        let len = if (TAG_STRING_BASE..TAG_STRING_LONG).contains(&tag) {
1183            (tag - TAG_STRING_BASE) as usize
1184        } else if tag == TAG_STRING_LONG {
1185            usize::decode(reader)?
1186        } else {
1187            return Err(EncoderError::Decode(format!(
1188                "Expected String tag ({}..={}), got {}",
1189                TAG_STRING_BASE, TAG_STRING_LONG, tag
1190            )));
1191        };
1192        if reader.remaining() < len {
1193            return Err(EncoderError::InsufficientData);
1194        }
1195        let mut bytes = vec![0u8; len];
1196        if len > 0 {
1197            reader.copy_to_slice(&mut bytes);
1198        }
1199        String::from_utf8(bytes).map_err(|e| EncoderError::Decode(e.to_string()))
1200    }
1201}
1202
1203impl Unpacker for String {
1204    fn unpack(reader: &mut Bytes) -> Result<Self> {
1205        Self::decode(reader)
1206    }
1207}
1208
1209// --- Option ---
1210/// Encodes an `Option<T>` as a tag byte followed by the value if present.
1211impl<T: Encoder> Encoder for Option<T> {
1212    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1213        match self {
1214            Some(value) => {
1215                writer.put_u8(TAG_SOME);
1216                value.encode(writer)
1217            }
1218            None => {
1219                writer.put_u8(TAG_NONE);
1220                Ok(())
1221            }
1222        }
1223    }
1224
1225    fn is_default(&self) -> bool {
1226        self.is_none()
1227    }
1228}
1229
1230impl<T: Packer> Packer for Option<T> {
1231    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1232        match self {
1233            Some(value) => {
1234                writer.put_u8(TAG_SOME);
1235                value.pack(writer)
1236            }
1237            None => {
1238                writer.put_u8(TAG_NONE);
1239                Ok(())
1240            }
1241        }
1242    }
1243}
1244
1245/// Decodes an `Option<T>` from the senax binary format.
1246impl<T: Decoder> Decoder for Option<T> {
1247    fn decode(reader: &mut Bytes) -> Result<Self> {
1248        if reader.remaining() == 0 {
1249            return Err(EncoderError::InsufficientData); // Not even a tag
1250        }
1251        let tag = reader.get_u8();
1252        match tag {
1253            TAG_NONE => Ok(None),
1254            TAG_SOME => Ok(Some(T::decode(reader)?)),
1255            other => Err(EncoderError::Decode(format!(
1256                "Expected Option tag ({} or {}), got {}",
1257                TAG_NONE, TAG_SOME, other
1258            ))),
1259        }
1260    }
1261}
1262
1263impl<T: Unpacker> Unpacker for Option<T> {
1264    fn unpack(reader: &mut Bytes) -> Result<Self> {
1265        if reader.remaining() == 0 {
1266            return Err(EncoderError::InsufficientData); // Not even a tag
1267        }
1268        let tag = reader.get_u8();
1269        match tag {
1270            TAG_NONE => Ok(None),
1271            TAG_SOME => Ok(Some(T::unpack(reader)?)),
1272            other => Err(EncoderError::Decode(format!(
1273                "Expected Option tag ({} or {}), got {}",
1274                TAG_NONE, TAG_SOME, other
1275            ))),
1276        }
1277    }
1278}
1279
1280// --- Vec<T> ---
1281/// Encodes a `Vec<T>` as a length-prefixed sequence.
1282impl<T: Encoder + 'static> Encoder for Vec<T> {
1283    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1284        encode_vec_length(self.len(), writer)?;
1285        for item in self {
1286            item.encode(writer)?;
1287        }
1288        Ok(())
1289    }
1290
1291    fn is_default(&self) -> bool {
1292        self.is_empty()
1293    }
1294}
1295
1296impl<T: Packer + 'static> Packer for Vec<T> {
1297    /// Packs a `Vec<T>` as a length-prefixed sequence.
1298    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1299        encode_vec_length(self.len(), writer)?;
1300        for item in self {
1301            item.pack(writer)?;
1302        }
1303        Ok(())
1304    }
1305}
1306
1307/// Decodes a `Vec<T>` from the senax binary format.
1308impl<T: Decoder + 'static> Decoder for Vec<T> {
1309    fn decode(reader: &mut Bytes) -> Result<Self> {
1310        let len = decode_vec_length(reader)?;
1311        let mut vec = Vec::with_capacity(len);
1312        for _ in 0..len {
1313            vec.push(T::decode(reader)?);
1314        }
1315        Ok(vec)
1316    }
1317}
1318
1319impl<T: Unpacker + 'static> Unpacker for Vec<T> {
1320    /// Unpacks a `Vec<T>` from the compact format.
1321    fn unpack(reader: &mut Bytes) -> Result<Self> {
1322        let len = decode_vec_length(reader)?;
1323        let mut vec = Vec::with_capacity(len);
1324        for _ in 0..len {
1325            vec.push(T::unpack(reader)?);
1326        }
1327        Ok(vec)
1328    }
1329}
1330
1331// --- Array ---
1332/// Encodes a fixed-size array as a length-prefixed sequence.
1333impl<T: Encoder, const N: usize> Encoder for [T; N] {
1334    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1335        encode_vec_length(N, writer)?;
1336        for item in self {
1337            item.encode(writer)?;
1338        }
1339        Ok(())
1340    }
1341
1342    fn is_default(&self) -> bool {
1343        self.iter().all(|item| item.is_default())
1344    }
1345}
1346
1347impl<T: Packer, const N: usize> Packer for [T; N] {
1348    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1349        encode_vec_length(N, writer)?;
1350        for item in self {
1351            item.pack(writer)?;
1352        }
1353        Ok(())
1354    }
1355}
1356
1357/// Decodes a fixed-size array from the senax binary format.
1358impl<T: Decoder, const N: usize> Decoder for [T; N] {
1359    fn decode(reader: &mut Bytes) -> Result<Self> {
1360        let len = decode_vec_length(reader)?;
1361        if len != N {
1362            return Err(EncoderError::Decode(format!(
1363                "Array length mismatch: expected {}, got {}",
1364                N, len
1365            )));
1366        }
1367        let mut array = Vec::with_capacity(N);
1368        for _ in 0..N {
1369            array.push(T::decode(reader)?);
1370        }
1371        array
1372            .try_into()
1373            .map_err(|_| EncoderError::Decode("Failed to convert Vec to array".to_string()))
1374    }
1375}
1376
1377impl<T: Unpacker, const N: usize> Unpacker for [T; N] {
1378    fn unpack(reader: &mut Bytes) -> Result<Self> {
1379        let len = decode_vec_length(reader)?;
1380        if len != N {
1381            return Err(EncoderError::Decode(format!(
1382                "Array length mismatch: expected {}, got {}",
1383                N, len
1384            )));
1385        }
1386        let mut array = Vec::with_capacity(N);
1387        for _ in 0..N {
1388            array.push(T::unpack(reader)?);
1389        }
1390        array
1391            .try_into()
1392            .map_err(|_| EncoderError::Decode("Failed to convert Vec to array".to_string()))
1393    }
1394}
1395
1396// --- Tuple ---
1397/// Implements encoding/decoding for tuples up to 10 elements.
1398///
1399/// Each tuple is encoded as a length-prefixed sequence of its elements.
1400macro_rules! impl_tuple {
1401    () => {
1402        impl Encoder for () {
1403
1404            fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1405                writer.put_u8(TAG_TUPLE);
1406                0usize.encode(writer)?;
1407                Ok(())
1408            }
1409
1410
1411            fn is_default(&self) -> bool {
1412                true
1413            }
1414        }
1415
1416        impl Packer for () {
1417
1418            fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1419                writer.put_u8(TAG_TUPLE);
1420                0usize.pack(writer)?;
1421                Ok(())
1422            }
1423        }
1424
1425        impl Decoder for () {
1426
1427            fn decode(reader: &mut Bytes) -> Result<Self> {
1428                if reader.remaining() == 0 {
1429                    return Err(EncoderError::InsufficientData);
1430                }
1431                let tag = reader.get_u8();
1432                if tag != TAG_TUPLE {
1433                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1434                }
1435                let len = usize::decode(reader)?;
1436                if len != 0 {
1437                    return Err(EncoderError::Decode(format!("Expected 0-tuple but got {}-tuple", len)));
1438                }
1439                Ok(())
1440            }
1441        }
1442
1443        impl Unpacker for () {
1444
1445            fn unpack(reader: &mut Bytes) -> Result<Self> {
1446                if reader.remaining() == 0 {
1447                    return Err(EncoderError::InsufficientData);
1448                }
1449                let tag = reader.get_u8();
1450                if tag != TAG_TUPLE {
1451                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1452                }
1453                let len = usize::decode(reader)?;
1454                if len != 0 {
1455                    return Err(EncoderError::Decode(format!("Expected 0-tuple but got {}-tuple", len)));
1456                }
1457                Ok(())
1458            }
1459        }
1460    };
1461    ($($T:ident: $idx:tt),+) => {
1462        impl<$($T: Encoder),+> Encoder for ($($T,)+) {
1463
1464            fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1465                writer.put_u8(TAG_TUPLE);
1466                let len = count_args!($($T),+);
1467                len.encode(writer)?;
1468                $(
1469                    self.$idx.encode(writer)?;
1470                )+
1471                Ok(())
1472            }
1473
1474
1475            fn is_default(&self) -> bool {
1476                $(self.$idx.is_default())&&+
1477            }
1478        }
1479
1480        impl<$($T: Packer),+> Packer for ($($T,)+) {
1481
1482            fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1483                writer.put_u8(TAG_TUPLE);
1484                let len = count_args!($($T),+);
1485                len.encode(writer)?;
1486                $(
1487                    self.$idx.pack(writer)?;
1488                )+
1489                Ok(())
1490            }
1491        }
1492
1493        impl<$($T: Decoder),+> Decoder for ($($T,)+) {
1494
1495            fn decode(reader: &mut Bytes) -> Result<Self> {
1496                if reader.remaining() == 0 {
1497                    return Err(EncoderError::InsufficientData);
1498                }
1499                let tag = reader.get_u8();
1500                if tag != TAG_TUPLE {
1501                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1502                }
1503                let len = usize::decode(reader)?;
1504                let expected_len = count_args!($($T),+);
1505                if len != expected_len {
1506                    return Err(EncoderError::Decode(format!("Expected {}-tuple but got {}-tuple", expected_len, len)));
1507                }
1508                Ok(($(
1509                    $T::decode(reader)?,
1510                )+))
1511            }
1512        }
1513
1514        impl<$($T: Unpacker),+> Unpacker for ($($T,)+) {
1515
1516            fn unpack(reader: &mut Bytes) -> Result<Self> {
1517                if reader.remaining() == 0 {
1518                    return Err(EncoderError::InsufficientData);
1519                }
1520                let tag = reader.get_u8();
1521                if tag != TAG_TUPLE {
1522                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1523                }
1524                let len = usize::decode(reader)?;
1525                let expected_len = count_args!($($T),+);
1526                if len != expected_len {
1527                    return Err(EncoderError::Decode(format!("Expected {}-tuple but got {}-tuple", expected_len, len)));
1528                }
1529                Ok(($(
1530                    $T::unpack(reader)?,
1531                )+))
1532            }
1533        }
1534    };
1535}
1536
1537macro_rules! count_args {
1538    () => { 0 };
1539    ($head:ident $(, $tail:ident)*) => { 1 + count_args!($($tail),*) };
1540}
1541
1542// Generate tuple implementations for 0 to 12 elements
1543impl_tuple!();
1544impl_tuple!(T0: 0);
1545impl_tuple!(T0: 0, T1: 1);
1546impl_tuple!(T0: 0, T1: 1, T2: 2);
1547impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
1548impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
1549impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
1550impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
1551impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
1552impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
1553impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
1554impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
1555impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);
1556
1557// --- Map (HashMap) ---
1558/// Encodes a map as a length-prefixed sequence of key-value pairs.
1559impl<K: Encoder, V: Encoder> Encoder for HashMap<K, V> {
1560    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1561        writer.put_u8(TAG_MAP);
1562        let len = self.len();
1563        len.encode(writer)?;
1564        for (k, v) in self {
1565            k.encode(writer)?;
1566            v.encode(writer)?;
1567        }
1568        Ok(())
1569    }
1570
1571    fn is_default(&self) -> bool {
1572        self.is_empty()
1573    }
1574}
1575
1576impl<K: Packer, V: Packer> Packer for HashMap<K, V> {
1577    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1578        writer.put_u8(TAG_MAP);
1579        let len = self.len();
1580        len.encode(writer)?;
1581        for (k, v) in self {
1582            k.pack(writer)?;
1583            v.pack(writer)?;
1584        }
1585        Ok(())
1586    }
1587}
1588
1589/// Decodes a map from the senax binary format.
1590impl<K: Decoder + Eq + std::hash::Hash, V: Decoder> Decoder for HashMap<K, V> {
1591    fn decode(reader: &mut Bytes) -> Result<Self> {
1592        let len = read_map_header(reader)?;
1593        let mut map = HashMap::with_capacity(len);
1594        for _ in 0..len {
1595            let k = K::decode(reader)?;
1596            let v = V::decode(reader)?;
1597            map.insert(k, v);
1598        }
1599        Ok(map)
1600    }
1601}
1602
1603impl<K: Unpacker + Eq + std::hash::Hash, V: Unpacker> Unpacker for HashMap<K, V> {
1604    fn unpack(reader: &mut Bytes) -> Result<Self> {
1605        let len = read_map_header(reader)?;
1606        let mut map = HashMap::with_capacity(len);
1607        for _ in 0..len {
1608            let k = K::unpack(reader)?;
1609            let v = V::unpack(reader)?;
1610            map.insert(k, v);
1611        }
1612        Ok(map)
1613    }
1614}
1615
1616/// Writes a `u32` in little-endian format without a tag.
1617///
1618/// This is used internally for struct/enum field/variant IDs.
1619pub fn write_u32_le(writer: &mut BytesMut, value: u32) -> Result<()> {
1620    writer.put_u32_le(value);
1621    Ok(())
1622}
1623
1624/// Reads a `u32` in little-endian format without a tag.
1625///
1626/// This is used internally for struct/enum field/variant IDs.
1627pub fn read_u32_le(reader: &mut Bytes) -> Result<u32> {
1628    if reader.remaining() < 4 {
1629        return Err(EncoderError::InsufficientData);
1630    }
1631    Ok(reader.get_u32_le())
1632}
1633
1634/// Writes a `u64` in little-endian format without a tag.
1635///
1636/// This is used internally for struct/enum field/variant IDs.
1637pub fn write_u64_le(writer: &mut BytesMut, value: u64) -> Result<()> {
1638    writer.put_u64_le(value);
1639    Ok(())
1640}
1641
1642/// Reads a `u64` in little-endian format without a tag.
1643///
1644/// This is used internally for struct/enum field/variant IDs.
1645pub fn read_u64_le(reader: &mut Bytes) -> Result<u64> {
1646    if reader.remaining() < 8 {
1647        return Err(EncoderError::InsufficientData);
1648    }
1649    Ok(reader.get_u64_le())
1650}
1651
1652/// Skips a value of any type in the senax binary format.
1653///
1654/// This is used for forward/backward compatibility when unknown fields/variants are encountered.
1655///
1656/// # Errors
1657/// Returns an error if the value cannot be skipped (e.g., insufficient data).
1658pub fn skip_value(reader: &mut Bytes) -> Result<()> {
1659    if reader.remaining() == 0 {
1660        return Err(EncoderError::InsufficientData);
1661    }
1662    let tag = reader.get_u8();
1663    match tag {
1664        TAG_ZERO..=TAG_U8_127 => Ok(()),
1665        TAG_U8 => {
1666            if reader.remaining() == 0 {
1667                return Err(EncoderError::InsufficientData);
1668            }
1669            reader.advance(1);
1670            Ok(())
1671        }
1672        TAG_U16 => {
1673            if reader.remaining() < 2 {
1674                return Err(EncoderError::InsufficientData);
1675            }
1676            reader.advance(2);
1677            Ok(())
1678        }
1679        TAG_U32 => {
1680            if reader.remaining() < 4 {
1681                return Err(EncoderError::InsufficientData);
1682            }
1683            reader.advance(4);
1684            Ok(())
1685        }
1686        TAG_U64 => {
1687            if reader.remaining() < 8 {
1688                return Err(EncoderError::InsufficientData);
1689            }
1690            reader.advance(8);
1691            Ok(())
1692        }
1693        TAG_U128 => {
1694            if reader.remaining() < 16 {
1695                return Err(EncoderError::InsufficientData);
1696            }
1697            reader.advance(16);
1698            Ok(())
1699        }
1700        TAG_F32 => {
1701            if reader.remaining() < 4 {
1702                return Err(EncoderError::InsufficientData);
1703            }
1704            reader.advance(4);
1705            Ok(())
1706        }
1707        TAG_F64 => {
1708            if reader.remaining() < 8 {
1709                return Err(EncoderError::InsufficientData);
1710            }
1711            reader.advance(8);
1712            Ok(())
1713        }
1714        TAG_STRING_BASE..=TAG_STRING_LONG => {
1715            let len = if tag < TAG_STRING_LONG {
1716                (tag - TAG_STRING_BASE) as usize
1717            } else {
1718                usize::decode(reader)?
1719            };
1720            if reader.remaining() < len {
1721                return Err(EncoderError::InsufficientData);
1722            }
1723            reader.advance(len);
1724            Ok(())
1725        }
1726        TAG_BINARY => {
1727            let len = usize::decode(reader)?;
1728            if reader.remaining() < len {
1729                return Err(EncoderError::InsufficientData);
1730            }
1731            reader.advance(len);
1732            Ok(())
1733        }
1734        TAG_ARRAY_VEC_SET_BASE..=TAG_ARRAY_VEC_SET_LONG => {
1735            let len = if tag < TAG_ARRAY_VEC_SET_LONG {
1736                (tag - TAG_ARRAY_VEC_SET_BASE) as usize
1737            } else {
1738                usize::decode(reader)?
1739            };
1740            for _ in 0..len {
1741                skip_value(reader)?;
1742            }
1743            Ok(())
1744        }
1745        TAG_STRUCT_UNIT => Ok(()),
1746        TAG_STRUCT_NAMED => {
1747            loop {
1748                let field_id = read_field_id_optimized(reader)?;
1749                if field_id == 0 {
1750                    break;
1751                }
1752                skip_value(reader)?;
1753            }
1754            Ok(())
1755        }
1756        TAG_STRUCT_UNNAMED => {
1757            let field_count = usize::decode(reader)?;
1758            for _ in 0..field_count {
1759                skip_value(reader)?;
1760            }
1761            Ok(())
1762        }
1763        TAG_ENUM => {
1764            let _variant_id = read_field_id_optimized(reader)?;
1765            Ok(())
1766        }
1767        TAG_ENUM_NAMED => {
1768            let _variant_id = read_field_id_optimized(reader)?;
1769            loop {
1770                let field_id = read_field_id_optimized(reader)?;
1771                if field_id == 0 {
1772                    break;
1773                }
1774                skip_value(reader)?;
1775            }
1776            Ok(())
1777        }
1778        TAG_ENUM_UNNAMED => {
1779            let _variant_id = read_field_id_optimized(reader)?;
1780            let field_count = usize::decode(reader)?;
1781            for _ in 0..field_count {
1782                skip_value(reader)?;
1783            }
1784            Ok(())
1785        }
1786        TAG_TUPLE => {
1787            let len = usize::decode(reader)?;
1788            for _ in 0..len {
1789                skip_value(reader)?;
1790            }
1791            Ok(())
1792        }
1793        TAG_MAP => {
1794            let len = usize::decode(reader)?;
1795            for _ in 0..len {
1796                skip_value(reader)?; // key
1797                skip_value(reader)?; // value
1798            }
1799            Ok(())
1800        }
1801        TAG_CHRONO_DATETIME => {
1802            if reader.remaining() < 12 {
1803                return Err(EncoderError::InsufficientData);
1804            } // Approximation for i64 + u32, could be more precise
1805            let _timestamp_seconds = i64::decode(reader)?;
1806            let _timestamp_nanos = u32::decode(reader)?;
1807            Ok(())
1808        }
1809        TAG_CHRONO_NAIVE_DATE => {
1810            if reader.remaining() < 8 {
1811                return Err(EncoderError::InsufficientData);
1812            } // Approximation for i64
1813            let _days_from_epoch = i64::decode(reader)?;
1814            Ok(())
1815        }
1816        TAG_CHRONO_NAIVE_TIME => {
1817            if reader.remaining() < 8 {
1818                return Err(EncoderError::InsufficientData);
1819            } // Approximation for u32 + u32
1820            let _seconds_from_midnight = u32::decode(reader)?;
1821            let _nanoseconds = u32::decode(reader)?;
1822            Ok(())
1823        }
1824        TAG_CHRONO_NAIVE_DATETIME => {
1825            if reader.remaining() < 12 {
1826                return Err(EncoderError::InsufficientData);
1827            } // Approximation for i64 + u32
1828            let _timestamp_seconds = i64::decode(reader)?;
1829            let _timestamp_nanos = u32::decode(reader)?;
1830            Ok(())
1831        }
1832        TAG_DECIMAL => {
1833            if reader.remaining() < 20 {
1834                return Err(EncoderError::InsufficientData);
1835            } // Approximation for i128 + u32
1836            let _mantissa = i128::decode(reader)?;
1837            let _scale = u32::decode(reader)?;
1838            Ok(())
1839        }
1840        TAG_UUID => {
1841            // Covers ULID as well
1842            if reader.remaining() < 16 {
1843                return Err(EncoderError::InsufficientData);
1844            }
1845            reader.advance(16);
1846            Ok(())
1847        }
1848        TAG_JSON_NULL => Ok(()),
1849        TAG_JSON_BOOL => Ok(()),
1850        TAG_JSON_NUMBER => {
1851            // Number has type marker + actual number
1852            if reader.remaining() == 0 {
1853                return Err(EncoderError::InsufficientData);
1854            }
1855            let number_type = reader.get_u8();
1856            match number_type {
1857                0 => {
1858                    u64::decode(reader)?;
1859                }
1860                1 => {
1861                    i64::decode(reader)?;
1862                }
1863                2 => {
1864                    f64::decode(reader)?;
1865                }
1866                _ => {
1867                    return Err(EncoderError::Decode(format!(
1868                        "Invalid JSON Number type marker: {}",
1869                        number_type
1870                    )));
1871                }
1872            }
1873            Ok(())
1874        }
1875        TAG_JSON_STRING => {
1876            // String uses regular string encoding
1877            String::decode(reader)?;
1878            Ok(())
1879        }
1880        TAG_JSON_ARRAY => {
1881            let len = usize::decode(reader)?;
1882            for _ in 0..len {
1883                skip_value(reader)?;
1884            }
1885            Ok(())
1886        }
1887        TAG_JSON_OBJECT => {
1888            let len = usize::decode(reader)?;
1889            for _ in 0..len {
1890                String::decode(reader)?; // key
1891                skip_value(reader)?; // value
1892            }
1893            Ok(())
1894        }
1895        TAG_NONE | TAG_SOME => {
1896            // These should have been handled by Option<T> decode or skip_value for T
1897            // For TAG_NONE, it's fine. For TAG_SOME, we need to skip the inner value.
1898            if tag == TAG_SOME {
1899                skip_value(reader)?;
1900            }
1901            Ok(())
1902        }
1903        _ => Err(EncoderError::Decode(format!(
1904            "skip_value: unknown or unhandled tag {}",
1905            tag
1906        ))),
1907    }
1908}
1909
1910// --- HashSet, BTreeSet, IndexSet ---
1911/// Encodes a set as a length-prefixed sequence of elements.
1912impl<T: Encoder + Eq + std::hash::Hash> Encoder for HashSet<T> {
1913    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1914        encode_vec_length(self.len(), writer)?;
1915        for v in self {
1916            v.encode(writer)?;
1917        }
1918        Ok(())
1919    }
1920
1921    fn is_default(&self) -> bool {
1922        self.is_empty()
1923    }
1924}
1925
1926impl<T: Packer + Eq + std::hash::Hash> Packer for HashSet<T> {
1927    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1928        encode_vec_length(self.len(), writer)?;
1929        for v in self {
1930            v.pack(writer)?;
1931        }
1932        Ok(())
1933    }
1934}
1935
1936/// Decodes a set from the senax binary format.
1937impl<T: Decoder + Eq + std::hash::Hash + 'static> Decoder for HashSet<T> {
1938    fn decode(reader: &mut Bytes) -> Result<Self> {
1939        let vec: Vec<T> = Vec::decode(reader)?;
1940        Ok(vec.into_iter().collect())
1941    }
1942}
1943
1944impl<T: Unpacker + Eq + std::hash::Hash + 'static> Unpacker for HashSet<T> {
1945    fn unpack(reader: &mut Bytes) -> Result<Self> {
1946        let vec: Vec<T> = Vec::unpack(reader)?;
1947        Ok(vec.into_iter().collect())
1948    }
1949}
1950// --- BTreeSet ---
1951impl<T: Encoder + Ord> Encoder for BTreeSet<T> {
1952    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1953        encode_vec_length(self.len(), writer)?;
1954        for v in self {
1955            v.encode(writer)?;
1956        }
1957        Ok(())
1958    }
1959
1960    fn is_default(&self) -> bool {
1961        self.is_empty()
1962    }
1963}
1964
1965impl<T: Packer + Ord> Packer for BTreeSet<T> {
1966    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
1967        encode_vec_length(self.len(), writer)?;
1968        for v in self {
1969            v.pack(writer)?;
1970        }
1971        Ok(())
1972    }
1973}
1974
1975impl<T: Decoder + Ord + 'static> Decoder for BTreeSet<T> {
1976    fn decode(reader: &mut Bytes) -> Result<Self> {
1977        let vec: Vec<T> = Vec::decode(reader)?;
1978        Ok(vec.into_iter().collect())
1979    }
1980}
1981
1982impl<T: Unpacker + Ord + 'static> Unpacker for BTreeSet<T> {
1983    fn unpack(reader: &mut Bytes) -> Result<Self> {
1984        let vec: Vec<T> = Vec::unpack(reader)?;
1985        Ok(vec.into_iter().collect())
1986    }
1987}
1988// --- BTreeMap ---
1989impl<K: Encoder + Ord, V: Encoder> Encoder for BTreeMap<K, V> {
1990    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1991        writer.put_u8(TAG_MAP);
1992        let len = self.len();
1993        len.encode(writer)?;
1994        for (k, v) in self {
1995            k.encode(writer)?;
1996            v.encode(writer)?;
1997        }
1998        Ok(())
1999    }
2000
2001    fn is_default(&self) -> bool {
2002        self.is_empty()
2003    }
2004}
2005
2006impl<K: Packer + Ord, V: Packer> Packer for BTreeMap<K, V> {
2007    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
2008        writer.put_u8(TAG_MAP);
2009        let len = self.len();
2010        len.encode(writer)?;
2011        for (k, v) in self {
2012            k.pack(writer)?;
2013            v.pack(writer)?;
2014        }
2015        Ok(())
2016    }
2017}
2018
2019impl<K: Decoder + Ord, V: Decoder> Decoder for BTreeMap<K, V> {
2020    fn decode(reader: &mut Bytes) -> Result<Self> {
2021        let len = read_map_header(reader)?;
2022        let mut map = BTreeMap::new();
2023        for _ in 0..len {
2024            let k = K::decode(reader)?;
2025            let v = V::decode(reader)?;
2026            map.insert(k, v);
2027        }
2028        Ok(map)
2029    }
2030}
2031
2032impl<K: Unpacker + Ord, V: Unpacker> Unpacker for BTreeMap<K, V> {
2033    fn unpack(reader: &mut Bytes) -> Result<Self> {
2034        let len = read_map_header(reader)?;
2035        let mut map = BTreeMap::new();
2036        for _ in 0..len {
2037            let k = K::unpack(reader)?;
2038            let v = V::unpack(reader)?;
2039            map.insert(k, v);
2040        }
2041        Ok(map)
2042    }
2043}
2044
2045// --- Bytes ---
2046impl Encoder for Bytes {
2047    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2048        writer.put_u8(TAG_BINARY);
2049        let len = self.len();
2050        len.encode(writer)?;
2051        writer.put_slice(self);
2052        Ok(())
2053    }
2054
2055    fn is_default(&self) -> bool {
2056        self.is_empty()
2057    }
2058}
2059
2060impl Packer for Bytes {
2061    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
2062        writer.put_u8(TAG_BINARY);
2063        let len = self.len();
2064        len.encode(writer)?;
2065        writer.put_slice(self);
2066        Ok(())
2067    }
2068}
2069
2070impl Decoder for Bytes {
2071    fn decode(reader: &mut Bytes) -> Result<Self> {
2072        if reader.remaining() == 0 {
2073            return Err(EncoderError::InsufficientData);
2074        }
2075        let tag = reader.get_u8();
2076        let len = if tag == TAG_BINARY {
2077            usize::decode(reader)?
2078        } else if (TAG_STRING_BASE..TAG_STRING_LONG).contains(&tag) {
2079            (tag - TAG_STRING_BASE) as usize
2080        } else if tag == TAG_STRING_LONG {
2081            usize::decode(reader)?
2082        } else {
2083            return Err(EncoderError::Decode(format!(
2084                "Expected Bytes tag ({} or {}..={}), got {}",
2085                TAG_BINARY, TAG_STRING_BASE, TAG_STRING_LONG, tag
2086            )));
2087        };
2088
2089        if reader.remaining() < len {
2090            return Err(EncoderError::InsufficientData);
2091        }
2092
2093        Ok(reader.split_to(len))
2094    }
2095}
2096
2097impl Unpacker for Bytes {
2098    fn unpack(reader: &mut Bytes) -> Result<Self> {
2099        if reader.remaining() == 0 {
2100            return Err(EncoderError::InsufficientData);
2101        }
2102        let tag = reader.get_u8();
2103        let len = if tag == TAG_BINARY {
2104            usize::unpack(reader)?
2105        } else if (TAG_STRING_BASE..TAG_STRING_LONG).contains(&tag) {
2106            (tag - TAG_STRING_BASE) as usize
2107        } else if tag == TAG_STRING_LONG {
2108            usize::unpack(reader)?
2109        } else {
2110            return Err(EncoderError::Decode(format!(
2111                "Expected Bytes tag ({} or {}..={}), got {}",
2112                TAG_BINARY, TAG_STRING_BASE, TAG_STRING_LONG, tag
2113            )));
2114        };
2115
2116        if reader.remaining() < len {
2117            return Err(EncoderError::InsufficientData);
2118        }
2119
2120        Ok(reader.split_to(len))
2121    }
2122}
2123
2124// --- Arc<T> ---
2125/// Encodes an `Arc<T>` by encoding the inner value.
2126impl<T: Encoder> Encoder for Arc<T> {
2127    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2128        (**self).encode(writer)
2129    }
2130
2131    fn is_default(&self) -> bool {
2132        T::is_default(self)
2133    }
2134}
2135
2136impl<T: Packer> Packer for Arc<T> {
2137    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
2138        (**self).pack(writer)
2139    }
2140}
2141
2142/// Decodes an `Arc<T>` by decoding the inner value and wrapping it in an Arc.
2143impl<T: Decoder> Decoder for Arc<T> {
2144    fn decode(reader: &mut Bytes) -> Result<Self> {
2145        Ok(Arc::new(T::decode(reader)?))
2146    }
2147}
2148
2149impl<T: Unpacker> Unpacker for Arc<T> {
2150    fn unpack(reader: &mut Bytes) -> Result<Self> {
2151        Ok(Arc::new(T::unpack(reader)?))
2152    }
2153}
2154
2155/// Writes a `u64` in little-endian format without a tag.
2156///
2157/// This is used internally for struct/enum field/variant IDs.
2158pub fn write_field_id_optimized(writer: &mut BytesMut, field_id: u64) -> Result<()> {
2159    if field_id == 0 {
2160        // Terminator
2161        writer.put_u8(0);
2162    } else if (1..=250).contains(&field_id) {
2163        // Small field ID: write as u8
2164        writer.put_u8(field_id as u8);
2165    } else {
2166        // Large field ID: write 255 marker then u64
2167        writer.put_u8(255);
2168        writer.put_u64_le(field_id);
2169    }
2170    Ok(())
2171}
2172
2173/// Reads a field ID using optimized encoding.
2174///
2175/// Returns Ok(0) for terminator, Ok(field_id) for valid field ID.
2176pub fn read_field_id_optimized(reader: &mut Bytes) -> Result<u64> {
2177    if reader.remaining() == 0 {
2178        return Err(EncoderError::InsufficientData);
2179    }
2180
2181    let first_byte = reader.get_u8();
2182
2183    if first_byte == 0 {
2184        // Terminator
2185        Ok(0)
2186    } else if first_byte == 255 {
2187        // Large field ID follows
2188        if reader.remaining() < 8 {
2189            return Err(EncoderError::InsufficientData);
2190        }
2191        Ok(reader.get_u64_le())
2192    } else {
2193        // Small field ID
2194        Ok(first_byte as u64)
2195    }
2196}
2197
2198/// Implementation for references - delegates to the referenced value
2199impl<T: Encoder> Encoder for &T {
2200    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2201        (*self).encode(writer)
2202    }
2203
2204    fn is_default(&self) -> bool {
2205        (*self).is_default()
2206    }
2207}
2208
2209impl<T: Packer> Packer for &T {
2210    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
2211        (*self).pack(writer)
2212    }
2213}
2214
2215// --- Box<T> ---
2216/// Encodes a `Box<T>` by encoding the inner value.
2217impl<T: Encoder> Encoder for Box<T> {
2218    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2219        (**self).encode(writer)
2220    }
2221
2222    fn is_default(&self) -> bool {
2223        T::is_default(self)
2224    }
2225}
2226
2227impl<T: Packer> Packer for Box<T> {
2228    fn pack(&self, writer: &mut BytesMut) -> Result<()> {
2229        (**self).pack(writer)
2230    }
2231}
2232
2233/// Decodes a `Box<T>` by decoding the inner value and wrapping it in a Box.
2234impl<T: Decoder> Decoder for Box<T> {
2235    fn decode(reader: &mut Bytes) -> Result<Self> {
2236        Ok(Box::new(T::decode(reader)?))
2237    }
2238}
2239
2240impl<T: Unpacker> Unpacker for Box<T> {
2241    fn unpack(reader: &mut Bytes) -> Result<Self> {
2242        Ok(Box::new(T::unpack(reader)?))
2243    }
2244}
2245
2246/// Encodes the length for array/vec/set format.
2247#[inline(never)]
2248pub(crate) fn encode_vec_length(len: usize, writer: &mut BytesMut) -> Result<()> {
2249    let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
2250    if len <= max_short {
2251        let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
2252        writer.put_u8(tag);
2253    } else {
2254        writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
2255        len.encode(writer)?;
2256    }
2257    Ok(())
2258}
2259
2260/// Decodes the length for array/vec/set format.
2261#[inline(never)]
2262pub(crate) fn decode_vec_length(reader: &mut Bytes) -> Result<usize> {
2263    if reader.remaining() == 0 {
2264        return Err(EncoderError::InsufficientData);
2265    }
2266    let tag = reader.get_u8();
2267    if (TAG_ARRAY_VEC_SET_BASE..TAG_ARRAY_VEC_SET_LONG).contains(&tag) {
2268        Ok((tag - TAG_ARRAY_VEC_SET_BASE) as usize)
2269    } else if tag == TAG_ARRAY_VEC_SET_LONG {
2270        usize::decode(reader)
2271    } else {
2272        Err(EncoderError::Decode(format!(
2273            "Expected Vec tag ({}..={}), got {}",
2274            TAG_ARRAY_VEC_SET_BASE, TAG_ARRAY_VEC_SET_LONG, tag
2275        )))
2276    }
2277}
2278
2279/// Reads and validates TAG_MAP, then returns the map length.
2280///
2281/// This helper function is used by all map-like types (HashMap, BTreeMap, etc.)
2282/// to avoid code duplication in decode/unpack implementations.
2283#[inline(never)]
2284pub(crate) fn read_map_header(reader: &mut Bytes) -> Result<usize> {
2285    if reader.remaining() == 0 {
2286        return Err(EncoderError::InsufficientData);
2287    }
2288    let tag = reader.get_u8();
2289    if tag != TAG_MAP {
2290        return Err(EncoderError::Decode(format!(
2291            "Expected Map tag ({}), got {}",
2292            TAG_MAP, tag
2293        )));
2294    }
2295    usize::decode(reader)
2296}