crous-core 1.1.0

Core encoder/decoder, block framing, and Value types for the Crous binary format
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! Trait for types that can be serialized/deserialized with the Crous format.
//!
//! This is the trait generated by `#[derive(Crous)]`. It provides schema-bound
//! encoding with stable field IDs and schema fingerprints.
//!
//! # Blanket implementations
//!
//! The following types have built-in `Crous` implementations:
//!
//! | Rust type | Crous `Value` | Notes |
//! |-----------|---------------|-------|
//! | `bool` | `Bool` | |
//! | `u8`, `u16`, `u32`, `u64`, `usize` | `UInt` | widened to `u64` |
//! | `u128` | `UInt` | panics if value > `u64::MAX` |
//! | `i8`, `i16`, `i32`, `i64`, `isize` | `Int` | widened to `i64` |
//! | `i128` | `Int` | panics if value outside `i64` range |
//! | `f32`, `f64` | `Float` | `f32` widened to `f64` |
//! | `String`, `Box<str>` | `Str` | |
//! | `Vec<u8>` | `Array` of `UInt` | use [`CrousBytes`] for `Value::Bytes` |
//! | `Vec<T: Crous>` | `Array` | |
//! | `Option<T: Crous>` | `T` or `Null` | |
//! | `Box<T: Crous>` | delegates to `T` | |
//! | [`CrousBytes`] | `Bytes` | newtype for raw binary blobs |
//! | `HashMap<String, T>` | `Object` | insertion-order not guaranteed |
//! | `BTreeMap<String, T>` | `Object` | sorted by key |
//! | `(A,)` through `(A,B,C,D,E,F)` | `Array` | heterogeneous tuples |

use crate::error::Result;
use crate::value::Value;
use std::collections::{BTreeMap, HashMap};

/// Trait for types that can encode/decode to/from the Crous binary format.
///
/// Implementations are typically generated by `#[derive(Crous)]` from
/// the `crous-derive` crate, which assigns stable field IDs and computes
/// schema fingerprints.
///
/// # Example (manual implementation)
/// ```
/// use crous_core::{Crous, Value};
///
/// struct Point { x: f64, y: f64 }
///
/// impl Crous for Point {
///     fn to_crous_value(&self) -> Value {
///         Value::Object(vec![
///             ("x".into(), Value::Float(self.x)),
///             ("y".into(), Value::Float(self.y)),
///         ])
///     }
///
///     fn from_crous_value(value: &Value) -> crous_core::Result<Self> {
///         match value {
///             Value::Object(fields) => {
///                 let mut x = 0.0;
///                 let mut y = 0.0;
///                 for (k, v) in fields {
///                     match k.as_str() {
///                         "x" => x = v.as_float().unwrap_or(0.0),
///                         "y" => y = v.as_float().unwrap_or(0.0),
///                         _ => {} // skip unknown fields for forward compat
///                     }
///                 }
///                 Ok(Point { x, y })
///             }
///             _ => Err(crous_core::CrousError::SchemaMismatch(
///                 "expected object for Point".into()
///             )),
///         }
///     }
///
///     fn schema_fingerprint() -> u64 { 0x1234567890abcdef }
///     fn type_name() -> &'static str { "Point" }
/// }
/// ```
pub trait Crous: Sized {
    /// Convert this value to an owned `Value` for encoding.
    fn to_crous_value(&self) -> Value;

    /// Construct this type from a decoded `Value`.
    fn from_crous_value(value: &Value) -> Result<Self>;

    /// A stable fingerprint (XXH64) of this type's schema.
    /// Used for schema-on-write validation.
    fn schema_fingerprint() -> u64;

    /// The human-readable type name for diagnostics.
    fn type_name() -> &'static str;

    /// Encode this value directly to Crous binary bytes.
    ///
    /// Convenience method that creates an `Encoder`, encodes the value,
    /// and returns the finished byte vector.
    fn to_crous_bytes(&self) -> Result<Vec<u8>> {
        let val = self.to_crous_value();
        let mut enc = crate::encoder::Encoder::new();
        enc.encode_value(&val)?;
        enc.finish()
    }

    /// Decode from Crous binary bytes using default limits.
    fn from_crous_bytes(data: &[u8]) -> Result<Self> {
        let mut dec = crate::decoder::Decoder::new(data);
        let val = dec.decode_next()?.to_owned_value();
        Self::from_crous_value(&val)
    }

