fastserial 0.1.1

Ultra-fast, zero-copy serialization/deserialization library for Rust with SIMD acceleration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! # FastSerial
//!
//! `fastserial` is a high-performance, format-agnostic serialization framework for Rust.
//! It is an **ambitious project** designed for specific high-throughput use cases
//! by leveraging specialized code generation and SIMD-accelerated scanning.
//!
//! ## Design Goals
//!
//! - **High Performance**: Aiming for maximum throughput in JSON and Binary formats.
//! - **Zero-Copy**: Borrowed data types (like `&str` and `&[u8]`) are deserialized without allocation.
//! - **SIMD Acceleration**: First-class support for AVX2 and SSE4.2 instructions for JSON parsing.
//! - **Safety First**: While leveraging `unsafe` for SIMD, the public API remains completely safe.
//! - **Minimal Overhead**: Thin abstraction layer that compiles down to efficient machine code.
//!
//! ## Supported Formats
//!
//! | Format | Module | Description |
//! |--------|--------|-------------|
//! | JSON   | [`json`] | High-speed JSON with SIMD scanning. |
//! | Binary | [`binary`] | Compact, schema-validated binary format. |
//!
//! ## Core Traits
//!
//! There are two primary traits that power `fastserial`:
//!
//! 1.  **[`Encode`]**: Types that can be serialized into a supported format.
//! 2.  **[`Decode`]**: Types that can be deserialized from a byte buffer.
//!
//! For most users, these traits should be implemented using the `derive` macros:
//!
//! ```rust
//! use fastserial::{Encode, Decode, json};
//!
//! #[derive(Encode, Decode, Debug, PartialEq)]
//! struct User {
//!     id: u64,
//!     username: String,
//!     email: String,
//! }
//!
//! # fn main() -> Result<(), fastserial::Error> {
//! let user = User {
//!     id: 42,
//!     username: "dev_user".to_string(),
//!     email: "dev@example.com".to_string(),
//! };
//!
//! // Serialize to JSON string
//! let json_data = json::encode(&user)?;
//!
//! // Deserialize back to struct
//! let decoded: User = json::decode(&json_data)?;
//!
//! assert_eq!(user, decoded);
//! # Ok(())
//! # }
//! ```
//!
//! ## SIMD Support and Safety
//!
//! `fastserial` automatically detects CPU features at runtime to use the fastest possible
//! implementation.
//!
//! - **AVX2**: Used on modern x86_64 CPUs for 32-byte parallel scanning.
//! - **SSE4.2**: Fallback for older x86_64 CPUs.
//! - **Scalar**: Default implementation for other architectures or when SIMD is disabled.
//!
//! All `unsafe` code used for SIMD is encapsulated within the [`simd`] module and is
//! thoroughly tested for memory safety.
//!
//! ## Feature Flags
//!
//! - `std` (default): Enables support for `std` types like `String`, `Vec`, and `std::error::Error`.
//! - `json` (default): Enables JSON serialization/deserialization.
//! - `binary` (default): Enables FastSerial binary format.
//! - `chrono`: Enables serialization support for `chrono` date/time types.
//! - `profile`: Enables internal profiling for performance debugging.

#![no_std]

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "std")]
extern crate alloc;

/// Derive macro for the `Decode` trait.
pub use fastserial_derive::Decode;
/// Derive macro for the `Encode` trait.
pub use fastserial_derive::Encode;

/// Codec implementations for various formats (JSON, Binary, etc.)
pub mod codec;
/// I/O traits and buffers for reading and writing.
pub mod io;
/// Schema hashing and validation.
pub mod schema;
/// SIMD-accelerated low-level operations.
pub mod simd;

mod error;
mod format;
pub mod value;

pub use error::Error;
pub use format::Format;
pub use value::Value;

/// Trait for types that can be encoded into a format.
///
/// This trait is the primary interface for serialization. It is recommended to use
/// `#[derive(Encode)]` to implement this trait for your structs.
///
/// # Examples
///
/// ```rust
/// use fastserial::Encode;
///
/// #[derive(Encode)]
/// struct MyData {
///     value: u32,
/// }
/// ```
pub trait Encode {
    /// A unique 64-bit hash representing the schema of the type.
    ///
    /// This hash is used by formats like Binary to ensure that the data
    /// being deserialized matches the struct definition.
    const SCHEMA_HASH: u64;

    /// Encodes the type into the provided `WriteBuffer`.
    ///
    /// This method is usually generated by the `derive` macro and handles
    /// the field-by-field serialization.
    fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error>;

