scirs2-io 0.4.2

Input/Output utilities module for SciRS2 (scirs2-io)
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
//! Pure-Rust Protocol Buffer wire format encoder and decoder.
//!
//! This module implements the proto3 wire format at the level required by the
//! schema registry: varint encoding/decoding, field tagging, fixed-width
//! fields, and length-delimited payloads.  It deliberately avoids the `prost`
//! crate to remain dependency-free (COOLJAPAN pure-Rust policy).
//!
//! # Wire type table
//!
//! | ID | Meaning          | Rust type     |
//! |----|------------------|---------------|
//! | 0  | Varint           | u64           |
//! | 1  | 64-bit fixed     | [u8; 8]       |
//! | 2  | Length-delimited | `Vec<u8>`     |
//! | 5  | 32-bit fixed     | [u8; 4]       |
//!
//! Wire types 3 and 4 (start/end group) are not supported.

use super::types::{
    FieldDescriptor, FieldType, FieldValue, MessageDescriptor, SchemaRegistryError,
    SchemaRegistryResult,
};

// ─── Wire type ───────────────────────────────────────────────────────────────

/// The four wire types used in this implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WireType {
    /// Wire type 0 — variable-length integer (LEB-128).
    Varint,
    /// Wire type 1 — 64-bit little-endian fixed-width.
    Fixed64,
    /// Wire type 2 — length-delimited byte sequence.
    LengthDelimited,
    /// Wire type 5 — 32-bit little-endian fixed-width.
    Fixed32,
}

impl WireType {
    /// Return the numeric wire-type id as used in the proto tag varint.
    pub fn id(self) -> u32 {
        match self {
            WireType::Varint => 0,
            WireType::Fixed64 => 1,
            WireType::LengthDelimited => 2,
            WireType::Fixed32 => 5,
        }
    }

    /// Parse a numeric wire-type id.
    pub fn from_id(id: u32) -> SchemaRegistryResult<Self> {
        match id {
            0 => Ok(WireType::Varint),
            1 => Ok(WireType::Fixed64),
            2 => Ok(WireType::LengthDelimited),
            5 => Ok(WireType::Fixed32),
            _ => Err(SchemaRegistryError::WireFormat(format!(
                "unknown wire type id: {id}"
            ))),
        }
    }

    /// Return the wire type implied by a [`FieldType`].
    pub fn for_field_type(ft: &FieldType) -> Self {
        match ft {
            FieldType::Int32
            | FieldType::Int64
            | FieldType::UInt32
            | FieldType::UInt64
            | FieldType::Bool => WireType::Varint,
            FieldType::Float => WireType::Fixed32,
            FieldType::Double => WireType::Fixed64,
            FieldType::String
            | FieldType::Bytes
            | FieldType::Message(_)
            | FieldType::Repeated(_) => WireType::LengthDelimited,
        }
    }
}

// ─── WireValue ────────────────────────────────────────────────────────────────

/// A raw decoded wire value before schema-guided interpretation.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum WireValue {
    /// Wire type 0 payload.
    Varint(u64),
    /// Wire type 1 payload (little-endian bytes).
    Fixed64([u8; 8]),
    /// Wire type 2 payload.
    LengthDelimited(Vec<u8>),
    /// Wire type 5 payload (little-endian bytes).
    Fixed32([u8; 4]),
}

// ─── Varint primitives ───────────────────────────────────────────────────────

/// Encode `value` as a Protocol Buffer varint (LEB-128 variant) and append it
/// to `buf`.
pub fn encode_varint(value: u64, buf: &mut Vec<u8>) {
    let mut v = value;
    loop {
        let byte = (v & 0x7f) as u8;
        v >>= 7;
        if v == 0 {
            buf.push(byte);
            break;
        }
        buf.push(byte | 0x80);
    }
}

