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