senax_encoder/
lib.rs

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