    /// Encodes the type using a specific `Format` implementation.
    ///
    /// This allows the type to customize its representation for different
    /// formats (e.g., JSON vs Binary).
    fn encode_with_format<F: Format, W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        F::encode_struct(self, w)
    }
}

/// Trait for types that can be decoded from a byte buffer.
///
/// The `'de` lifetime represents the lifetime of the input buffer. Types that
/// implement `Decode<'de>` can borrow data directly from this buffer (zero-copy).
///
/// # Examples
///
/// ```rust
/// use fastserial::Decode;
///
/// #[derive(Decode)]
/// struct MyData {
///     owned_string: String,
/// }
/// ```
pub trait Decode<'de>: Sized {
    /// Decodes the type from the provided `ReadBuffer`.
    ///
    /// This method handles field-by-field deserialization and may borrow
    /// from the buffer `r`.
    fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error>;
}

/// JSON format support.
///
/// This module provides a high-level API for serializing and deserializing data in JSON format.
/// It is powered by SIMD scanning and specialized code generation to achieve maximum throughput.
pub mod json {
    use super::*;

    /// Encodes a value to a JSON byte vector.
    ///
    /// This is a convenience function that allocates a new `Vec<u8>` and serializes the
    /// provided value into it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::json;
    ///
    /// let data = vec![1, 2, 3];
    /// let json_bytes = json::encode(&data).unwrap();
    /// assert_eq!(json_bytes, b"[1,2,3]");
    /// ```
    ///
    /// # Errors
    /// Returns an [`Error`] if the value cannot be encoded (e.g., contains invalid floating point numbers).
    pub fn encode<T: Encode>(val: &T) -> Result<alloc::vec::Vec<u8>, Error> {
        let mut buf = alloc::vec::Vec::with_capacity(256);
        val.encode(&mut buf)?;
        Ok(buf)
    }

    /// Encodes a value into an existing byte vector.
    ///
    /// This is more efficient than [`encode`] if you already have a buffer that can be reused.
    ///
    /// # Arguments
    /// * `val` - The value to encode.
    /// * `buf` - The destination buffer. Encoded data will be appended to it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::json;
    ///
    /// let mut buf = Vec::new();
    /// json::encode_into(&42, &mut buf).unwrap();
    /// assert_eq!(buf, b"42");
    /// ```
    pub fn encode_into<T: Encode>(val: &T, buf: &mut alloc::vec::Vec<u8>) -> Result<(), Error> {
        val.encode(buf)
    }

    /// Decodes a value from a JSON byte slice.
    ///
    /// This function performs zero-copy deserialization where possible, meaning it borrows
    /// strings and byte slices directly from the input `input`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::{Decode, json};
    ///
    /// #[derive(Decode)]
    /// struct Message {
    ///     text: String,
    /// }
    ///
    /// let input = r#"{"text":"Hello"}"#;
    /// let msg: Message = json::decode(input.as_bytes()).unwrap();
    /// assert_eq!(msg.text, "Hello");
    /// ```
    ///
    /// # Errors
    /// Returns an [`Error`] if the JSON is malformed, missing required fields, or contains
    /// invalid data types for the target struct.
    pub fn decode<'de, T: Decode<'de>>(input: &'de [u8]) -> Result<T, Error> {
        let mut r = io::ReadBuffer::new(input);
        let val = T::decode(&mut r)?;
        codec::json::skip_whitespace(&mut r);
        if !r.is_eof() {
            return Err(Error::TrailingData);
        }
        Ok(val)
    }

    pub fn decode_str<'de, T: Decode<'de>>(input: &'de str) -> Result<T, Error> {
        decode(input.as_bytes())
    }

    pub fn encode_pretty<T: Encode>(val: &T) -> Result<alloc::vec::Vec<u8>, Error> {
        let compact = encode(val)?;
        let value: crate::Value = decode(&compact)?;
        let mut buf = alloc::vec::Vec::with_capacity(compact.len() * 2);
        pretty_print_value(&value, &mut buf, 0)?;
        Ok(buf)
    }

