senax_encoder/
core.rs

1use crate::*;
2
3/// Type tags used in the senax binary format.
4///
5/// These tags are written as the first byte of each encoded value to identify its type and optimize decoding.
6/// Most users do not need to use these directly.
7///
8/// - Primitives, Option, String, Vec, arrays, maps, structs, enums, and feature types each have their own tag(s).
9/// - Tags are stable and part of the wire format.
10pub const TAG_NONE: u8 = 1;
11///< Option::None
12pub const TAG_SOME: u8 = 2;
13///< Option::Some
14pub const TAG_ZERO: u8 = 3;
15///< 0 for numbers, false for bool
16pub const TAG_ONE: u8 = 4;
17///< 1 for numbers, true for bool
18// 5-130: Values 2-127 (compact encoding for small unsigned integers)
19pub const TAG_U8_2_BASE: u8 = 5; // 2
20pub const TAG_U8_127: u8 = 130; // 127
21pub const TAG_U8: u8 = 131;
22///< u8 (full range)
23pub const TAG_U16: u8 = 132;
24///< u16
25pub const TAG_U32: u8 = 133;
26///< u32
27pub const TAG_U64: u8 = 134;
28///< u64
29pub const TAG_U128: u8 = 135;
30///< u128
31pub const TAG_NEGATIVE: u8 = 136;
32///< Negative signed integer (bit-inverted encoding)
33pub const TAG_F32: u8 = 137;
34///< f32
35pub const TAG_F64: u8 = 138;
36///< f64
37pub const TAG_STRING_BASE: u8 = 139;
38///< Short string (length in tag) - String, SmolStr
39pub const TAG_STRING_LONG: u8 = 180;
40///< Long string (length encoded) - String, SmolStr
41pub const TAG_BINARY: u8 = 181;
42///< Vec<u8> or Bytes
43pub const TAG_STRUCT_UNIT: u8 = 182;
44///< Unit struct
45pub const TAG_STRUCT_NAMED: u8 = 183;
46///< Named struct
47pub const TAG_STRUCT_UNNAMED: u8 = 184;
48///< Tuple struct
49pub const TAG_ENUM: u8 = 185;
50///< C-like enum (unit variants)
51pub const TAG_ENUM_NAMED: u8 = 186;
52///< Enum with named fields
53pub const TAG_ENUM_UNNAMED: u8 = 187;
54///< Enum with tuple fields
55pub const TAG_ARRAY_VEC_SET_BASE: u8 = 188;
56///< Short array/vec/set (length in tag) - includes HashSet, BTreeSet, IndexSet, FxHashSet, AHashSet
57pub const TAG_ARRAY_VEC_SET_LONG: u8 = 194;
58///< Long array/vec/set (length encoded) - includes HashSet, BTreeSet, IndexSet, FxHashSet, AHashSet
59pub const TAG_TUPLE: u8 = 195;
60///< Tuple
61pub const TAG_MAP: u8 = 196;
62///< Map (HashMap, BTreeMap, IndexMap, FxHashMap, AHashMap)
63pub const TAG_CHRONO_DATETIME: u8 = 197;
64///< chrono::DateTime
65pub const TAG_CHRONO_NAIVE_DATE: u8 = 198;
66///< chrono::NaiveDate
67pub const TAG_CHRONO_NAIVE_TIME: u8 = 199;
68///< chrono::NaiveTime
69pub const TAG_DECIMAL: u8 = 200;
70///< rust_decimal::Decimal
71pub const TAG_UUID: u8 = 201;
72///< uuid::Uuid, ulid::Ulid
73pub const TAG_JSON_NULL: u8 = 202;
74pub const TAG_JSON_BOOL: u8 = 203; // Uses existing TAG_ZERO/TAG_ONE for value
75pub const TAG_JSON_NUMBER: u8 = 204;
76pub const TAG_JSON_STRING: u8 = 205; // Uses existing string encoding
77pub const TAG_JSON_ARRAY: u8 = 206;
78pub const TAG_JSON_OBJECT: u8 = 207;
79
80// --- bool ---
81/// Encodes a `bool` as a single tag byte: `TAG_ZERO` for `false`, `TAG_ONE` for `true`.
82impl Encoder for bool {
83    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
84        let tag = if !*self { TAG_ZERO } else { TAG_ONE }; // 3: false, 4: true
85        writer.put_u8(tag);
86        Ok(())
87    }
88
89    fn is_default(&self) -> bool {
90        !(*self)
91    }
92}
93/// Decodes a `bool` from a single tag byte.
94///
95/// # Errors
96/// Returns an error if the tag is not `TAG_ZERO` or `TAG_ONE`.
97impl Decoder for bool {
98    fn decode(reader: &mut Bytes) -> Result<Self> {
99        if reader.remaining() == 0 {
100            return Err(EncoderError::InsufficientData);
101        }
102        let tag = reader.get_u8();
103        match tag {
104            TAG_ZERO => Ok(false),
105            TAG_ONE => Ok(true),
106            other => Err(EncoderError::Decode(format!(
107                "Expected bool tag ({} or {}), got {}",
108                TAG_ZERO, TAG_ONE, other
109            ))),
110        }
111    }
112}
113
114// --- Common decode functions ---
115/// Decodes a `u8` value from a tag and buffer.
116/// Used internally for compact integer decoding.
117///
118/// # Errors
119/// Returns an error if the tag is not valid for a `u8`.
120#[inline]
121fn decode_u8_from_tag(tag: u8, reader: &mut Bytes) -> Result<u8> {
122    if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
123        Ok(tag - TAG_ZERO)
124    } else if tag == TAG_U8 {
125        if reader.remaining() < 1 {
126            return Err(EncoderError::InsufficientData);
127        }
128        let stored_val = reader.get_u8();
129        stored_val.checked_add(128).ok_or_else(|| {
130            EncoderError::Decode(format!("u8 TAG_U8 value overflow: {}", stored_val))
131        })
132    } else {
133        Err(EncoderError::Decode(format!(
134            "Unexpected tag for u8: {}",
135            tag
136        )))
137    }
138}
139/// Decodes a `u16` value from a tag and buffer.
140/// Used internally for compact integer decoding.
141#[inline(never)]
142fn decode_u16_from_tag(tag: u8, reader: &mut Bytes) -> Result<u16> {
143    if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
144        Ok((tag - TAG_ZERO) as u16)
145    } else if tag == TAG_U8 {
146        if reader.remaining() < 1 {
147            return Err(EncoderError::InsufficientData);
148        }
149        Ok(reader.get_u8() as u16 + 128)
150    } else if tag == TAG_U16 {
151        if reader.remaining() < 2 {
152            return Err(EncoderError::InsufficientData);
153        }
154        Ok(reader.get_u16_le())
155    } else {
156        Err(EncoderError::Decode(format!(
157            "Unexpected tag for u16: {}",
158            tag
159        )))
160    }
161}
162/// Decodes a `u32` value from a tag and buffer.
163/// Used internally for compact integer decoding.
164#[inline]
165fn decode_u32_from_tag(tag: u8, reader: &mut Bytes) -> Result<u32> {
166    if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
167        Ok((tag - TAG_ZERO) as u32)
168    } else if tag == TAG_U8 {
169        if reader.remaining() < 1 {
170            return Err(EncoderError::InsufficientData);
171        }
172        Ok(reader.get_u8() as u32 + 128)
173    } else if tag == TAG_U16 {
174        if reader.remaining() < 2 {
175            return Err(EncoderError::InsufficientData);
176        }
177        Ok(reader.get_u16_le() as u32)
178    } else if tag == TAG_U32 {
179        if reader.remaining() < 4 {
180            return Err(EncoderError::InsufficientData);
181        }
182        Ok(reader.get_u32_le())
183    } else {
184        Err(EncoderError::Decode(format!(
185            "Unexpected tag for u32: {}",
186            tag
187        )))
188    }
189}
190/// Decodes a `u64` value from a tag and buffer.
191/// Used internally for compact integer decoding.
192#[inline]
193fn decode_u64_from_tag(tag: u8, reader: &mut Bytes) -> Result<u64> {
194    if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
195        Ok((tag - TAG_ZERO) as u64)
196    } else if tag == TAG_U8 {
197        if reader.remaining() < 1 {
198            return Err(EncoderError::InsufficientData);
199        }
200        Ok(reader.get_u8() as u64 + 128)
201    } else if tag == TAG_U16 {
202        if reader.remaining() < 2 {
203            return Err(EncoderError::InsufficientData);
204        }
205        Ok(reader.get_u16_le() as u64)
206    } else if tag == TAG_U32 {
207        if reader.remaining() < 4 {
208            return Err(EncoderError::InsufficientData);
209        }
210        Ok(reader.get_u32_le() as u64)
211    } else if tag == TAG_U64 {
212        if reader.remaining() < 8 {
213            return Err(EncoderError::InsufficientData);
214        }
215        Ok(reader.get_u64_le())
216    } else {
217        Err(EncoderError::Decode(format!(
218            "Unexpected tag for u64: {}",
219            tag
220        )))
221    }
222}
223/// Decodes a `u128` value from a tag and buffer.
224/// Used internally for compact integer decoding.
225#[inline(never)]
226fn decode_u128_from_tag(tag: u8, reader: &mut Bytes) -> Result<u128> {
227    if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
228        Ok((tag - TAG_ZERO) as u128)
229    } else if tag == TAG_U8 {
230        if reader.remaining() < 1 {
231            return Err(EncoderError::InsufficientData);
232        }
233        Ok(reader.get_u8() as u128 + 128)
234    } else if tag == TAG_U16 {
235        if reader.remaining() < 2 {
236            return Err(EncoderError::InsufficientData);
237        }
238        Ok(reader.get_u16_le() as u128)
239    } else if tag == TAG_U32 {
240        if reader.remaining() < 4 {
241            return Err(EncoderError::InsufficientData);
242        }
243        Ok(reader.get_u32_le() as u128)
244    } else if tag == TAG_U64 {
245        if reader.remaining() < 8 {
246            return Err(EncoderError::InsufficientData);
247        }
248        Ok(reader.get_u64_le() as u128)
249    } else if tag == TAG_U128 {
250        if reader.remaining() < 16 {
251            return Err(EncoderError::InsufficientData);
252        }
253        Ok(reader.get_u128_le())
254    } else {
255        Err(EncoderError::Decode(format!(
256            "Unexpected tag for u128: {}",
257            tag
258        )))
259    }
260}
261
262// --- Unsigned integer types ---
263/// Encodes unsigned integers using a compact variable-length format.
264///
265/// - Values 0/1 are encoded as `TAG_ZERO`/`TAG_ONE` (1 byte)
266/// - 2..=127 are encoded as a single tag byte (1 byte)
267/// - Larger values use `TAG_U8`, `TAG_U16`, `TAG_U32`, `TAG_U64`, or `TAG_U128` with the value in little-endian
268/// - The encoding is stable and compatible across platforms
269impl Encoder for u8 {
270    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
271        if *self <= 127 {
272            writer.put_u8(TAG_ZERO + *self);
273        } else {
274            writer.put_u8(TAG_U8);
275            writer.put_u8(*self - 128);
276        }
277        Ok(())
278    }
279
280    fn is_default(&self) -> bool {
281        *self == 0
282    }
283}
284/// Decodes a `u8` from the compact format.
285impl Decoder for u8 {
286    fn decode(reader: &mut Bytes) -> Result<Self> {
287        if reader.remaining() == 0 {
288            return Err(EncoderError::InsufficientData);
289        }
290        let tag = reader.get_u8();
291        decode_u8_from_tag(tag, reader)
292    }
293}
294/// See `u8` for format details.
295impl Encoder for u16 {
296    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
297        if *self <= 127 {
298            writer.put_u8(TAG_ZERO + (*self as u8));
299        } else if *self <= 255 + 128 {
300            writer.put_u8(TAG_U8);
301            writer.put_u8((*self - 128) as u8);
302        } else {
303            writer.put_u8(TAG_U16);
304            writer.put_u16_le(*self);
305        }
306        Ok(())
307    }
308
309    fn is_default(&self) -> bool {
310        *self == 0
311    }
312}
313impl Decoder for u16 {
314    fn decode(reader: &mut Bytes) -> Result<Self> {
315        if reader.remaining() == 0 {
316            return Err(EncoderError::InsufficientData);
317        }
318        let tag = reader.get_u8();
319        decode_u16_from_tag(tag, reader)
320    }
321}
322impl Encoder for u32 {
323    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
324        if *self <= 127 {
325            writer.put_u8(TAG_ZERO + (*self as u8));
326        } else if *self <= 255 + 128 {
327            writer.put_u8(TAG_U8);
328            writer.put_u8((*self - 128) as u8);
329        } else if *self <= 65535 {
330            writer.put_u8(TAG_U16);
331            writer.put_u16_le(*self as u16);
332        } else {
333            writer.put_u8(TAG_U32);
334            writer.put_u32_le(*self);
335        }
336        Ok(())
337    }
338
339    fn is_default(&self) -> bool {
340        *self == 0
341    }
342}
343impl Decoder for u32 {
344    fn decode(reader: &mut Bytes) -> Result<Self> {
345        if reader.remaining() == 0 {
346            return Err(EncoderError::InsufficientData);
347        }
348        let tag = reader.get_u8();
349        decode_u32_from_tag(tag, reader)
350    }
351}
352impl Encoder for u64 {
353    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
354        if *self <= 127 {
355            writer.put_u8(TAG_ZERO + (*self as u8));
356        } else if *self <= 255 + 128 {
357            writer.put_u8(TAG_U8);
358            writer.put_u8((*self - 128) as u8);
359        } else if *self <= 65535 {
360            writer.put_u8(TAG_U16);
361            writer.put_u16_le(*self as u16);
362        } else if *self <= 4294967295 {
363            writer.put_u8(TAG_U32);
364            writer.put_u32_le(*self as u32);
365        } else {
366            writer.put_u8(TAG_U64);
367            writer.put_u64_le(*self);
368        }
369        Ok(())
370    }
371
372    fn is_default(&self) -> bool {
373        *self == 0
374    }
375}
376impl Decoder for u64 {
377    fn decode(reader: &mut Bytes) -> Result<Self> {
378        if reader.remaining() == 0 {
379            return Err(EncoderError::InsufficientData);
380        }
381        let tag = reader.get_u8();
382        decode_u64_from_tag(tag, reader)
383    }
384}
385impl Encoder for u128 {
386    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
387        if *self <= 127 {
388            writer.put_u8(TAG_ZERO + (*self as u8));
389        } else if *self <= 255 + 128 {
390            writer.put_u8(TAG_U8);
391            writer.put_u8((*self - 128) as u8);
392        } else if *self <= 65535 {
393            writer.put_u8(TAG_U16);
394            writer.put_u16_le(*self as u16);
395        } else if *self <= 4294967295 {
396            writer.put_u8(TAG_U32);
397            writer.put_u32_le(*self as u32);
398        } else if *self <= 18446744073709551615 {
399            writer.put_u8(TAG_U64);
400            writer.put_u64_le(*self as u64);
401        } else {
402            writer.put_u8(TAG_U128);
403            writer.put_u128_le(*self);
404        }
405        Ok(())
406    }
407
408    fn is_default(&self) -> bool {
409        *self == 0
410    }
411}
412impl Decoder for u128 {
413    fn decode(reader: &mut Bytes) -> Result<Self> {
414        if reader.remaining() == 0 {
415            return Err(EncoderError::InsufficientData);
416        }
417        let tag = reader.get_u8();
418        decode_u128_from_tag(tag, reader)
419    }
420}
421/// Encodes `usize` using the platform's pointer width, but always as a portable integer format.
422impl Encoder for usize {
423    #[inline]
424    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
425        if usize::BITS == u64::BITS {
426            let v = *self as u64;
427            v.encode(writer)
428        } else if usize::BITS == u32::BITS {
429            let v = *self as u32;
430            v.encode(writer)
431        } else if usize::BITS == u16::BITS {
432            let v = *self as u16;
433            v.encode(writer)
434        } else {
435            let v = *self as u128;
436            v.encode(writer)
437        }
438    }
439
440    fn is_default(&self) -> bool {
441        *self == 0
442    }
443}
444impl Decoder for usize {
445    fn decode(reader: &mut Bytes) -> Result<Self> {
446        if reader.remaining() == 0 {
447            return Err(EncoderError::InsufficientData);
448        }
449        let tag = reader.get_u8();
450        if usize::BITS == u64::BITS {
451            Ok(decode_u64_from_tag(tag, reader)? as usize)
452        } else if usize::BITS == u32::BITS {
453            Ok(decode_u32_from_tag(tag, reader)? as usize)
454        } else if usize::BITS == u16::BITS {
455            Ok(decode_u16_from_tag(tag, reader)? as usize)
456        } else {
457            Ok(decode_u128_from_tag(tag, reader)? as usize)
458        }
459    }
460}
461
462// --- Signed integer types (bit-inverted encoding) ---
463/// Encodes signed integers using bit-inverted encoding for negative values.
464///
465/// - Non-negative values (>= 0) are encoded as unsigned integers
466/// - Negative values use `TAG_NEGATIVE` and bit-inverted encoding
467impl Encoder for i8 {
468    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
469        if *self >= 0 {
470            (*self as u8).encode(writer)
471        } else {
472            writer.put_u8(TAG_NEGATIVE);
473            let inv = !(*self as u8);
474            inv.encode(writer)
475        }
476    }
477
478    fn is_default(&self) -> bool {
479        *self == 0
480    }
481}
482/// Decodes a `i8` from the bit-inverted encoding.
483///
484/// # Errors
485/// Returns an error if the tag is not valid for an `i8`.
486impl Decoder for i8 {
487    fn decode(reader: &mut Bytes) -> Result<Self> {
488        if reader.remaining() == 0 {
489            return Err(EncoderError::InsufficientData);
490        }
491        let tag = reader.get_u8();
492        match tag {
493            TAG_NEGATIVE => {
494                let inv = u8::decode(reader)?;
495                Ok(!inv as i8)
496            }
497            t => {
498                let v = decode_u8_from_tag(t, reader)?;
499                if v > i8::MAX as u8 {
500                    return Err(EncoderError::Decode(format!(
501                        "Value {} too large for i8",
502                        v
503                    )));
504                }
505                Ok(v as i8)
506            }
507        }
508    }
509}
510// i16
511impl Encoder for i16 {
512    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
513        if *self >= 0 {
514            (*self as u16).encode(writer)
515        } else {
516            writer.put_u8(TAG_NEGATIVE);
517            let inv = !(*self as u16);
518            inv.encode(writer)
519        }
520    }
521
522    fn is_default(&self) -> bool {
523        *self == 0
524    }
525}
526impl Decoder for i16 {
527    fn decode(reader: &mut Bytes) -> Result<Self> {
528        if reader.remaining() == 0 {
529            return Err(EncoderError::InsufficientData);
530        }
531        let tag = reader.get_u8();
532        match tag {
533            TAG_NEGATIVE => {
534                let inv = u16::decode(reader)?;
535                Ok(!inv as i16)
536            }
537            t => {
538                let v = decode_u16_from_tag(t, reader)?;
539                if v > i16::MAX as u16 {
540                    return Err(EncoderError::Decode(format!(
541                        "Value {} too large for i16",
542                        v
543                    )));
544                }
545                Ok(v as i16)
546            }
547        }
548    }
549}
550// i32
551impl Encoder for i32 {
552    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
553        if *self >= 0 {
554            (*self as u32).encode(writer)
555        } else {
556            writer.put_u8(TAG_NEGATIVE);
557            let inv = !(*self as u32);
558            inv.encode(writer)
559        }
560    }
561
562    fn is_default(&self) -> bool {
563        *self == 0
564    }
565}
566impl Decoder for i32 {
567    fn decode(reader: &mut Bytes) -> Result<Self> {
568        if reader.remaining() == 0 {
569            return Err(EncoderError::InsufficientData);
570        }
571        let tag = reader.get_u8();
572        match tag {
573            TAG_NEGATIVE => {
574                let inv = u32::decode(reader)?;
575                Ok(!inv as i32)
576            }
577            t => {
578                let v = decode_u32_from_tag(t, reader)?;
579                if v > i32::MAX as u32 {
580                    return Err(EncoderError::Decode(format!(
581                        "Value {} too large for i32",
582                        v
583                    )));
584                }
585                Ok(v as i32)
586            }
587        }
588    }
589}
590// i64
591impl Encoder for i64 {
592    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
593        if *self >= 0 {
594            (*self as u64).encode(writer)
595        } else {
596            writer.put_u8(TAG_NEGATIVE);
597            let inv = !(*self as u64);
598            inv.encode(writer)
599        }
600    }
601
602    fn is_default(&self) -> bool {
603        *self == 0
604    }
605}
606impl Decoder for i64 {
607    fn decode(reader: &mut Bytes) -> Result<Self> {
608        if reader.remaining() == 0 {
609            return Err(EncoderError::InsufficientData);
610        }
611        let tag = reader.get_u8();
612        match tag {
613            TAG_NEGATIVE => {
614                let inv = u64::decode(reader)?;
615                Ok(!inv as i64)
616            }
617            t => {
618                let v = decode_u64_from_tag(t, reader)?;
619                if v > i64::MAX as u64 {
620                    return Err(EncoderError::Decode(format!(
621                        "Value {} too large for i64",
622                        v
623                    )));
624                }
625                Ok(v as i64)
626            }
627        }
628    }
629}
630// i128
631impl Encoder for i128 {
632    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
633        if *self >= 0 {
634            (*self as u128).encode(writer)
635        } else {
636            writer.put_u8(TAG_NEGATIVE);
637            let inv = !(*self as u128);
638            inv.encode(writer)
639        }
640    }
641
642    fn is_default(&self) -> bool {
643        *self == 0
644    }
645}
646impl Decoder for i128 {
647    fn decode(reader: &mut Bytes) -> Result<Self> {
648        if reader.remaining() == 0 {
649            return Err(EncoderError::InsufficientData);
650        }
651        let tag = reader.get_u8();
652        match tag {
653            TAG_NEGATIVE => {
654                let inv = u128::decode(reader)?;
655                Ok(!inv as i128)
656            }
657            t => {
658                let v = decode_u128_from_tag(t, reader)?;
659                if v > i128::MAX as u128 {
660                    return Err(EncoderError::Decode(format!(
661                        "Value {} too large for i128",
662                        v
663                    )));
664                }
665                Ok(v as i128)
666            }
667        }
668    }
669}
670// isize
671impl Encoder for isize {
672    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
673        if usize::BITS == u64::BITS {
674            let v = *self as i64;
675            v.encode(writer)
676        } else if usize::BITS == u32::BITS {
677            let v = *self as i32;
678            v.encode(writer)
679        } else if usize::BITS == u16::BITS {
680            let v = *self as i16;
681            v.encode(writer)
682        } else {
683            let v = *self as i128;
684            v.encode(writer)
685        }
686    }
687
688    fn is_default(&self) -> bool {
689        *self == 0
690    }
691}
692impl Decoder for isize {
693    fn decode(reader: &mut Bytes) -> Result<Self> {
694        if reader.remaining() == 0 {
695            return Err(EncoderError::InsufficientData);
696        }
697        if usize::BITS == u64::BITS {
698            Ok(i64::decode(reader)? as isize)
699        } else if usize::BITS == u32::BITS {
700            Ok(i32::decode(reader)? as isize)
701        } else if usize::BITS == u16::BITS {
702            Ok(i16::decode(reader)? as isize)
703        } else {
704            Ok(i128::decode(reader)? as isize)
705        }
706    }
707}
708
709// --- f32/f64 ---
710/// Encodes an `f32` as a tag and 4 bytes (little-endian IEEE 754).
711impl Encoder for f32 {
712    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
713        writer.put_u8(TAG_F32);
714        writer.put_f32_le(*self);
715        Ok(())
716    }
717
718    fn is_default(&self) -> bool {
719        *self == 0.0
720    }
721}
722/// Decodes an `f32` from either 4 or 8 bytes (accepts f64 for compatibility with precision loss).
723impl Decoder for f32 {
724    fn decode(reader: &mut Bytes) -> Result<Self> {
725        if reader.remaining() == 0 {
726            return Err(EncoderError::InsufficientData);
727        }
728        let tag = reader.get_u8();
729        if tag == TAG_F32 {
730            if reader.remaining() < 4 {
731                return Err(EncoderError::InsufficientData);
732            }
733            let mut bytes = [0u8; 4];
734            reader.copy_to_slice(&mut bytes);
735            Ok(f32::from_le_bytes(bytes))
736        } else if tag == TAG_F64 {
737            if reader.remaining() < 8 {
738                return Err(EncoderError::InsufficientData);
739            }
740            let mut bytes = [0u8; 8];
741            reader.copy_to_slice(&mut bytes);
742            Ok(f64::from_le_bytes(bytes) as f32)
743        } else {
744            Err(EncoderError::Decode(format!(
745                "Expected f32/f64 tag ({} or {}), got {}",
746                TAG_F32, TAG_F64, tag
747            )))
748        }
749    }
750}
751/// Encodes an `f64` as a tag and 8 bytes (little-endian IEEE 754).
752impl Encoder for f64 {
753    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
754        writer.put_u8(TAG_F64);
755        writer.put_f64_le(*self);
756        Ok(())
757    }
758
759    fn is_default(&self) -> bool {
760        *self == 0.0
761    }
762}
763/// Decodes an `f64` from 8 bytes (f32 cross-decoding not supported).
764impl Decoder for f64 {
765    fn decode(reader: &mut Bytes) -> Result<Self> {
766        if reader.remaining() == 0 {
767            return Err(EncoderError::InsufficientData);
768        }
769        let tag = reader.get_u8();
770        if tag == TAG_F64 {
771            if reader.remaining() < 8 {
772                return Err(EncoderError::InsufficientData);
773            }
774            let mut bytes = [0u8; 8];
775            reader.copy_to_slice(&mut bytes);
776            Ok(f64::from_le_bytes(bytes))
777        } else {
778            Err(EncoderError::Decode(format!(
779                "Expected f64 tag ({}), got {}. f32 to f64 cross-decoding is not supported due to precision concerns.",
780                TAG_F64, tag
781            )))
782        }
783    }
784}
785
786// --- String ---
787/// Encodes a `String` as UTF-8 with a length prefix (short strings use a single tag byte).
788impl Encoder for String {
789    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
790        let len = self.len();
791        let max_short = (TAG_STRING_LONG - TAG_STRING_BASE - 1) as usize;
792        if len <= max_short {
793            let tag = TAG_STRING_BASE + len as u8; // 9..=29
794            writer.put_u8(tag);
795            writer.put_slice(self.as_bytes());
796        } else {
797            writer.put_u8(TAG_STRING_LONG);
798            len.encode(writer)?;
799            writer.put_slice(self.as_bytes());
800        }
801        Ok(())
802    }
803
804    fn is_default(&self) -> bool {
805        self.is_empty()
806    }
807}
808/// Decodes a `String` from the senax binary format.
809impl Decoder for String {
810    fn decode(reader: &mut Bytes) -> Result<Self> {
811        if reader.remaining() == 0 {
812            return Err(EncoderError::InsufficientData);
813        }
814        let tag = reader.get_u8();
815        let len = if (TAG_STRING_BASE..TAG_STRING_LONG).contains(&tag) {
816            (tag - TAG_STRING_BASE) as usize
817        } else if tag == TAG_STRING_LONG {
818            usize::decode(reader)?
819        } else {
820            return Err(EncoderError::Decode(format!(
821                "Expected String tag ({}..={}), got {}",
822                TAG_STRING_BASE, TAG_STRING_LONG, tag
823            )));
824        };
825        if reader.remaining() < len {
826            return Err(EncoderError::InsufficientData);
827        }
828        let mut bytes = vec![0u8; len];
829        if len > 0 {
830            reader.copy_to_slice(&mut bytes);
831        }
832        String::from_utf8(bytes).map_err(|e| EncoderError::Decode(e.to_string()))
833    }
834}
835
836// --- Option ---
837/// Encodes an `Option<T>` as a tag byte followed by the value if present.
838impl<T: Encoder> Encoder for Option<T> {
839    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
840        match self {
841            Some(value) => {
842                writer.put_u8(TAG_SOME);
843                value.encode(writer)
844            }
845            None => {
846                writer.put_u8(TAG_NONE);
847                Ok(())
848            }
849        }
850    }
851
852    fn is_default(&self) -> bool {
853        self.is_none()
854    }
855}
856/// Decodes an `Option<T>` from the senax binary format.
857impl<T: Decoder> Decoder for Option<T> {
858    fn decode(reader: &mut Bytes) -> Result<Self> {
859        if reader.remaining() == 0 {
860            return Err(EncoderError::InsufficientData); // Not even a tag
861        }
862        let tag = reader.get_u8();
863        match tag {
864            TAG_NONE => Ok(None),
865            TAG_SOME => {
866                if reader.remaining() == 0 {
867                    // Check before T::decode if only TAG_SOME was present
868                    return Err(EncoderError::InsufficientData);
869                }
870                Ok(Some(T::decode(reader)?))
871            }
872            other => Err(EncoderError::Decode(format!(
873                "Expected Option tag ({} or {}), got {}",
874                TAG_NONE, TAG_SOME, other
875            ))),
876        }
877    }
878}
879
880// --- Vec<T> ---
881/// Encodes a `Vec<T>` as a length-prefixed sequence. `Vec<u8>` is optimized as binary.
882impl<T: Encoder + 'static> Encoder for Vec<T> {
883    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
884        if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
885            // Safety: We've verified T is u8, so this cast is safe
886            let vec_u8 = unsafe { &*(self as *const Vec<T> as *const Vec<u8>) };
887            encode_vec_u8(vec_u8, writer)
888        } else {
889            encode_vec_length(self.len(), writer)?;
890            for item in self {
891                item.encode(writer)?;
892            }
893            Ok(())
894        }
895    }
896
897    fn is_default(&self) -> bool {
898        self.is_empty()
899    }
900}
901/// Decodes a `Vec<T>` from the senax binary format.
902impl<T: Decoder + 'static> Decoder for Vec<T> {
903    fn decode(reader: &mut Bytes) -> Result<Self> {
904        if reader.remaining() == 0 {
905            return Err(EncoderError::InsufficientData);
906        }
907        let tag = reader.get_u8();
908
909        if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
910            if tag == TAG_BINARY {
911                let vec_u8 = decode_vec_u8(reader)?;
912                // Safety: We've verified T is u8, so this cast is safe
913                let ptr = vec_u8.as_ptr() as *mut T;
914                let len = vec_u8.len();
915                let cap = vec_u8.capacity();
916                std::mem::forget(vec_u8);
917                unsafe { Ok(Vec::from_raw_parts(ptr, len, cap)) }
918            } else {
919                Err(EncoderError::Decode(format!(
920                    "Expected Vec<u8> tag ({}), got {}",
921                    TAG_BINARY, tag
922                )))
923            }
924        } else {
925            let len = decode_vec_length(tag, reader)?;
926            let mut vec = Vec::with_capacity(len);
927            for _ in 0..len {
928                vec.push(T::decode(reader)?);
929            }
930            Ok(vec)
931        }
932    }
933}
934
935// --- Array ---
936/// Encodes a fixed-size array as a length-prefixed sequence.
937impl<T: Encoder, const N: usize> Encoder for [T; N] {
938    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
939        encode_vec_length(N, writer)?;
940        for item in self {
941            item.encode(writer)?;
942        }
943        Ok(())
944    }
945
946    fn is_default(&self) -> bool {
947        self.iter().all(|item| item.is_default())
948    }
949}
950/// Decodes a fixed-size array from the senax binary format.
951impl<T: Decoder, const N: usize> Decoder for [T; N] {
952    fn decode(reader: &mut Bytes) -> Result<Self> {
953        if reader.remaining() == 0 {
954            return Err(EncoderError::InsufficientData);
955        }
956        let tag = reader.get_u8();
957        let len = decode_vec_length(tag, reader)?;
958        if len != N {
959            return Err(EncoderError::Decode(format!(
960                "Array length mismatch: expected {}, got {}",
961                N, len
962            )));
963        }
964        let mut array = Vec::with_capacity(N);
965        for _ in 0..N {
966            array.push(T::decode(reader)?);
967        }
968        array
969            .try_into()
970            .map_err(|_| EncoderError::Decode("Failed to convert Vec to array".to_string()))
971    }
972}
973
974// --- Tuple ---
975/// Implements encoding/decoding for tuples up to 10 elements.
976///
977/// Each tuple is encoded as a length-prefixed sequence of its elements.
978macro_rules! impl_tuple {
979    () => {
980impl Encoder for () {
981    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
982                writer.put_u8(TAG_TUPLE);
983                0usize.encode(writer)?;
984        Ok(())
985    }
986
987    fn is_default(&self) -> bool {
988        true
989    }
990}
991impl Decoder for () {
992    fn decode(reader: &mut Bytes) -> Result<Self> {
993        if reader.remaining() == 0 {
994            return Err(EncoderError::InsufficientData);
995        }
996        let tag = reader.get_u8();
997                if tag != TAG_TUPLE {
998                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
999                }
1000                let len = usize::decode(reader)?;
1001                if len != 0 {
1002                    return Err(EncoderError::Decode(format!("Expected 0-tuple but got {}-tuple", len)));
1003        }
1004        Ok(())
1005    }
1006}
1007    };
1008    ($($T:ident : $idx:tt),+) => {
1009        impl<$($T: Encoder),+> Encoder for ($($T,)+) {
1010    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1011                writer.put_u8(TAG_TUPLE);
1012                let count = count_args!($($T),+);
1013                count.encode(writer)?;
1014                $(
1015                    self.$idx.encode(writer)?;
1016                )+
1017        Ok(())
1018    }
1019
1020    fn is_default(&self) -> bool {
1021        $(self.$idx.is_default())&&+
1022    }
1023}
1024        impl<$($T: Decoder),+> Decoder for ($($T,)+) {
1025    fn decode(reader: &mut Bytes) -> Result<Self> {
1026        if reader.remaining() == 0 {
1027            return Err(EncoderError::InsufficientData);
1028        }
1029        let tag = reader.get_u8();
1030                if tag != TAG_TUPLE {
1031                    return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1032                }
1033                let len = usize::decode(reader)?;
1034                let expected_len = count_args!($($T),+);
1035                if len != expected_len {
1036                    return Err(EncoderError::Decode(format!("Expected {}-tuple but got {}-tuple", expected_len, len)));
1037                }
1038                Ok(($(
1039                    $T::decode(reader)?,
1040                )+))
1041            }
1042        }
1043    };
1044}
1045
1046macro_rules! count_args {
1047    () => { 0 };
1048    ($head:ident $(, $tail:ident)*) => { 1 + count_args!($($tail),*) };
1049}
1050
1051// Generate tuple implementations for 0 to 12 elements
1052impl_tuple!();
1053impl_tuple!(T0: 0);
1054impl_tuple!(T0: 0, T1: 1);
1055impl_tuple!(T0: 0, T1: 1, T2: 2);
1056impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
1057impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
1058impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
1059impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
1060impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
1061impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
1062impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
1063impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
1064impl_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);
1065
1066// --- Map (HashMap) ---
1067/// Encodes a map as a length-prefixed sequence of key-value pairs.
1068impl<K: Encoder, V: Encoder> Encoder for HashMap<K, V> {
1069    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1070        writer.put_u8(TAG_MAP);
1071        let len = self.len();
1072        len.encode(writer)?;
1073        for (k, v) in self {
1074            k.encode(writer)?;
1075            v.encode(writer)?;
1076        }
1077        Ok(())
1078    }
1079
1080    fn is_default(&self) -> bool {
1081        self.is_empty()
1082    }
1083}
1084/// Decodes a map from the senax binary format.
1085impl<K: Decoder + Eq + std::hash::Hash, V: Decoder> Decoder for HashMap<K, V> {
1086    fn decode(reader: &mut Bytes) -> Result<Self> {
1087        if reader.remaining() == 0 {
1088            return Err(EncoderError::InsufficientData);
1089        }
1090        let tag = reader.get_u8();
1091        if tag != TAG_MAP {
1092            return Err(EncoderError::Decode(format!(
1093                "Expected Map tag ({}), got {}",
1094                TAG_MAP, tag
1095            )));
1096        }
1097        let len = usize::decode(reader)?;
1098        let mut map = HashMap::with_capacity(len);
1099        for _ in 0..len {
1100            let k = K::decode(reader)?;
1101            let v = V::decode(reader)?;
1102            map.insert(k, v);
1103        }
1104        Ok(map)
1105    }
1106}
1107// --- Enum ---
1108// Enum is handled by proc-macro with tag TAG_ENUM (see proc-macro side)
1109// 32: Enum
1110
1111/// Writes a `u32` in little-endian format without a tag.
1112///
1113/// This is used internally for struct/enum field/variant IDs.
1114pub fn write_u32_le(writer: &mut BytesMut, value: u32) -> Result<()> {
1115    writer.put_u32_le(value);
1116    Ok(())
1117}
1118
1119/// Reads a `u32` in little-endian format without a tag.
1120///
1121/// This is used internally for struct/enum field/variant IDs.
1122pub fn read_u32_le(reader: &mut Bytes) -> Result<u32> {
1123    if reader.remaining() < 4 {
1124        return Err(EncoderError::InsufficientData);
1125    }
1126    Ok(reader.get_u32_le())
1127}
1128
1129/// Writes a `u64` in little-endian format without a tag.
1130///
1131/// This is used internally for struct/enum field/variant IDs.
1132pub fn write_u64_le(writer: &mut BytesMut, value: u64) -> Result<()> {
1133    writer.put_u64_le(value);
1134    Ok(())
1135}
1136
1137/// Reads a `u64` in little-endian format without a tag.
1138///
1139/// This is used internally for struct/enum field/variant IDs.
1140pub fn read_u64_le(reader: &mut Bytes) -> Result<u64> {
1141    if reader.remaining() < 8 {
1142        return Err(EncoderError::InsufficientData);
1143    }
1144    Ok(reader.get_u64_le())
1145}
1146
1147/// Skips a value of any type in the senax binary format.
1148///
1149/// This is used for forward/backward compatibility when unknown fields/variants are encountered.
1150///
1151/// # Errors
1152/// Returns an error if the value cannot be skipped (e.g., insufficient data).
1153pub fn skip_value(reader: &mut Bytes) -> Result<()> {
1154    if reader.remaining() == 0 {
1155        return Err(EncoderError::InsufficientData);
1156    }
1157    let tag = reader.get_u8();
1158    match tag {
1159        TAG_ZERO | TAG_ONE => Ok(()),
1160        TAG_U8_2_BASE..=TAG_U8_127 => Ok(()),
1161        TAG_U8 => {
1162            if reader.remaining() < 1 {
1163                return Err(EncoderError::InsufficientData);
1164            }
1165            reader.advance(1);
1166            Ok(())
1167        }
1168        TAG_U16 => {
1169            if reader.remaining() < 2 {
1170                return Err(EncoderError::InsufficientData);
1171            }
1172            reader.advance(2);
1173            Ok(())
1174        }
1175        TAG_U32 => {
1176            if reader.remaining() < 4 {
1177                return Err(EncoderError::InsufficientData);
1178            }
1179            reader.advance(4);
1180            Ok(())
1181        }
1182        TAG_U64 => {
1183            if reader.remaining() < 8 {
1184                return Err(EncoderError::InsufficientData);
1185            }
1186            reader.advance(8);
1187            Ok(())
1188        }
1189        TAG_U128 => {
1190            if reader.remaining() < 16 {
1191                return Err(EncoderError::InsufficientData);
1192            }
1193            reader.advance(16);
1194            Ok(())
1195        }
1196        TAG_F32 => {
1197            if reader.remaining() < 4 {
1198                return Err(EncoderError::InsufficientData);
1199            }
1200            reader.advance(4);
1201            Ok(())
1202        }
1203        TAG_F64 => {
1204            if reader.remaining() < 8 {
1205                return Err(EncoderError::InsufficientData);
1206            }
1207            reader.advance(8);
1208            Ok(())
1209        }
1210        TAG_STRING_BASE..=TAG_STRING_LONG => {
1211            let len = if tag < TAG_STRING_LONG {
1212                (tag - TAG_STRING_BASE) as usize
1213            } else {
1214                usize::decode(reader)?
1215            };
1216            if reader.remaining() < len {
1217                return Err(EncoderError::InsufficientData);
1218            }
1219            reader.advance(len);
1220            Ok(())
1221        }
1222        TAG_BINARY => {
1223            let len = usize::decode(reader)?;
1224            if reader.remaining() < len {
1225                return Err(EncoderError::InsufficientData);
1226            }
1227            reader.advance(len);
1228            Ok(())
1229        }
1230        TAG_ARRAY_VEC_SET_BASE..=TAG_ARRAY_VEC_SET_LONG => {
1231            let len = if tag < TAG_ARRAY_VEC_SET_LONG {
1232                (tag - TAG_ARRAY_VEC_SET_BASE) as usize
1233            } else {
1234                usize::decode(reader)?
1235            };
1236            for _ in 0..len {
1237                skip_value(reader)?;
1238            }
1239            Ok(())
1240        }
1241        TAG_STRUCT_UNIT => Ok(()),
1242        TAG_STRUCT_NAMED => {
1243            loop {
1244                let field_id = read_field_id_optimized(reader)?;
1245                if field_id == 0 {
1246                    break;
1247                }
1248                skip_value(reader)?;
1249            }
1250            Ok(())
1251        }
1252        TAG_STRUCT_UNNAMED => {
1253            let field_count = usize::decode(reader)?;
1254            for _ in 0..field_count {
1255                skip_value(reader)?;
1256            }
1257            Ok(())
1258        }
1259        TAG_ENUM => {
1260            let _variant_id = read_field_id_optimized(reader)?;
1261            Ok(())
1262        }
1263        TAG_ENUM_NAMED => {
1264            let _variant_id = read_field_id_optimized(reader)?;
1265            loop {
1266                let field_id = read_field_id_optimized(reader)?;
1267                if field_id == 0 {
1268                    break;
1269                }
1270                skip_value(reader)?;
1271            }
1272            Ok(())
1273        }
1274        TAG_ENUM_UNNAMED => {
1275            let _variant_id = read_field_id_optimized(reader)?;
1276            let field_count = usize::decode(reader)?;
1277            for _ in 0..field_count {
1278                skip_value(reader)?;
1279            }
1280            Ok(())
1281        }
1282        TAG_TUPLE => {
1283            let len = usize::decode(reader)?;
1284            for _ in 0..len {
1285                skip_value(reader)?;
1286            }
1287            Ok(())
1288        }
1289        TAG_MAP => {
1290            let len = usize::decode(reader)?;
1291            for _ in 0..len {
1292                skip_value(reader)?; // key
1293                skip_value(reader)?; // value
1294            }
1295            Ok(())
1296        }
1297        TAG_CHRONO_DATETIME => {
1298            if reader.remaining() < 12 {
1299                return Err(EncoderError::InsufficientData);
1300            } // Approximation for i64 + u32, could be more precise
1301            let _timestamp_seconds = i64::decode(reader)?;
1302            let _timestamp_nanos = u32::decode(reader)?;
1303            Ok(())
1304        }
1305        TAG_CHRONO_NAIVE_DATE => {
1306            if reader.remaining() < 8 {
1307                return Err(EncoderError::InsufficientData);
1308            } // Approximation for i64
1309            let _days_from_epoch = i64::decode(reader)?;
1310            Ok(())
1311        }
1312        TAG_CHRONO_NAIVE_TIME => {
1313            if reader.remaining() < 8 {
1314                return Err(EncoderError::InsufficientData);
1315            } // Approximation for u32 + u32
1316            let _seconds_from_midnight = u32::decode(reader)?;
1317            let _nanoseconds = u32::decode(reader)?;
1318            Ok(())
1319        }
1320        TAG_DECIMAL => {
1321            if reader.remaining() < 20 {
1322                return Err(EncoderError::InsufficientData);
1323            } // Approximation for i128 + u32
1324            let _mantissa = i128::decode(reader)?;
1325            let _scale = u32::decode(reader)?;
1326            Ok(())
1327        }
1328        TAG_UUID => {
1329            // Covers ULID as well
1330            if reader.remaining() < 16 {
1331                return Err(EncoderError::InsufficientData);
1332            }
1333            reader.advance(16);
1334            Ok(())
1335        }
1336        TAG_JSON_NULL => Ok(()),
1337        TAG_JSON_BOOL => Ok(()),
1338        TAG_JSON_NUMBER => {
1339            // Number has type marker + actual number
1340            if reader.remaining() == 0 {
1341                return Err(EncoderError::InsufficientData);
1342            }
1343            let number_type = reader.get_u8();
1344            match number_type {
1345                0 => {
1346                    u64::decode(reader)?;
1347                }
1348                1 => {
1349                    i64::decode(reader)?;
1350                }
1351                2 => {
1352                    f64::decode(reader)?;
1353                }
1354                _ => {
1355                    return Err(EncoderError::Decode(format!(
1356                        "Invalid JSON Number type marker: {}",
1357                        number_type
1358                    )));
1359                }
1360            }
1361            Ok(())
1362        }
1363        TAG_JSON_STRING => {
1364            // String uses regular string encoding
1365            String::decode(reader)?;
1366            Ok(())
1367        }
1368        TAG_JSON_ARRAY => {
1369            let len = usize::decode(reader)?;
1370            for _ in 0..len {
1371                skip_value(reader)?;
1372            }
1373            Ok(())
1374        }
1375        TAG_JSON_OBJECT => {
1376            let len = usize::decode(reader)?;
1377            for _ in 0..len {
1378                String::decode(reader)?; // key
1379                skip_value(reader)?; // value
1380            }
1381            Ok(())
1382        }
1383        TAG_NONE | TAG_SOME => {
1384            // These should have been handled by Option<T> decode or skip_value for T
1385            // For TAG_NONE, it's fine. For TAG_SOME, we need to skip the inner value.
1386            if tag == TAG_SOME {
1387                skip_value(reader)?;
1388            }
1389            Ok(())
1390        }
1391        _ => Err(EncoderError::Decode(format!(
1392            "skip_value: unknown or unhandled tag {}",
1393            tag
1394        ))),
1395    }
1396}
1397
1398// --- HashSet, BTreeSet, IndexSet ---
1399/// Encodes a set as a length-prefixed sequence of elements.
1400impl<T: Encoder + Eq + std::hash::Hash> Encoder for HashSet<T> {
1401    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1402        encode_vec_length(self.len(), writer)?;
1403        for v in self {
1404            v.encode(writer)?;
1405        }
1406        Ok(())
1407    }
1408
1409    fn is_default(&self) -> bool {
1410        self.is_empty()
1411    }
1412}
1413/// Decodes a set from the senax binary format.
1414impl<T: Decoder + Eq + std::hash::Hash + 'static> Decoder for HashSet<T> {
1415    fn decode(reader: &mut Bytes) -> Result<Self> {
1416        let vec: Vec<T> = Vec::decode(reader)?;
1417        Ok(vec.into_iter().collect())
1418    }
1419}
1420// --- BTreeSet ---
1421impl<T: Encoder + Ord> Encoder for BTreeSet<T> {
1422    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1423        encode_vec_length(self.len(), writer)?;
1424        for v in self {
1425            v.encode(writer)?;
1426        }
1427        Ok(())
1428    }
1429
1430    fn is_default(&self) -> bool {
1431        self.is_empty()
1432    }
1433}
1434impl<T: Decoder + Ord + 'static> Decoder for BTreeSet<T> {
1435    fn decode(reader: &mut Bytes) -> Result<Self> {
1436        let vec: Vec<T> = Vec::decode(reader)?;
1437        Ok(vec.into_iter().collect())
1438    }
1439}
1440// --- BTreeMap ---
1441impl<K: Encoder + Ord, V: Encoder> Encoder for BTreeMap<K, V> {
1442    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1443        writer.put_u8(TAG_MAP);
1444        let len = self.len();
1445        len.encode(writer)?;
1446        for (k, v) in self {
1447            k.encode(writer)?;
1448            v.encode(writer)?;
1449        }
1450        Ok(())
1451    }
1452
1453    fn is_default(&self) -> bool {
1454        self.is_empty()
1455    }
1456}
1457impl<K: Decoder + Ord, V: Decoder> Decoder for BTreeMap<K, V> {
1458    fn decode(reader: &mut Bytes) -> Result<Self> {
1459        if reader.remaining() == 0 {
1460            return Err(EncoderError::InsufficientData);
1461        }
1462        let tag = reader.get_u8();
1463        if tag != TAG_MAP {
1464            return Err(EncoderError::Decode(format!(
1465                "Expected Map tag ({}), got {}",
1466                TAG_MAP, tag
1467            )));
1468        }
1469        let len = usize::decode(reader)?;
1470        let mut map = BTreeMap::new();
1471        for _ in 0..len {
1472            let k = K::decode(reader)?;
1473            let v = V::decode(reader)?;
1474            map.insert(k, v);
1475        }
1476        Ok(map)
1477    }
1478}
1479
1480// --- Bytes ---
1481impl Encoder for Bytes {
1482    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1483        writer.put_u8(TAG_BINARY);
1484        let len = self.len();
1485        len.encode(writer)?;
1486        writer.put_slice(self);
1487        Ok(())
1488    }
1489
1490    fn is_default(&self) -> bool {
1491        self.is_empty()
1492    }
1493}
1494impl Decoder for Bytes {
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        let len = if tag == TAG_BINARY {
1501            usize::decode(reader)?
1502        } else if (TAG_STRING_BASE..=TAG_STRING_LONG).contains(&tag) {
1503            if tag < TAG_STRING_LONG {
1504                (tag - TAG_STRING_BASE) as usize
1505            } else {
1506                usize::decode(reader)?
1507            }
1508        } else {
1509            return Err(EncoderError::Decode(format!(
1510                "Expected Bytes tag ({} or {}..={}), got {}",
1511                TAG_BINARY, TAG_STRING_BASE, TAG_STRING_LONG, tag
1512            )));
1513        };
1514
1515        if reader.remaining() < len {
1516            return Err(EncoderError::InsufficientData);
1517        }
1518
1519        Ok(reader.split_to(len))
1520    }
1521}
1522
1523// --- Arc<T> ---
1524/// Encodes an `Arc<T>` by encoding the inner value.
1525impl<T: Encoder> Encoder for Arc<T> {
1526    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1527        (**self).encode(writer)
1528    }
1529
1530    fn is_default(&self) -> bool {
1531        T::is_default(self)
1532    }
1533}
1534
1535/// Decodes an `Arc<T>` by decoding the inner value and wrapping it in an Arc.
1536impl<T: Decoder> Decoder for Arc<T> {
1537    fn decode(reader: &mut Bytes) -> Result<Self> {
1538        Ok(Arc::new(T::decode(reader)?))
1539    }
1540}
1541
1542/// Writes a `u64` in little-endian format without a tag.
1543///
1544/// This is used internally for struct/enum field/variant IDs.
1545pub fn write_field_id_optimized(writer: &mut BytesMut, field_id: u64) -> Result<()> {
1546    if field_id == 0 {
1547        // Terminator
1548        writer.put_u8(0);
1549    } else if (1..=250).contains(&field_id) {
1550        // Small field ID: write as u8
1551        writer.put_u8(field_id as u8);
1552    } else {
1553        // Large field ID: write 255 marker then u64
1554        writer.put_u8(255);
1555        writer.put_u64_le(field_id);
1556    }
1557    Ok(())
1558}
1559
1560/// Reads a field ID using optimized encoding.
1561///
1562/// Returns Ok(0) for terminator, Ok(field_id) for valid field ID.
1563pub fn read_field_id_optimized(reader: &mut Bytes) -> Result<u64> {
1564    if reader.remaining() < 1 {
1565        return Err(EncoderError::InsufficientData);
1566    }
1567
1568    let first_byte = reader.get_u8();
1569
1570    if first_byte == 0 {
1571        // Terminator
1572        Ok(0)
1573    } else if first_byte == 255 {
1574        // Large field ID follows
1575        if reader.remaining() < 8 {
1576            return Err(EncoderError::InsufficientData);
1577        }
1578        Ok(reader.get_u64_le())
1579    } else {
1580        // Small field ID
1581        Ok(first_byte as u64)
1582    }
1583}
1584
1585/// Implementation for references - delegates to the referenced value
1586impl<T: Encoder> Encoder for &T {
1587    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1588        (*self).encode(writer)
1589    }
1590
1591    fn is_default(&self) -> bool {
1592        (*self).is_default()
1593    }
1594}
1595
1596// --- Box<T> ---
1597/// Encodes a `Box<T>` by encoding the inner value.
1598impl<T: Encoder> Encoder for Box<T> {
1599    fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1600        (**self).encode(writer)
1601    }
1602
1603    fn is_default(&self) -> bool {
1604        T::is_default(self)
1605    }
1606}
1607
1608/// Decodes a `Box<T>` by decoding the inner value and wrapping it in a Box.
1609impl<T: Decoder> Decoder for Box<T> {
1610    fn decode(reader: &mut Bytes) -> Result<Self> {
1611        Ok(Box::new(T::decode(reader)?))
1612    }
1613}
1614
1615/// Encodes a `Vec<u8>` using the optimized binary format.
1616fn encode_vec_u8(vec: &[u8], writer: &mut BytesMut) -> Result<()> {
1617    writer.put_u8(TAG_BINARY);
1618    let len = vec.len();
1619    len.encode(writer)?;
1620    let bytes = unsafe { std::slice::from_raw_parts(vec.as_ptr(), vec.len()) };
1621    writer.put_slice(bytes);
1622    Ok(())
1623}
1624
1625/// Decodes a `Vec<u8>` from the optimized binary format.
1626fn decode_vec_u8(reader: &mut Bytes) -> Result<Vec<u8>> {
1627    let len = usize::decode(reader)?;
1628    let mut vec = vec![0u8; len];
1629    if len > 0 {
1630        reader.copy_to_slice(&mut vec);
1631    }
1632    Ok(vec)
1633}
1634
1635/// Encodes the length for array/vec/set format.
1636#[inline(never)]
1637pub(crate) fn encode_vec_length(len: usize, writer: &mut BytesMut) -> Result<()> {
1638    let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1639    if len <= max_short {
1640        let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
1641        writer.put_u8(tag);
1642    } else {
1643        writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1644        len.encode(writer)?;
1645    }
1646    Ok(())
1647}
1648
1649/// Decodes the length for array/vec/set format.
1650#[inline(never)]
1651pub(crate) fn decode_vec_length(tag: u8, reader: &mut Bytes) -> Result<usize> {
1652    if (TAG_ARRAY_VEC_SET_BASE..TAG_ARRAY_VEC_SET_LONG).contains(&tag) {
1653        Ok((tag - TAG_ARRAY_VEC_SET_BASE) as usize)
1654    } else if tag == TAG_ARRAY_VEC_SET_LONG {
1655        usize::decode(reader)
1656    } else {
1657        Err(EncoderError::Decode(format!(
1658            "Expected Vec tag ({}..={}), got {}",
1659            TAG_ARRAY_VEC_SET_BASE, TAG_ARRAY_VEC_SET_LONG, tag
1660        )))
1661    }
1662}