    /// Decode from Crous binary bytes with custom limits.
    ///
    /// This enforces all `Limits` during binary decode: nesting depth,
    /// memory, block size, string length, and item count.
    fn from_crous_bytes_with_limits(data: &[u8], limits: crate::limits::Limits) -> Result<Self> {
        let mut dec = crate::decoder::Decoder::with_limits(data, limits);
        let val = dec.decode_next()?.to_owned_value();
        Self::from_crous_value(&val)
    }
}

// ---------------------------------------------------------------------------
// Blanket impls for primitive types
// ---------------------------------------------------------------------------

// --- Bool ---

impl Crous for bool {
    fn to_crous_value(&self) -> Value {
        Value::Bool(*self)
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Bool(b) => Ok(*b),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected bool".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0004
    }
    fn type_name() -> &'static str {
        "bool"
    }
}

// --- Unsigned integers ---

/// Helper macro: implement Crous for unsigned integer types that fit in u64.
macro_rules! impl_crous_uint {
    ($($ty:ty => $fp:expr, $name:expr);+ $(;)?) => { $(
        impl Crous for $ty {
            fn to_crous_value(&self) -> Value {
                Value::UInt(*self as u64)
            }

            fn from_crous_value(value: &Value) -> Result<Self> {
                match value {
                    Value::UInt(n) => {
                        <$ty>::try_from(*n).map_err(|_| crate::error::CrousError::SchemaMismatch(
                            format!("uint {} out of range for {}", n, $name)
                        ))
                    }
                    _ => Err(crate::error::CrousError::SchemaMismatch(
                        format!("expected uint for {}", $name)
                    )),
                }
            }

            fn schema_fingerprint() -> u64 { $fp }
            fn type_name() -> &'static str { $name }
        }
    )+ };
}

impl_crous_uint! {
    u8   => 0x0002_0001, "u8";
    u16  => 0x0002_0002, "u16";
    u32  => 0x0002_0003, "u32";
    u64  => 0x0002,      "u64";
}

// usize: same wire representation as u64
impl Crous for usize {
    fn to_crous_value(&self) -> Value {
        Value::UInt(*self as u64)
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::UInt(n) => {
                usize::try_from(*n).map_err(|_| {
                    crate::error::CrousError::SchemaMismatch(format!(
                        "uint {n} out of range for usize"
                    ))
                })
            }
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected uint for usize".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0002_0005
    }
    fn type_name() -> &'static str {
        "usize"
    }
}

// u128: encode as UInt, but panics on encode if > u64::MAX
impl Crous for u128 {
    fn to_crous_value(&self) -> Value {
        Value::UInt(u64::try_from(*self).expect("u128 value exceeds u64::MAX for Crous encoding"))
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::UInt(n) => Ok(u128::from(*n)),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected uint for u128".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0002_0006
    }
    fn type_name() -> &'static str {
        "u128"
    }
}

// --- Signed integers ---

/// Helper macro: implement Crous for signed integer types that fit in i64.
macro_rules! impl_crous_int {
    ($($ty:ty => $fp:expr, $name:expr);+ $(;)?) => { $(
        impl Crous for $ty {
            fn to_crous_value(&self) -> Value {
                Value::Int(i64::from(*self))
            }

            fn from_crous_value(value: &Value) -> Result<Self> {
                match value {
                    Value::Int(n) => {
                        <$ty>::try_from(*n).map_err(|_| crate::error::CrousError::SchemaMismatch(
                            format!("int {} out of range for {}", n, $name)
                        ))
                    }
                    // Also accept UInt for small non-negative values (cross-compat).
                    Value::UInt(n) => {
                        let as_i64 = i64::try_from(*n).map_err(|_| {
                            crate::error::CrousError::SchemaMismatch(
                                format!("uint {} out of range for {}", n, $name)
                            )
                        })?;
                        <$ty>::try_from(as_i64).map_err(|_| {
                            crate::error::CrousError::SchemaMismatch(
                                format!("uint {} out of range for {}", n, $name)
                            )
                        })
                    }
                    _ => Err(crate::error::CrousError::SchemaMismatch(
                        format!("expected int for {}", $name)
                    )),
                }
            }

            fn schema_fingerprint() -> u64 { $fp }
            fn type_name() -> &'static str { $name }
        }
    )+ };
}

impl_crous_int! {
    i8   => 0x0003_0001, "i8";
    i16  => 0x0003_0002, "i16";
    i32  => 0x0003_0003, "i32";
    i64  => 0x0003,      "i64";
}