/// Decode a varint from `buf` starting at `*pos`.  On success, advances
/// `*pos` past the varint bytes and returns the decoded value.  Returns
/// `None` on truncated input or overflow.
pub fn decode_varint(buf: &[u8], pos: &mut usize) -> Option<u64> {
    let mut result: u64 = 0;
    let mut shift: u32 = 0;
    loop {
        if *pos >= buf.len() || shift >= 64 {
            return None;
        }
        let byte = buf[*pos];
        *pos += 1;
        result |= ((byte & 0x7f) as u64) << shift;
        shift += 7;
        if byte & 0x80 == 0 {
            return Some(result);
        }
    }
}

// ─── Field tag encoding ──────────────────────────────────────────────────────

/// Encode the field tag (field_number << 3 | wire_type) and append to `buf`.
pub fn encode_field(field_number: u32, wire_type: WireType, buf: &mut Vec<u8>) {
    let tag: u64 = ((field_number as u64) << 3) | (wire_type.id() as u64);
    encode_varint(tag, buf);
}

// ─── ProtoEncoder ────────────────────────────────────────────────────────────

/// Fluent builder for constructing Protocol Buffer messages byte-by-byte.
///
/// Each method encodes one field (tag + payload) and returns `&mut Self` for
/// chaining.  Call [`build`](ProtoEncoder::build) to extract the completed byte
/// vector.
///
/// # Example
///
/// ```rust
/// use scirs2_io::schema_registry::wire::ProtoEncoder;
///
/// let bytes = ProtoEncoder::new()
///     .int64(1, 12345)
///     .string(2, "hello world")
///     .build();
/// assert!(!bytes.is_empty());
/// ```
#[derive(Debug, Default)]
pub struct ProtoEncoder {
    buf: Vec<u8>,
}

impl ProtoEncoder {
    /// Create a new, empty encoder.
    pub fn new() -> Self {
        Self { buf: Vec::new() }
    }

    /// Encode a signed 32-bit integer as a varint (wire type 0).
    pub fn int32(mut self, field_number: u32, value: i32) -> Self {
        encode_field(field_number, WireType::Varint, &mut self.buf);
        encode_varint(value as u64, &mut self.buf);
        self
    }

    /// Encode a signed 64-bit integer as a varint (wire type 0).
    pub fn int64(mut self, field_number: u32, value: i64) -> Self {
        encode_field(field_number, WireType::Varint, &mut self.buf);
        encode_varint(value as u64, &mut self.buf);
        self
    }

    /// Encode an unsigned 32-bit integer as a varint (wire type 0).
    pub fn uint32(mut self, field_number: u32, value: u32) -> Self {
        encode_field(field_number, WireType::Varint, &mut self.buf);
        encode_varint(value as u64, &mut self.buf);
        self
    }

    /// Encode an unsigned 64-bit integer as a varint (wire type 0).
    pub fn uint64(mut self, field_number: u32, value: u64) -> Self {
        encode_field(field_number, WireType::Varint, &mut self.buf);
        encode_varint(value, &mut self.buf);
        self
    }

    /// Encode a boolean as a varint (wire type 0).
    pub fn bool(mut self, field_number: u32, value: bool) -> Self {
        encode_field(field_number, WireType::Varint, &mut self.buf);
        encode_varint(value as u64, &mut self.buf);
        self
    }

    /// Encode a 32-bit float (wire type 5).
    pub fn float(mut self, field_number: u32, value: f32) -> Self {
        encode_field(field_number, WireType::Fixed32, &mut self.buf);
        self.buf.extend_from_slice(&value.to_le_bytes());
        self
    }

    /// Encode a 64-bit float (wire type 1).
    pub fn double(mut self, field_number: u32, value: f64) -> Self {
        encode_field(field_number, WireType::Fixed64, &mut self.buf);
        self.buf.extend_from_slice(&value.to_le_bytes());
        self
    }

    /// Encode a UTF-8 string as a length-delimited field (wire type 2).
    pub fn string(mut self, field_number: u32, value: &str) -> Self {
        self.write_length_delimited(field_number, value.as_bytes());
        self
    }