    fn pretty_print_value(
        val: &crate::Value,
        buf: &mut alloc::vec::Vec<u8>,
        indent: usize,
    ) -> Result<(), Error> {
        use crate::io::WriteBuffer;
        match val {
            crate::Value::Null => buf.write_bytes(b"null"),
            crate::Value::Bool(true) => buf.write_bytes(b"true"),
            crate::Value::Bool(false) => buf.write_bytes(b"false"),
            crate::Value::Number(_) | crate::Value::String(_) => val.encode(buf),
            crate::Value::Array(arr) => {
                if arr.is_empty() {
                    return buf.write_bytes(b"[]");
                }
                buf.write_bytes(b"[\n")?;
                let child_indent = indent + 2;
                for (i, item) in arr.iter().enumerate() {
                    for _ in 0..child_indent {
                        buf.write_byte(b' ')?;
                    }
                    pretty_print_value(item, buf, child_indent)?;
                    if i + 1 < arr.len() {
                        buf.write_byte(b',')?;
                    }
                    buf.write_byte(b'\n')?;
                }
                for _ in 0..indent {
                    buf.write_byte(b' ')?;
                }
                buf.write_byte(b']')
            }
            crate::Value::Object(map) => {
                if map.is_empty() {
                    return buf.write_bytes(b"{}");
                }
                buf.write_bytes(b"{\n")?;
                let child_indent = indent + 2;
                let len = map.len();
                for (i, (k, v)) in map.iter().enumerate() {
                    for _ in 0..child_indent {
                        buf.write_byte(b' ')?;
                    }
                    codec::json::write_str(k, buf)?;
                    buf.write_bytes(b": ")?;
                    pretty_print_value(v, buf, child_indent)?;
                    if i + 1 < len {
                        buf.write_byte(b',')?;
                    }
                    buf.write_byte(b'\n')?;
                }
                for _ in 0..indent {
                    buf.write_byte(b' ')?;
                }
                buf.write_byte(b'}')
            }
        }
    }
}

/// FastSerial binary format support.
///
/// The binary format is a high-performance, compact representation of data.
/// It includes a 16-byte header with a magic number, version, and schema hash
/// to ensure data integrity and compatibility.
///
/// ### Header Specification (16 bytes)
///
/// | Bytes | Name | Description |
/// |-------|------|-------------|
/// | 0-3   | Magic | Fixed string `FBIN`. |
/// | 4-5   | Version | Format version (current: `0x0001`). |
/// | 6-13  | Schema Hash | 64-bit hash of the target type's schema. |
/// | 14-15 | Reserved | Reserved for future use. |
pub mod binary {
    use super::*;

    const MAGIC: [u8; 4] = *b"FBIN";
    const VERSION: u16 = 0x0001;

    /// Encodes a value to a new byte vector using the FastSerial binary format.
    ///
    /// This function automatically prepends the 16-byte protocol header.
    /// Use [`encode_raw`] for faster encoding without header.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::binary;
    ///
    /// let data = 12345u64;
    /// let bin_data = binary::encode(&data).unwrap();
    /// assert!(bin_data.starts_with(b"FBIN"));
    /// ```
    ///
    /// # Returns
    /// A `Vec<u8>` containing the header followed by the serialized data.
    pub fn encode<T: Encode>(val: &T) -> Result<alloc::vec::Vec<u8>, Error> {
        let mut buf = alloc::vec::Vec::with_capacity(256);
        buf.extend_from_slice(&MAGIC);
        buf.extend_from_slice(&VERSION.to_le_bytes());
        buf.extend_from_slice(&T::SCHEMA_HASH.to_le_bytes());
        buf.extend_from_slice(&[0, 0]);
        val.encode(&mut buf)?;
        Ok(buf)
    }

    /// Decodes a value from a byte slice using the FastSerial binary format.
    ///
    /// This function validates the magic number, version, and schema hash
    /// before performing deserialization.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::{Encode, Decode, binary};
    ///
    /// #[derive(Encode, Decode, PartialEq, Debug)]
    /// struct Data { id: u32 }
    ///
    /// let original = Data { id: 100 };
    /// let bytes = binary::encode(&original).unwrap();
    /// let decoded: Data = binary::decode(&bytes).unwrap();
    /// assert_eq!(original, decoded);
    /// ```
    ///
    /// # Errors
    /// Returns [`Error::InvalidMagic`] if the header is missing, or [`Error::InvalidUtf8`]
    /// if the schema hash doesn't match (coming soon).
    pub fn decode<'de, T: Decode<'de>>(input: &'de [u8]) -> Result<T, Error> {
        if input.len() < 16 {
            return Err(Error::UnexpectedEof);
        }
        if input[0..4] != MAGIC {
            return Err(Error::InvalidMagic);
        }
        let version = u16::from_le_bytes([input[4], input[5]]);
        if version != VERSION {
            return Err(Error::UnsupportedVersion { version });
        }
        // TODO: Validate T::SCHEMA_HASH against input[6..14]
        let mut r = io::ReadBuffer::new(&input[16..]);
        let val = T::decode(&mut r)?;
        if !r.is_eof() {
            return Err(Error::TrailingData);
        }
        Ok(val)
    }