// isize: same wire representation as i64
impl Crous for isize {
    fn to_crous_value(&self) -> Value {
        Value::Int(*self as i64)
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Int(n) => {
                isize::try_from(*n).map_err(|_| {
                    crate::error::CrousError::SchemaMismatch(format!(
                        "int {n} out of range for isize"
                    ))
                })
            }
            Value::UInt(n) => {
                let as_i64 = i64::try_from(*n).map_err(|_| {
                    crate::error::CrousError::SchemaMismatch(format!(
                        "uint {n} out of range for isize"
                    ))
                })?;
                isize::try_from(as_i64).map_err(|_| {
                    crate::error::CrousError::SchemaMismatch(format!(
                        "int {as_i64} out of range for isize"
                    ))
                })
            }
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected int for isize".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0003_0005
    }
    fn type_name() -> &'static str {
        "isize"
    }
}

// i128: encode as Int, but panics on encode if outside i64 range
impl Crous for i128 {
    fn to_crous_value(&self) -> Value {
        Value::Int(i64::try_from(*self).expect("i128 value exceeds i64 range for Crous encoding"))
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Int(n) => Ok(i128::from(*n)),
            Value::UInt(n) => Ok(i128::from(*n)),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected int for i128".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0003_0006
    }
    fn type_name() -> &'static str {
        "i128"
    }
}

// --- Floating point ---

impl Crous for f64 {
    fn to_crous_value(&self) -> Value {
        Value::Float(*self)
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Float(f) => Ok(*f),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected float".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0005
    }
    fn type_name() -> &'static str {
        "f64"
    }
}

impl Crous for f32 {
    fn to_crous_value(&self) -> Value {
        Value::Float(f64::from(*self))
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Float(f) => Ok(*f as f32),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected float for f32".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0005_0001
    }
    fn type_name() -> &'static str {
        "f32"
    }
}

// --- String types ---

impl Crous for String {
    fn to_crous_value(&self) -> Value {
        Value::Str(self.clone())
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Str(s) => Ok(s.clone()),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected string".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0001
    }
    fn type_name() -> &'static str {
        "String"
    }
}

impl Crous for Box<str> {
    fn to_crous_value(&self) -> Value {
        Value::Str(self.to_string())
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Str(s) => Ok(s.clone().into_boxed_str()),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected string for Box<str>".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0001_0001
    }
    fn type_name() -> &'static str {
        "Box<str>"
    }
}

// --- Raw bytes newtype ---

/// Newtype wrapper for `Vec<u8>` that serializes as `Value::Bytes` (binary blob).
///
/// Use this instead of `Vec<u8>` when you want the raw-bytes wire encoding.
/// Plain `Vec<u8>` encodes as an array of unsigned integers via the generic
/// `Vec<T: Crous>` impl.
///
/// # Example
/// ```
/// use crous_core::{Crous, CrousBytes, Value};
///
/// let blob = CrousBytes(vec![0xDE, 0xAD, 0xBE, 0xEF]);
/// assert!(matches!(blob.to_crous_value(), Value::Bytes(_)));
///
/// let arr: Vec<u8> = vec![1, 2, 3];
/// // Vec<u8> uses the generic Vec<T> impl → Array of UInts
/// assert!(matches!(arr.to_crous_value(), Value::Array(_)));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CrousBytes(pub Vec<u8>);

impl CrousBytes {
    /// Create a new `CrousBytes` from a byte vector.
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Consume and return the inner `Vec<u8>`.
    pub fn into_inner(self) -> Vec<u8> {
        self.0
    }

    /// Borrow the inner bytes as a slice.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }
}

impl From<Vec<u8>> for CrousBytes {
    fn from(v: Vec<u8>) -> Self {
        Self(v)
    }
}

impl From<CrousBytes> for Vec<u8> {
    fn from(b: CrousBytes) -> Self {
        b.0
    }
}

impl AsRef<[u8]> for CrousBytes {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl Crous for CrousBytes {
    fn to_crous_value(&self) -> Value {
        Value::Bytes(self.0.clone())
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Bytes(b) => Ok(CrousBytes(b.clone())),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected bytes".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0006
    }
    fn type_name() -> &'static str {
        "CrousBytes"
    }
}

// --- Generic containers ---

