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