    /// Encodes a value to binary without the 16-byte header.
    ///
    /// This is faster for internal use where the schema is known.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::binary;
    ///
    /// let data = 12345u64;
    /// let bin_data = binary::encode_raw(&data).unwrap();
    /// assert!(!bin_data.starts_with(b"FBIN"));
    /// ```
    pub fn encode_raw<T: Encode>(val: &T) -> Result<alloc::vec::Vec<u8>, Error> {
        let mut buf = alloc::vec::Vec::with_capacity(256);
        val.encode(&mut buf)?;
        Ok(buf)
    }

    /// Decodes a value from binary without parsing the header.
    ///
    /// Use this with data encoded via [`encode_raw`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fastserial::{Encode, Decode, binary};
    ///
    /// #[derive(Encode, Decode, PartialEq, Debug)]
    /// struct Data { id: u32 }
    ///
    /// let original = Data { id: 100 };
    /// let bytes = binary::encode_raw(&original).unwrap();
    /// let decoded: Data = binary::decode_raw(&bytes).unwrap();
    /// assert_eq!(original, decoded);
    /// ```
    pub fn decode_raw<'de, T: Decode<'de>>(input: &'de [u8]) -> Result<T, Error> {
        let mut r = io::ReadBuffer::new(input);
        let val = T::decode(&mut r)?;
        if !r.is_eof() {
            return Err(Error::TrailingData);
        }
        Ok(val)
    }
}

mod option_impl {
    use super::*;

    impl<T: Encode> Encode for Option<T> {
        const SCHEMA_HASH: u64 = 0;

        #[inline]
        fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
            match self {
                None => w.write_bytes(b"null"),
                Some(v) => v.encode(w),
            }
        }

        #[inline]
        fn encode_with_format<F: Format, W: io::WriteBuffer>(
            &self,
            w: &mut W,
        ) -> Result<(), Error> {
            match self {
                None => F::write_null(w),
                Some(v) => v.encode_with_format::<F, W>(w),
            }
        }
    }

    impl<'de, T: Decode<'de>> Decode<'de> for Option<T> {
        #[inline]
        fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
            codec::json::skip_whitespace(r);
            if r.peek() == b'n' {
                r.expect_bytes(b"null")?;
                Ok(None)
            } else {
                Ok(Some(T::decode(r)?))
            }
        }
    }
}

mod vec_impl {
    use super::*;

    impl<T: Encode> Encode for alloc::vec::Vec<T> {
        const SCHEMA_HASH: u64 = 0;

        #[inline]
        fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
            w.write_byte(b'[')?;
            let mut iter = self.iter();
            if let Some(item) = iter.next() {
                item.encode(w)?;
                for item in iter {
                    w.write_byte(b',')?;
                    item.encode(w)?;
                }
            }
            w.write_byte(b']')
        }

        #[inline]
        fn encode_with_format<F: Format, W: io::WriteBuffer>(
            &self,
            w: &mut W,
        ) -> Result<(), Error> {
            F::begin_array(self.len(), w)?;
            let mut iter = self.iter();
            if let Some(item) = iter.next() {
                item.encode_with_format::<F, W>(w)?;
                for item in iter {
                    F::array_separator(w)?;
                    item.encode_with_format::<F, W>(w)?;
                }
            }
            F::end_array(w)
        }
    }

    impl<'de, T: Decode<'de>> Decode<'de> for alloc::vec::Vec<T> {
        #[inline]
        fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
            r.expect_byte(b'[')?;
            let mut vec = alloc::vec::Vec::new();
            codec::json::skip_whitespace(r);
            if r.peek() == b']' {
                r.advance(1);
                return Ok(vec);
            }
            loop {
                vec.push(T::decode(r)?);
                codec::json::skip_comma_or_close(r, b']')?;
                if r.peek() == b']' {
                    r.advance(1);
                    break;
                }
            }
            Ok(vec)
        }
    }
}

macro_rules! impl_primitive {
    ($($ty:ty => $write_fn:ident, $read_fn:ident, $hash:literal),* $(,)?) => {
        $(
            impl Encode for $ty {
                const SCHEMA_HASH: u64 = $hash;

                #[inline(always)]
                fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
                    codec::json::$write_fn(*self, w)
                }

                #[inline(always)]
                fn encode_with_format<F: Format, W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
                    F::write_u64(*self as u64, w)
                }
            }

            impl<'de> Decode<'de> for $ty {
                #[inline(always)]
                fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
                    codec::json::$read_fn(r)
                }
            }
        )*
    };
}