    /// Encode a raw byte sequence as a length-delimited field (wire type 2).
    pub fn bytes(mut self, field_number: u32, value: &[u8]) -> Self {
        self.write_length_delimited(field_number, value);
        self
    }

    /// Encode a pre-encoded nested message as a length-delimited field (wire type 2).
    pub fn message(mut self, field_number: u32, nested_bytes: &[u8]) -> Self {
        self.write_length_delimited(field_number, nested_bytes);
        self
    }

    /// Consume the encoder and return the completed byte vector.
    pub fn build(self) -> Vec<u8> {
        self.buf
    }

    // ── Internal helpers ────────────────────────────────────────────────────

    fn write_length_delimited(&mut self, field_number: u32, data: &[u8]) {
        encode_field(field_number, WireType::LengthDelimited, &mut self.buf);
        encode_varint(data.len() as u64, &mut self.buf);
        self.buf.extend_from_slice(data);
    }
}

// ─── ProtoDecoder ────────────────────────────────────────────────────────────

/// Iterator-style decoder over a Protocol Buffer wire-format byte slice.
///
/// Each call to [`next_field`](ProtoDecoder::next_field) consumes one complete
/// field (tag + payload) from the buffer and returns `(field_number, WireValue)`.
pub struct ProtoDecoder<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> ProtoDecoder<'a> {
    /// Create a new decoder over `buf`.
    pub fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Returns `true` when the entire buffer has been consumed.
    pub fn is_empty(&self) -> bool {
        self.pos >= self.buf.len()
    }

    /// Decode the next field from the buffer.
    ///
    /// Returns `None` at end-of-buffer, or `Some(Err(_))` on a malformed
    /// message.
    pub fn next_field(&mut self) -> Option<SchemaRegistryResult<(u32, WireValue)>> {
        if self.is_empty() {
            return None;
        }

        // Decode tag varint
        let tag = decode_varint(self.buf, &mut self.pos)?;
        let wire_type_id = (tag & 0x07) as u32;
        let field_number = (tag >> 3) as u32;

        let wire_type = match WireType::from_id(wire_type_id) {
            Ok(wt) => wt,
            Err(e) => return Some(Err(e)),
        };

        let value = match self.decode_payload(wire_type) {
            Ok(v) => v,
            Err(e) => return Some(Err(e)),
        };

        Some(Ok((field_number, value)))
    }

    /// Decode all remaining fields into a `Vec`.
    pub fn collect_all(&mut self) -> SchemaRegistryResult<Vec<(u32, WireValue)>> {
        let mut out = Vec::new();
        while let Some(result) = self.next_field() {
            out.push(result?);
        }
        Ok(out)
    }

    // ── Internal helpers ────────────────────────────────────────────────────

    fn decode_payload(&mut self, wire_type: WireType) -> SchemaRegistryResult<WireValue> {
        match wire_type {
            WireType::Varint => {
                let v = decode_varint(self.buf, &mut self.pos).ok_or_else(|| {
                    SchemaRegistryError::WireFormat("truncated varint".to_string())
                })?;
                Ok(WireValue::Varint(v))
            }
            WireType::Fixed64 => {
                if self.pos + 8 > self.buf.len() {
                    return Err(SchemaRegistryError::WireFormat(
                        "truncated fixed64 field".to_string(),
                    ));
                }
                let mut b = [0u8; 8];
                b.copy_from_slice(&self.buf[self.pos..self.pos + 8]);
                self.pos += 8;
                Ok(WireValue::Fixed64(b))
            }
            WireType::LengthDelimited => {
                let len = decode_varint(self.buf, &mut self.pos).ok_or_else(|| {
                    SchemaRegistryError::WireFormat(
                        "truncated length prefix in length-delimited field".to_string(),
                    )
                })? as usize;

                if self.pos + len > self.buf.len() {
                    return Err(SchemaRegistryError::WireFormat(format!(
                        "length-delimited field claims {len} bytes but only {} remain",
                        self.buf.len() - self.pos
                    )));
                }
                let payload = self.buf[self.pos..self.pos + len].to_vec();
                self.pos += len;
                Ok(WireValue::LengthDelimited(payload))
            }
            WireType::Fixed32 => {
                if self.pos + 4 > self.buf.len() {
                    return Err(SchemaRegistryError::WireFormat(
                        "truncated fixed32 field".to_string(),
                    ));
                }
                let mut b = [0u8; 4];
                b.copy_from_slice(&self.buf[self.pos..self.pos + 4]);
                self.pos += 4;
                Ok(WireValue::Fixed32(b))
            }
        }
    }
}