impl<T: Crous> Crous for Vec<T> {
    fn to_crous_value(&self) -> Value {
        Value::Array(self.iter().map(|item| item.to_crous_value()).collect())
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Array(items) => items.iter().map(T::from_crous_value).collect(),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected array".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        T::schema_fingerprint()
            .wrapping_mul(31)
            .wrapping_add(0x0010)
    }

    fn type_name() -> &'static str {
        "Vec"
    }
}

impl<T: Crous> Crous for Option<T> {
    fn to_crous_value(&self) -> Value {
        match self {
            Some(v) => v.to_crous_value(),
            None => Value::Null,
        }
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            other => Ok(Some(T::from_crous_value(other)?)),
        }
    }

    fn schema_fingerprint() -> u64 {
        T::schema_fingerprint()
            .wrapping_mul(37)
            .wrapping_add(0x0020)
    }

    fn type_name() -> &'static str {
        "Option"
    }
}

impl<T: Crous> Crous for Box<T> {
    fn to_crous_value(&self) -> Value {
        (**self).to_crous_value()
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        T::from_crous_value(value).map(Box::new)
    }

    fn schema_fingerprint() -> u64 {
        T::schema_fingerprint()
    }

    fn type_name() -> &'static str {
        T::type_name()
    }
}

// --- Map types → Object ---

impl<T: Crous> Crous for HashMap<String, T> {
    fn to_crous_value(&self) -> Value {
        Value::Object(
            self.iter()
                .map(|(k, v)| (k.clone(), v.to_crous_value()))
                .collect(),
        )
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Object(entries) => {
                let mut map = HashMap::with_capacity(entries.len());
                for (k, v) in entries {
                    map.insert(k.clone(), T::from_crous_value(v)?);
                }
                Ok(map)
            }
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected object for HashMap".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        T::schema_fingerprint()
            .wrapping_mul(41)
            .wrapping_add(0x0030)
    }

    fn type_name() -> &'static str {
        "HashMap"
    }
}

impl<T: Crous> Crous for BTreeMap<String, T> {
    fn to_crous_value(&self) -> Value {
        Value::Object(
            self.iter()
                .map(|(k, v)| (k.clone(), v.to_crous_value()))
                .collect(),
        )
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Object(entries) => {
                let mut map = BTreeMap::new();
                for (k, v) in entries {
                    map.insert(k.clone(), T::from_crous_value(v)?);
                }
                Ok(map)
            }
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected object for BTreeMap".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        T::schema_fingerprint()
            .wrapping_mul(43)
            .wrapping_add(0x0031)
    }

    fn type_name() -> &'static str {
        "BTreeMap"
    }
}

// --- Tuple impls (heterogeneous, encoded as Array) ---

macro_rules! impl_crous_tuple {
    ($fp:expr, $($idx:tt : $T:ident),+) => {
        impl<$($T: Crous),+> Crous for ($($T,)+) {
            fn to_crous_value(&self) -> Value {
                Value::Array(vec![
                    $(self.$idx.to_crous_value()),+
                ])
            }

            fn from_crous_value(value: &Value) -> Result<Self> {
                match value {
                    Value::Array(items) => {
                        let mut iter = items.iter();
                        Ok(($(
                            $T::from_crous_value(
                                iter.next().ok_or_else(|| {
                                    crate::error::CrousError::SchemaMismatch(
                                        "tuple: not enough array elements".into()
                                    )
                                })?
                            )?,
                        )+))
                    }
                    _ => Err(crate::error::CrousError::SchemaMismatch(
                        "expected array for tuple".into(),
                    )),
                }
            }

            fn schema_fingerprint() -> u64 { $fp }
            fn type_name() -> &'static str { "tuple" }
        }
    };
}

impl_crous_tuple!(0x0040_0001, 0: A);
impl_crous_tuple!(0x0040_0002, 0: A, 1: B);
impl_crous_tuple!(0x0040_0003, 0: A, 1: B, 2: C);
impl_crous_tuple!(0x0040_0004, 0: A, 1: B, 2: C, 3: D);
impl_crous_tuple!(0x0040_0005, 0: A, 1: B, 2: C, 3: D, 4: E);
impl_crous_tuple!(0x0040_0006, 0: A, 1: B, 2: C, 3: D, 4: E, 5: F);

// --- Unit type ---

impl Crous for () {
    fn to_crous_value(&self) -> Value {
        Value::Null
    }

