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