impl_primitive! {
    u8 => write_u8, read_u8, 0x7a3c8d2e,
    u16 => write_u16, read_u16, 0x8b4d9e3f,
    u32 => write_u32, read_u32, 0x9c5e0f4a,
    u64 => write_u64, read_u64, 0xad6f1a5b,
    i8 => write_i8, read_i8, 0xbe7a2b6c,
    i16 => write_i16, read_i16, 0xcf8b3c7d,
    i32 => write_i32, read_i32, 0xde9c4d8e,
    i64 => write_i64, read_i64, 0xefad5e9f,
    f32 => write_f32, read_f32, 0xf0be6faa,
    f64 => write_f64, read_f64, 0x01cf8fbb,
    bool => write_bool, read_bool, 0x12d090cc,
}

impl Encode for () {
    const SCHEMA_HASH: u64 = 0x23e1a1dd;

    #[inline]
    fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        codec::json::write_null(w)
    }
}

impl<'de> Decode<'de> for () {
    #[inline]
    fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
        codec::json::read_null(r)
    }
}

impl Encode for alloc::string::String {
    const SCHEMA_HASH: u64 = 0x34f2b2ee3d6e8cbb;

    #[inline]
    fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        codec::json::write_str(self, w)
    }

    #[inline]
    fn encode_with_format<F: Format, W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        F::write_str(self, w)
    }
}

impl<'de> Decode<'de> for alloc::string::String {
    #[inline]
    fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
        Ok(codec::json::read_string_cow(r)?.into_owned())
    }
}

impl Encode for &str {
    const SCHEMA_HASH: u64 = 0x45c3c3ff4e7d9dcc;

    #[inline]
    fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        codec::json::write_str(self, w)
    }

    #[inline]
    fn encode_with_format<F: Format, W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        F::write_str(self, w)
    }
}

impl<'de> Decode<'de> for &'de str {
    #[inline]
    fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
        codec::json::read_string(r)
    }
}

impl Encode for &[u8] {
    const SCHEMA_HASH: u64 = 0x56d4d4ff5f8deed;

    #[inline]
    fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        codec::json::write_bytes(self, w)
    }

    #[inline]
    fn encode_with_format<F: Format, W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
        F::write_bytes(self, w)
    }
}

impl<'de> Decode<'de> for &'de [u8] {
    #[inline]
    fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
        codec::json::read_bytes(r)
    }
}

#[cfg(feature = "chrono")]
mod chrono_impl {
    use super::*;
    use chrono::{DateTime, Utc};

    impl Encode for DateTime<Utc> {
        const SCHEMA_HASH: u64 = 0x67e5e5ff6f9efffe;

        #[inline]
        fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
            let s = self.to_rfc3339();
            codec::json::write_str(&s, w)
        }

        #[inline]
        fn encode_with_format<F: Format, W: io::WriteBuffer>(
            &self,
            w: &mut W,
        ) -> Result<(), Error> {
            let s = self.to_rfc3339();
            F::write_str(&s, w)
        }
    }

    impl<'de> Decode<'de> for DateTime<Utc> {
        #[inline]
        fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
            let s = codec::json::read_string(r)?;
            DateTime::parse_from_rfc3339(s)
                .map(|dt| dt.with_timezone(&Utc))
                .map_err(|_| Error::InvalidUtf8 {
                    byte_offset: r.get_pos(),
                })
        }
    }
}

#[cfg(feature = "std")]
mod hashmap_impl {
    use super::*;
    use std::collections::HashMap;

    impl<K: Encode + core::fmt::Display, V: Encode> Encode for HashMap<K, V> {
        const SCHEMA_HASH: u64 = 0;