    fn from_crous_value(value: &Value) -> Result<Self> {
        match value {
            Value::Null => Ok(()),
            _ => Err(crate::error::CrousError::SchemaMismatch(
                "expected null for ()".into(),
            )),
        }
    }

    fn schema_fingerprint() -> u64 {
        0x0000
    }
    fn type_name() -> &'static str {
        "()"
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn u8_roundtrip() {
        let v: u8 = 200;
        let val = v.to_crous_value();
        assert_eq!(val, Value::UInt(200));
        assert_eq!(u8::from_crous_value(&val).unwrap(), 200);
    }

    #[test]
    fn u8_overflow() {
        let val = Value::UInt(256);
        assert!(u8::from_crous_value(&val).is_err());
    }

    #[test]
    fn u16_roundtrip() {
        let v: u16 = 60000;
        let val = v.to_crous_value();
        assert_eq!(u16::from_crous_value(&val).unwrap(), 60000);
    }

    #[test]
    fn u32_roundtrip() {
        let v: u32 = u32::MAX;
        let val = v.to_crous_value();
        assert_eq!(u32::from_crous_value(&val).unwrap(), u32::MAX);
    }

    #[test]
    fn i8_roundtrip() {
        let v: i8 = -42;
        let val = v.to_crous_value();
        assert_eq!(val, Value::Int(-42));
        assert_eq!(i8::from_crous_value(&val).unwrap(), -42);
    }

    #[test]
    fn i8_overflow() {
        let val = Value::Int(200);
        assert!(i8::from_crous_value(&val).is_err());
    }

    #[test]
    fn i16_roundtrip() {
        let v: i16 = -30000;
        let val = v.to_crous_value();
        assert_eq!(i16::from_crous_value(&val).unwrap(), -30000);
    }

    #[test]
    fn i32_roundtrip() {
        let v: i32 = i32::MIN;
        let val = v.to_crous_value();
        assert_eq!(i32::from_crous_value(&val).unwrap(), i32::MIN);
    }

    #[test]
    fn i32_from_uint_compat() {
        // Signed types should accept UInt values when they fit.
        let val = Value::UInt(42);
        assert_eq!(i32::from_crous_value(&val).unwrap(), 42);
    }

    #[test]
    fn f32_roundtrip() {
        let v: f32 = 2.78;
        let val = v.to_crous_value();
        assert!(matches!(val, Value::Float(_)));
        let back = f32::from_crous_value(&val).unwrap();
        assert!((back - 2.78).abs() < 1e-5);
    }

    #[test]
    fn vec_u8_is_array() {
        let v: Vec<u8> = vec![1, 2, 3];
        let val = v.to_crous_value();
        // Vec<u8> uses the generic Vec<T> impl → Array of UInts.
        assert!(matches!(val, Value::Array(_)));
        let back = Vec::<u8>::from_crous_value(&val).unwrap();
        assert_eq!(back, vec![1, 2, 3]);
    }

    #[test]
    fn crous_bytes_is_bytes() {
        let blob = CrousBytes(vec![0xDE, 0xAD, 0xBE, 0xEF]);
        let val = blob.to_crous_value();
        assert!(matches!(val, Value::Bytes(_)));
        let back = CrousBytes::from_crous_value(&val).unwrap();
        assert_eq!(back.0, vec![0xDE, 0xAD, 0xBE, 0xEF]);
    }

    #[test]
    fn box_str_roundtrip() {
        let s: Box<str> = "hello".into();
        let val = s.to_crous_value();
        assert_eq!(val, Value::Str("hello".into()));
        let back = Box::<str>::from_crous_value(&val).unwrap();
        assert_eq!(&*back, "hello");
    }

    #[test]
    fn box_t_roundtrip() {
        let v: Box<u32> = Box::new(42);
        let val = v.to_crous_value();
        assert_eq!(val, Value::UInt(42));
        let back = Box::<u32>::from_crous_value(&val).unwrap();
        assert_eq!(*back, 42);
    }

    #[test]
    fn hashmap_roundtrip() {
        let mut map = HashMap::new();
        map.insert("x".to_string(), 10u64);
        map.insert("y".to_string(), 20u64);

        let val = map.to_crous_value();
        assert!(matches!(val, Value::Object(_)));

        let back = HashMap::<String, u64>::from_crous_value(&val).unwrap();
        assert_eq!(back.get("x"), Some(&10));
        assert_eq!(back.get("y"), Some(&20));
    }