// ─── Schema-guided encode / decode ────────────────────────────────────────────

/// Encode a set of `(field_number, FieldValue)` pairs according to the message
/// descriptor and return the wire-format bytes.
///
/// Fields not declared in the descriptor are silently skipped.  The field
/// values are encoded in the order they appear in `values`.
pub fn encode_message(schema: &MessageDescriptor, values: &[(u32, FieldValue)]) -> Vec<u8> {
    let mut buf = Vec::new();

    for (field_number, value) in values {
        // Only encode fields that appear in the descriptor.
        let field_desc = match schema.field_by_number(*field_number) {
            Some(fd) => fd,
            None => continue,
        };

        encode_field_value(*field_number, &field_desc.field_type, value, &mut buf);
    }

    buf
}

/// Decode wire-format `bytes` into a list of `(field_name, FieldValue)` pairs
/// using the supplied message descriptor for type guidance.
///
/// Unknown field numbers (not in the descriptor) are silently skipped — this
/// mirrors proto3 unknown-field handling and allows forward-compatible readers.
pub fn decode_message(
    schema: &MessageDescriptor,
    bytes: &[u8],
) -> SchemaRegistryResult<Vec<(std::string::String, FieldValue)>> {
    let mut decoder = ProtoDecoder::new(bytes);
    let raw_fields = decoder.collect_all()?;
    let mut out = Vec::new();

    for (field_number, wire_value) in raw_fields {
        let field_desc = match schema.field_by_number(field_number) {
            Some(fd) => fd,
            None => continue, // Unknown field — skip
        };

        let field_value = wire_value_to_field_value(&field_desc.field_type, wire_value)?;
        out.push((field_desc.name.clone(), field_value));
    }

    Ok(out)
}

// ─── Internal helpers ────────────────────────────────────────────────────────