        #[inline]
        fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
            w.write_byte(b'{')?;
            let mut first = true;
            for (k, v) in self {
                if !first {
                    w.write_byte(b',')?;
                }
                first = false;
                let key_str = alloc::format!("{}", k);
                codec::json::write_str(&key_str, w)?;
                w.write_byte(b':')?;
                v.encode(w)?;
            }
            w.write_byte(b'}')
        }
    }

    impl<'de, V: Decode<'de>> Decode<'de> for HashMap<alloc::string::String, V> {
        #[inline]
        fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
            codec::json::skip_whitespace(r);
            r.expect_byte(b'{')?;
            let mut map = HashMap::new();
            codec::json::skip_whitespace(r);
            if r.peek() == b'}' {
                r.advance(1);
                return Ok(map);
            }
            loop {
                codec::json::skip_whitespace(r);
                let key = codec::json::read_string_cow(r)?.into_owned();
                codec::json::skip_whitespace(r);
                r.expect_byte(b':')?;
                let val = V::decode(r)?;
                map.insert(key, val);
                codec::json::skip_comma_or_close(r, b'}')?;
                if r.peek() == b'}' {
                    r.advance(1);
                    break;
                }
            }
            Ok(map)
        }
    }
}

mod btreemap_impl {
    use super::*;
    use alloc::collections::BTreeMap;

    impl<K: Encode + core::fmt::Display, V: Encode> Encode for BTreeMap<K, V> {
        const SCHEMA_HASH: u64 = 0;

        #[inline]
        fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
            w.write_byte(b'{')?;
            let mut first = true;
            for (k, v) in self {
                if !first {
                    w.write_byte(b',')?;
                }
                first = false;
                let key_str = alloc::format!("{}", k);
                codec::json::write_str(&key_str, w)?;
                w.write_byte(b':')?;
                v.encode(w)?;
            }
            w.write_byte(b'}')
        }
    }

    impl<'de, V: Decode<'de>> Decode<'de> for BTreeMap<alloc::string::String, V> {
        #[inline]
        fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
            codec::json::skip_whitespace(r);
            r.expect_byte(b'{')?;
            let mut map = BTreeMap::new();
            codec::json::skip_whitespace(r);
            if r.peek() == b'}' {
                r.advance(1);
                return Ok(map);
            }
            loop {
                codec::json::skip_whitespace(r);
                let key = codec::json::read_string_cow(r)?.into_owned();
                codec::json::skip_whitespace(r);
                r.expect_byte(b':')?;
                let val = V::decode(r)?;
                map.insert(key, val);
                codec::json::skip_comma_or_close(r, b'}')?;
                if r.peek() == b'}' {
                    r.advance(1);
                    break;
                }
            }
            Ok(map)
        }
    }
}

macro_rules! impl_tuple {
    ($($idx:tt $T:ident),+) => {
        impl<$($T: Encode),+> Encode for ($($T,)+) {
            const SCHEMA_HASH: u64 = 0;

            #[inline]
            fn encode<W: io::WriteBuffer>(&self, w: &mut W) -> Result<(), Error> {
                w.write_byte(b'[')?;
                impl_tuple!(@encode self w $($idx $T),+);
                w.write_byte(b']')
            }
        }

        impl<'de, $($T: Decode<'de>),+> Decode<'de> for ($($T,)+) {
            #[inline]
            fn decode(r: &mut io::ReadBuffer<'de>) -> Result<Self, Error> {
                codec::json::skip_whitespace(r);
                r.expect_byte(b'[')?;
                impl_tuple!(@decode r $($idx $T),+);
                codec::json::skip_whitespace(r);
                r.expect_byte(b']')?;
                Ok(($($T,)+))
            }
        }
    };

    (@encode $self:ident $w:ident $first_idx:tt $first_T:ident $(, $idx:tt $T:ident)*) => {
        $self.$first_idx.encode($w)?;
        $(
            $w.write_byte(b',')?;
            $self.$idx.encode($w)?;
        )*
    };

    (@decode $r:ident $first_idx:tt $first_T:ident $(, $idx:tt $T:ident)*) => {
        codec::json::skip_whitespace($r);
        #[allow(non_snake_case)]
        let $first_T = $first_T::decode($r)?;
        $(
            codec::json::skip_comma_or_close($r, b']')?;
            #[allow(non_snake_case)]
            let $T = $T::decode($r)?;
        )*
    };
}

impl_tuple!(0 A);
impl_tuple!(0 A, 1 B);
impl_tuple!(0 A, 1 B, 2 C);
impl_tuple!(0 A, 1 B, 2 C, 3 D);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G, 7 H);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G, 7 H, 8 I2);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G, 7 H, 8 I2, 9 J);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G, 7 H, 8 I2, 9 J, 10 K);
impl_tuple!(0 A, 1 B, 2 C, 3 D, 4 E2, 5 F2, 6 G, 7 H, 8 I2, 9 J, 10 K, 11 L);

#[cfg(feature = "msgpack")]
pub mod msgpack {
    pub use crate::codec::msgpack::*;
}