    #[test]
    fn btreemap_roundtrip() {
        let mut map = BTreeMap::new();
        map.insert("a".to_string(), Value::Bool(true));
        map.insert("b".to_string(), Value::UInt(7));

        // BTreeMap<String, Value> doesn't work since Value doesn't impl Crous,
        // but BTreeMap<String, bool> does.
        let mut m2 = BTreeMap::new();
        m2.insert("flag".to_string(), true);
        m2.insert("enabled".to_string(), false);
        let val = m2.to_crous_value();
        let back = BTreeMap::<String, bool>::from_crous_value(&val).unwrap();
        assert_eq!(back.get("flag"), Some(&true));
        assert_eq!(back.get("enabled"), Some(&false));
    }

    #[test]
    fn tuple2_roundtrip() {
        let t = (42u32, "hello".to_string());
        let val = t.to_crous_value();
        assert!(matches!(val, Value::Array(_)));
        let back = <(u32, String)>::from_crous_value(&val).unwrap();
        assert_eq!(back, (42, "hello".to_string()));
    }

    #[test]
    fn tuple3_roundtrip() {
        let t = (true, -5i16, 2.78f64);
        let val = t.to_crous_value();
        let back = <(bool, i16, f64)>::from_crous_value(&val).unwrap();
        assert!(back.0);
        assert_eq!(back.1, -5);
        assert!((back.2 - 2.78).abs() < 1e-10);
    }

    #[test]
    fn unit_roundtrip() {
        let val = ().to_crous_value();
        assert_eq!(val, Value::Null);
        assert_eq!(<()>::from_crous_value(&val).unwrap(), ());
    }

    #[test]
    fn usize_roundtrip() {
        let v: usize = 999;
        let val = v.to_crous_value();
        assert_eq!(usize::from_crous_value(&val).unwrap(), 999);
    }

    #[test]
    fn isize_roundtrip() {
        let v: isize = -999;
        let val = v.to_crous_value();
        assert_eq!(isize::from_crous_value(&val).unwrap(), -999);
    }

    #[test]
    fn u128_small_roundtrip() {
        let v: u128 = 123456;
        let val = v.to_crous_value();
        assert_eq!(u128::from_crous_value(&val).unwrap(), 123456);
    }

    #[test]
    fn i128_small_roundtrip() {
        let v: i128 = -123456;
        let val = v.to_crous_value();
        assert_eq!(i128::from_crous_value(&val).unwrap(), -123456);
    }

    #[test]
    fn nested_option_vec() {
        let v: Option<Vec<u8>> = Some(vec![10, 20, 30]);
        let val = v.to_crous_value();
        let back = Option::<Vec<u8>>::from_crous_value(&val).unwrap();
        assert_eq!(back, Some(vec![10, 20, 30]));
    }

    #[test]
    fn option_none() {
        let v: Option<u8> = None;
        let val = v.to_crous_value();
        assert_eq!(val, Value::Null);
        let back = Option::<u8>::from_crous_value(&val).unwrap();
        assert_eq!(back, None);
    }

    #[test]
    fn full_binary_roundtrip_u8() {
        // Verify u8 survives encode → binary → decode.
        let v: u8 = 42;
        let bytes = v.to_crous_bytes().unwrap();
        let back = u8::from_crous_bytes(&bytes).unwrap();
        assert_eq!(back, 42);
    }

    #[test]
    fn full_binary_roundtrip_crous_bytes() {
        let blob = CrousBytes(vec![1, 2, 3, 4]);
        let bytes = blob.to_crous_bytes().unwrap();
        let back = CrousBytes::from_crous_bytes(&bytes).unwrap();
        assert_eq!(back.0, vec![1, 2, 3, 4]);
    }

    #[test]
    fn full_binary_roundtrip_tuple() {
        let t = (100u16, "world".to_string(), false);
        let bytes = t.to_crous_bytes().unwrap();
        let back = <(u16, String, bool)>::from_crous_bytes(&bytes).unwrap();
        assert_eq!(back, (100, "world".to_string(), false));
    }

    #[test]
    fn full_binary_roundtrip_hashmap() {
        let mut m = HashMap::new();
        m.insert("key".to_string(), 99u32);
        let bytes = m.to_crous_bytes().unwrap();
        let back = HashMap::<String, u32>::from_crous_bytes(&bytes).unwrap();
        assert_eq!(back.get("key"), Some(&99));
    }
}