fn encode_field_value(
    field_number: u32,
    field_type: &FieldType,
    value: &FieldValue,
    buf: &mut Vec<u8>,
) {
    match (field_type, value) {
        (FieldType::Int32, FieldValue::Int32(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::Int64, FieldValue::Int64(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::Int64, FieldValue::Int32(v)) => {
            // Widening: int32 into int64 field
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::UInt32, FieldValue::UInt32(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::UInt64, FieldValue::UInt64(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v, buf);
        }
        (FieldType::UInt64, FieldValue::UInt32(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::Bool, FieldValue::Bool(v)) => {
            encode_field(field_number, WireType::Varint, buf);
            encode_varint(*v as u64, buf);
        }
        (FieldType::Float, FieldValue::Float(v)) => {
            encode_field(field_number, WireType::Fixed32, buf);
            buf.extend_from_slice(&v.to_le_bytes());
        }
        (FieldType::Double, FieldValue::Double(v)) => {
            encode_field(field_number, WireType::Fixed64, buf);
            buf.extend_from_slice(&v.to_le_bytes());
        }
        (FieldType::Double, FieldValue::Float(v)) => {
            encode_field(field_number, WireType::Fixed64, buf);
            buf.extend_from_slice(&(*v as f64).to_le_bytes());
        }
        (FieldType::String, FieldValue::Str(s)) => {
            let data = s.as_bytes();
            encode_field(field_number, WireType::LengthDelimited, buf);
            encode_varint(data.len() as u64, buf);
            buf.extend_from_slice(data);
        }
        (FieldType::Bytes, FieldValue::Bytes(data)) => {
            encode_field(field_number, WireType::LengthDelimited, buf);
            encode_varint(data.len() as u64, buf);
            buf.extend_from_slice(data);
        }
        (FieldType::Message(_), FieldValue::Message(data)) => {
            encode_field(field_number, WireType::LengthDelimited, buf);
            encode_varint(data.len() as u64, buf);
            buf.extend_from_slice(data);
        }
        (FieldType::Repeated(_), FieldValue::Bytes(data)) => {
            // Pre-encoded repeated/packed field
            encode_field(field_number, WireType::LengthDelimited, buf);
            encode_varint(data.len() as u64, buf);
            buf.extend_from_slice(data);
        }
        _ => {
            // Type mismatch — silently skip (caller should validate first)
        }
    }
}

fn wire_value_to_field_value(ft: &FieldType, wv: WireValue) -> SchemaRegistryResult<FieldValue> {
    match (ft, wv) {
        (FieldType::Int32, WireValue::Varint(v)) => Ok(FieldValue::Int32(v as i32)),
        (FieldType::Int64, WireValue::Varint(v)) => Ok(FieldValue::Int64(v as i64)),
        (FieldType::UInt32, WireValue::Varint(v)) => Ok(FieldValue::UInt32(v as u32)),
        (FieldType::UInt64, WireValue::Varint(v)) => Ok(FieldValue::UInt64(v)),
        (FieldType::Bool, WireValue::Varint(v)) => Ok(FieldValue::Bool(v != 0)),
        (FieldType::Float, WireValue::Fixed32(b)) => Ok(FieldValue::Float(f32::from_le_bytes(b))),
        (FieldType::Double, WireValue::Fixed64(b)) => Ok(FieldValue::Double(f64::from_le_bytes(b))),
        (FieldType::String, WireValue::LengthDelimited(data)) => {
            let s = std::string::String::from_utf8(data).map_err(|e| {
                SchemaRegistryError::WireFormat(format!("invalid UTF-8 in string field: {e}"))
            })?;
            Ok(FieldValue::Str(s))
        }
        (FieldType::Bytes, WireValue::LengthDelimited(data)) => Ok(FieldValue::Bytes(data)),
        (FieldType::Message(_), WireValue::LengthDelimited(data)) => Ok(FieldValue::Message(data)),
        (FieldType::Repeated(_), WireValue::LengthDelimited(data)) => Ok(FieldValue::Bytes(data)),
        (ft, wv) => Err(SchemaRegistryError::WireFormat(format!(
            "wire type mismatch for field type {}: got {:?}",
            ft.proto_name(),
            wv
        ))),
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    // ── Varint ────────────────────────────────────────────────────────────────

    #[test]
    fn test_varint_zero() {
        let mut buf = Vec::new();
        encode_varint(0, &mut buf);
        assert_eq!(buf, [0x00]);
        let mut pos = 0;
        assert_eq!(decode_varint(&buf, &mut pos), Some(0));
        assert_eq!(pos, 1);
    }

    #[test]
    fn test_varint_one_byte_boundary() {
        let mut buf = Vec::new();
        encode_varint(127, &mut buf);
        assert_eq!(buf, [0x7f]);
    }

    #[test]
    fn test_varint_two_byte_boundary() {
        let mut buf = Vec::new();
        encode_varint(128, &mut buf);
        assert_eq!(buf, [0x80, 0x01]);
    }

    #[test]
    fn test_varint_300() {
        let mut buf = Vec::new();
        encode_varint(300, &mut buf);
        assert_eq!(buf, [0xac, 0x02]);
        let mut pos = 0;
        assert_eq!(decode_varint(&buf, &mut pos), Some(300));
    }

    #[test]
    fn test_varint_u64_max() {
        let mut buf = Vec::new();
        encode_varint(u64::MAX, &mut buf);
        assert_eq!(buf.len(), 10);
        let mut pos = 0;
        assert_eq!(decode_varint(&buf, &mut pos), Some(u64::MAX));
    }

    #[test]
    fn test_varint_roundtrip_sequence() {
        let values: &[u64] = &[0, 1, 127, 128, 255, 1024, 65535, 1 << 32, u64::MAX];
        for &v in values {
            let mut buf = Vec::new();
            encode_varint(v, &mut buf);
            let mut pos = 0;
            assert_eq!(decode_varint(&buf, &mut pos), Some(v), "value={v}");
        }
    }

    #[test]
    fn test_decode_varint_truncated_returns_none() {
        // A multi-byte varint that is cut short
        let buf = [0x80]; // continuation bit set but no following byte
        let mut pos = 0;
        assert_eq!(decode_varint(&buf, &mut pos), None);
    }

    // ── Field tag encoding ────────────────────────────────────────────────────

    #[test]
    fn test_wire_type_tag_field_1_varint() {
        // field 1, wire type 0 → tag = (1 << 3) | 0 = 8
        let mut buf = Vec::new();
        encode_field(1, WireType::Varint, &mut buf);
        assert_eq!(buf, [0x08]);
    }

    #[test]
    fn test_wire_type_tag_field_2_len_delim() {
        // field 2, wire type 2 → tag = (2 << 3) | 2 = 18
        let mut buf = Vec::new();
        encode_field(2, WireType::LengthDelimited, &mut buf);
        assert_eq!(buf, [0x12]);
    }

    // ── ProtoEncoder ─────────────────────────────────────────────────────────

    #[test]
    fn test_proto_encoder_int32() {
        let bytes = ProtoEncoder::new().int32(1, 150).build();
        // tag = 0x08, varint 150 = [0x96, 0x01]
        assert_eq!(bytes, [0x08, 0x96, 0x01]);
    }

    #[test]
    fn test_proto_encoder_string() {
        let bytes = ProtoEncoder::new().string(1, "testing").build();
        // tag = 0x0a (field 1, wire type 2), length = 7, then "testing"
        assert_eq!(bytes[0], 0x0a);
        assert_eq!(bytes[1], 7);
        assert_eq!(&bytes[2..], b"testing");
    }

    #[test]
    fn test_proto_encoder_bool_true() {
        let bytes = ProtoEncoder::new().bool(1, true).build();
        assert_eq!(bytes, [0x08, 0x01]);
    }

    #[test]
    fn test_proto_encoder_bool_false() {
        let bytes = ProtoEncoder::new().bool(1, false).build();
        assert_eq!(bytes, [0x08, 0x00]);
    }

    #[test]
    fn test_proto_encoder_float() {
        let v = 1.0_f32;
        let bytes = ProtoEncoder::new().float(1, v).build();
        // tag field 1 wire type 5 = (1 << 3) | 5 = 0x0d
        assert_eq!(bytes[0], 0x0d);
        let decoded = f32::from_le_bytes(bytes[1..5].try_into().expect("slice"));
        assert!((decoded - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_proto_encoder_double() {
        let v = std::f64::consts::PI;
        let bytes = ProtoEncoder::new().double(1, v).build();
        // tag field 1 wire type 1 = (1 << 3) | 1 = 0x09
        assert_eq!(bytes[0], 0x09);
        let decoded = f64::from_le_bytes(bytes[1..9].try_into().expect("slice"));
        assert!((decoded - std::f64::consts::PI).abs() < 1e-12);
    }

    #[test]
    fn test_proto_encoder_bytes() {
        let data = b"\xde\xad\xbe\xef";
        let bytes = ProtoEncoder::new().bytes(1, data).build();
        assert_eq!(bytes[0], 0x0a); // field 1, wire type 2
        assert_eq!(bytes[1], 4); // length
        assert_eq!(&bytes[2..], data);
    }

    #[test]
    fn test_proto_encoder_message_nested() {
        let inner = ProtoEncoder::new().int32(1, 42).build();
        let outer = ProtoEncoder::new().message(1, &inner).build();
        // The outer message wraps the inner as a length-delimited field
        let mut dec = ProtoDecoder::new(&outer);
        let (fn_, wv) = dec.next_field().expect("field").expect("ok");
        assert_eq!(fn_, 1);
        if let WireValue::LengthDelimited(payload) = wv {
            assert_eq!(payload, inner);
        } else {
            panic!("expected LengthDelimited");
        }
    }

    // ── ProtoDecoder ─────────────────────────────────────────────────────────

    #[test]
    fn test_proto_decoder_varint_field() {
        let bytes = ProtoEncoder::new().int64(3, 9999).build();
        let mut dec = ProtoDecoder::new(&bytes);
        let (fn_, wv) = dec.next_field().expect("field").expect("ok");
        assert_eq!(fn_, 3);
        assert_eq!(wv, WireValue::Varint(9999));
        assert!(dec.is_empty());
    }

    #[test]
    fn test_proto_decoder_multiple_fields() {
        let bytes = ProtoEncoder::new()
            .int32(1, 1)
            .string(2, "abc")
            .bool(3, true)
            .build();

        let mut dec = ProtoDecoder::new(&bytes);
        let fields = dec.collect_all().expect("ok");
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0].0, 1);
        assert_eq!(fields[1].0, 2);
        assert_eq!(fields[2].0, 3);
    }

    // ── Schema-guided encode/decode ───────────────────────────────────────────

    #[test]
    fn test_encode_decode_all_field_types() {
        use crate::schema_registry::types::FieldDescriptor;

        let desc = MessageDescriptor::new("AllTypes", "test")
            .with_field(FieldDescriptor::optional(1, "i32", FieldType::Int32))
            .with_field(FieldDescriptor::optional(2, "i64", FieldType::Int64))
            .with_field(FieldDescriptor::optional(3, "u32", FieldType::UInt32))
            .with_field(FieldDescriptor::optional(4, "u64", FieldType::UInt64))
            .with_field(FieldDescriptor::optional(5, "flt", FieldType::Float))
            .with_field(FieldDescriptor::optional(6, "dbl", FieldType::Double))
            .with_field(FieldDescriptor::optional(7, "b", FieldType::Bool))
            .with_field(FieldDescriptor::optional(8, "s", FieldType::String))
            .with_field(FieldDescriptor::optional(9, "raw", FieldType::Bytes));

        let values: Vec<(u32, FieldValue)> = vec![
            (1, FieldValue::Int32(-7)),
            (2, FieldValue::Int64(-9_999_999_999)),
            (3, FieldValue::UInt32(42)),
            (4, FieldValue::UInt64(u64::MAX)),
            (5, FieldValue::Float(3.25)),
            (6, FieldValue::Double(2.345_678_901)),
            (7, FieldValue::Bool(true)),
            (8, FieldValue::Str("hello".to_string())),
            (9, FieldValue::Bytes(vec![0xca, 0xfe])),
        ];

        let bytes = encode_message(&desc, &values);
        let decoded = decode_message(&desc, &bytes).expect("decode ok");
        assert_eq!(decoded.len(), 9);

        assert_eq!(decoded[0], ("i32".to_string(), FieldValue::Int32(-7)));
        assert_eq!(
            decoded[1],
            ("i64".to_string(), FieldValue::Int64(-9_999_999_999))
        );
        assert_eq!(decoded[2], ("u32".to_string(), FieldValue::UInt32(42)));
        assert_eq!(
            decoded[3],
            ("u64".to_string(), FieldValue::UInt64(u64::MAX))
        );
        assert_eq!(decoded[6], ("b".to_string(), FieldValue::Bool(true)));
        assert_eq!(
            decoded[7],
            ("s".to_string(), FieldValue::Str("hello".to_string()))
        );
        assert_eq!(
            decoded[8],
            ("raw".to_string(), FieldValue::Bytes(vec![0xca, 0xfe]))
        );
    }

    #[test]
    fn test_message_encode_decode_roundtrip() {
        use crate::schema_registry::types::FieldDescriptor;

        let desc = MessageDescriptor::new("Point", "geometry")
            .with_field(FieldDescriptor::optional(1, "x", FieldType::Double))
            .with_field(FieldDescriptor::optional(2, "y", FieldType::Double))
            .with_field(FieldDescriptor::optional(3, "label", FieldType::String));

        let values = vec![
            (1, FieldValue::Double(1.5)),
            (2, FieldValue::Double(-3.75)),
            (3, FieldValue::Str("origin".to_string())),
        ];

        let encoded = encode_message(&desc, &values);
        let decoded = decode_message(&desc, &encoded).expect("decode ok");

        assert_eq!(decoded.len(), 3);
        assert_eq!(decoded[2].1, FieldValue::Str("origin".to_string()));
    }

    #[test]
    fn test_nested_message_encoding() {
        use crate::schema_registry::types::FieldDescriptor;

        // Inner: { id: int32 }
        let inner_desc = MessageDescriptor::new("Inner", "test")
            .with_field(FieldDescriptor::optional(1, "id", FieldType::Int32));

        let inner_bytes = encode_message(&inner_desc, &[(1, FieldValue::Int32(99))]);

        // Outer: { nested: message(Inner) }
        let outer_desc = MessageDescriptor::new("Outer", "test").with_field(
            FieldDescriptor::optional(1, "nested", FieldType::Message("Inner".to_string())),
        );

        let outer_values = vec![(1, FieldValue::Message(inner_bytes.clone()))];
        let outer_bytes = encode_message(&outer_desc, &outer_values);
        let outer_decoded = decode_message(&outer_desc, &outer_bytes).expect("ok");

        assert_eq!(outer_decoded.len(), 1);
        if let FieldValue::Message(payload) = &outer_decoded[0].1 {
            assert_eq!(payload, &inner_bytes);
        } else {
            panic!("expected Message variant");
        }
    }

    #[test]
    fn test_repeated_field_encoding() {
        use crate::schema_registry::types::FieldDescriptor;

        // Repeated int32: packed encoding — client pre-packs as bytes
        let desc = MessageDescriptor::new("Bag", "test").with_field(FieldDescriptor::optional(
            1,
            "items",
            FieldType::Repeated(Box::new(FieldType::Int32)),
        ));

        // Pack [1, 2, 3] as varints
        let mut packed = Vec::new();
        for v in [1u64, 2, 3] {
            encode_varint(v, &mut packed);
        }

        let values = vec![(1, FieldValue::Bytes(packed.clone()))];
        let bytes = encode_message(&desc, &values);
        let decoded = decode_message(&desc, &bytes).expect("ok");

        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].0, "items");
        if let FieldValue::Bytes(b) = &decoded[0].1 {
            assert_eq!(b, &packed);
        } else {
            panic!("expected Bytes");
        }
    }

    #[test]
    fn test_unknown_field_skipped_on_decode() {
        use crate::schema_registry::types::FieldDescriptor;

        // Encode a message with two fields
        let desc_full = MessageDescriptor::new("M", "test")
            .with_field(FieldDescriptor::optional(1, "a", FieldType::Int32))
            .with_field(FieldDescriptor::optional(2, "b", FieldType::String));

        let bytes = encode_message(
            &desc_full,
            &[
                (1, FieldValue::Int32(7)),
                (2, FieldValue::Str("x".to_string())),
            ],
        );

        // Decode with a schema that only knows about field 1
        let desc_partial = MessageDescriptor::new("M", "test")
            .with_field(FieldDescriptor::optional(1, "a", FieldType::Int32));

        let decoded = decode_message(&desc_partial, &bytes).expect("ok");
        // Field 2 should be silently skipped
        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].1, FieldValue::Int32(7));
    }
}