ignite-v2-client 1.0.1

Apache Ignite v2 Client
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
//! Ergonomic layer over the binary-object codec (see `crate::protocol::binary`):
//! the [`WriteBinary`]/[`ReadBinary`] traits for whole objects, the
//! [`FieldWrite`]/[`FieldRead`] traits for individual fields, and newtypes for
//! Ignite wire types with no direct Rust equivalent (CHAR, DATE, TIME,
//! TIMESTAMP).
//!
//! This module is also the public `binary` facade: it re-exports the
//! lower-level codec types ([`BinaryObject`], [`BinaryObjectBuilder`],
//! [`BinaryObjectReader`]), the metadata model ([`BinaryType`],
//! [`BinaryFieldMeta`], [`BinarySchemaMeta`]), and the id helpers
//! ([`type_id`], [`field_id`], [`schema_id`]) alongside the traits and
//! newtypes defined here.

pub use crate::protocol::binary::metadata::{BinaryFieldMeta, BinarySchemaMeta, BinaryType};
pub use crate::protocol::binary::reader::BinaryObjectReader;
pub use crate::protocol::binary::value::BinaryObject;
pub use crate::protocol::binary::writer::BinaryObjectBuilder;
pub use crate::protocol::binary::{field_id, schema_id, type_id};
pub use crate::protocol::types::type_code;
pub use ignite_client_derive::IgniteBinary;

use bigdecimal::BigDecimal;
use uuid::Uuid;

use crate::Result;
use crate::protocol::error::{ProtocolError, value_type_name};
use crate::protocol::types::IgniteValue;

// ─── Newtypes ─────────────────────────────────────────────────────────────────
//
// Ignite has four wire types with no direct Rust equivalent (or that would be
// ambiguous against an existing Rust type). Each wraps the field's exact wire
// representation so `FieldWrite`/`FieldRead` can round-trip it unambiguously.

/// Ignite CHAR (type code 7): a single UTF-16 code unit. Distinct from
/// `String` (VARCHAR, type code 9) at the wire level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IgniteChar(pub u16);

/// Ignite DATE (type code 11): milliseconds since the Unix epoch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IgniteDate(pub i64);

/// Ignite TIME (type code 36): nanoseconds since midnight.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IgniteTime(pub i64);

/// Ignite TIMESTAMP (type code 33): `(milliseconds_since_epoch,
/// nanosecond_fraction)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IgniteTimestamp(pub i64, pub i32);

// ─── Traits ─────────────────────────────────────────────────────────────────

/// Serialise `Self` as a whole Ignite binary (complex) object.
pub trait WriteBinary {
    /// The fully-qualified Ignite type name (used to derive the type id).
    fn type_name() -> &'static str;

    /// Write every field of `self` into `b`, returning the builder for
    /// chaining.
    fn write(&self, b: BinaryObjectBuilder) -> BinaryObjectBuilder;

    /// Build a complete [`BinaryObject`] from `self`.
    fn to_binary(&self) -> BinaryObject {
        self.write(BinaryObjectBuilder::new(Self::type_name()))
            .build()
    }

    /// The [`BinaryType`] metadata describing `Self`'s schema, suitable for
    /// registration via `OP_BINARY_TYPE_PUT`.
    fn binary_type() -> BinaryType;
}

/// Serialise a single field's value into a [`BinaryObjectBuilder`].
pub trait FieldWrite {
    /// Write `self` as field `name`, returning the builder for chaining.
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder;

    /// The Ignite wire type code for this field's value.
    fn field_type_code() -> i32;
}

/// Deserialise a whole Ignite binary (complex) object into `Self`.
pub trait ReadBinary: Sized {
    fn read(r: &BinaryObjectReader) -> Result<Self>;
}

/// Deserialise a single named field from a [`BinaryObjectReader`].
pub trait FieldRead: Sized {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self>;
}

// ─── Nested-object schema resolution ────────────────────────────────────────
//
// A nested `Object` field (a `#[derive(IgniteBinary)]`'d struct used as a
// field of another) may itself be compact-footer-encoded on the wire — real
// Ignite peers (e.g. the Java thin client) use compact footers throughout,
// not just at the top level. Decoding a compact footer needs that nested
// type's own schema (`field_ids` in declaration order), which can only be
// discovered from the object's own bytes (its type id lives inside them) —
// there is no way to know it ahead of time the way `IgniteCache::get_binary`
// knows the *top-level* type before it has any bytes at all.
//
// `FieldRead::read_field` (generated by `#[derive(IgniteBinary)]` for nested
// struct fields) is a plain synchronous function with no access to a
// `ChannelRegistry` to fetch that schema over the network, and changing its
// signature to thread one through would break every derived type's trait
// impl. Instead, `get_binary` walks the whole object graph up front
// (`prefetch_nested_schemas`), fetches every nested type's schema it finds,
// and installs the result here via [`with_nested_schemas`] before running
// the synchronous decode. Nested `FieldRead` impls then resolve compact
// footers via [`nested_object_reader`] instead of calling
// `BinaryObjectReader::new` directly.

thread_local! {
    static NESTED_SCHEMAS: std::cell::RefCell<std::collections::HashMap<(i32, i32), Vec<i32>>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

/// Makes `schemas` (keyed by `(type_id, schema_id)`, mapping to that
/// schema's field ids in declaration order) available to
/// [`nested_object_reader`] for the duration of `f`, then clears it.
///
/// `f` must be purely synchronous (no `.await`): this is thread-local
/// state, so it only reliably survives a stretch of code that never yields
/// back to the async runtime (which could resume the task on a different
/// worker thread). `IgniteCache::get_binary` upholds this by populating the
/// schemas from a prior `.await`-ing walk of the object graph, then calling
/// this with just the synchronous `V::read(&reader)` decode as `f`.
pub(crate) fn with_nested_schemas<F, R>(
    schemas: std::collections::HashMap<(i32, i32), Vec<i32>>,
    f: F,
) -> R
where
    F: FnOnce() -> R,
{
    NESTED_SCHEMAS.with(|cell| *cell.borrow_mut() = schemas);
    let result = f();
    NESTED_SCHEMAS.with(|cell| cell.borrow_mut().clear());
    result
}

/// Builds a [`BinaryObjectReader`] for a nested-object field's raw bytes
/// (an [`IgniteValue::Object`] payload). Used by `#[derive(IgniteBinary)]`'s
/// generated nested-field `FieldRead` impls instead of calling
/// `BinaryObjectReader::new` directly, so a compact-footer nested object can
/// resolve its schema from the map installed by `with_nested_schemas`
/// rather than failing outright.
///
/// Tries a non-compact parse first (the common case for hand-built test
/// frames, and cheap to rule out); only consults the nested-schema map if
/// the frame turns out to need one.
pub fn nested_object_reader(bytes: bytes::Bytes) -> Result<BinaryObjectReader> {
    match BinaryObjectReader::new(bytes.clone()) {
        Ok(r) => Ok(r),
        Err(ProtocolError::CompactFooterNeedsSchema) => {
            let mut hb = bytes.clone();
            let header = crate::protocol::binary::header::BinaryHeader::read(&mut hb)?;
            let key = (header.type_id, header.schema_id);
            let schema = NESTED_SCHEMAS
                .with(|cell| cell.borrow().get(&key).cloned())
                .ok_or(ProtocolError::CompactFooterNeedsSchema)?;
            Ok(BinaryObjectReader::with_schema(bytes, &schema)?)
        }
        Err(e) => Err(e.into()),
    }
}

// ─── Leaf FieldWrite/FieldRead impls ────────────────────────────────────────
//
// `FieldRead::read_field` reads via `r.field(name)?`, matching the expected
// `IgniteValue` variant. A present-but-wrong-variant field is
// `ProtocolError::TypeMismatch`; a missing field is `ProtocolError::UnexpectedNull`
// (callers who want a missing field to mean "no value" should read `Option<T>`
// instead — see below).

/// Implements `FieldWrite`/`FieldRead` for a `Copy` leaf type that maps
/// directly onto a single-field `IgniteValue` variant.
macro_rules! leaf_field {
    ($rust_ty:ty, $variant:ident, $code:path, $expected:literal) => {
        impl FieldWrite for $rust_ty {
            fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
                b.set_value(name, &IgniteValue::$variant(*self))
            }

            fn field_type_code() -> i32 {
                $code as i32
            }
        }

        impl FieldRead for $rust_ty {
            fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
                match r.field(name)? {
                    Some(IgniteValue::$variant(v)) => Ok(v),
                    Some(other) => Err(ProtocolError::TypeMismatch {
                        expected: $expected,
                        got: value_type_name(&other),
                    }
                    .into()),
                    None => Err(ProtocolError::UnexpectedNull.into()),
                }
            }
        }
    };
}

leaf_field!(bool, Bool, type_code::BOOL, "Bool");
leaf_field!(i8, Byte, type_code::BYTE, "Byte");
leaf_field!(i16, Short, type_code::SHORT, "Short");
leaf_field!(i32, Int, type_code::INT, "Int");
leaf_field!(i64, Long, type_code::LONG, "Long");
leaf_field!(f32, Float, type_code::FLOAT, "Float");
leaf_field!(f64, Double, type_code::DOUBLE, "Double");

/// Implements `FieldWrite`/`FieldRead` for a single-field newtype wrapping an
/// `IgniteValue` variant's inner type.
macro_rules! newtype_field {
    ($newtype:ty, $variant:ident, $code:path, $expected:literal) => {
        impl FieldWrite for $newtype {
            fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
                b.set_value(name, &IgniteValue::$variant(self.0))
            }

            fn field_type_code() -> i32 {
                $code as i32
            }
        }

        impl FieldRead for $newtype {
            fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
                match r.field(name)? {
                    Some(IgniteValue::$variant(v)) => Ok(Self(v)),
                    Some(other) => Err(ProtocolError::TypeMismatch {
                        expected: $expected,
                        got: value_type_name(&other),
                    }
                    .into()),
                    None => Err(ProtocolError::UnexpectedNull.into()),
                }
            }
        }
    };
}

newtype_field!(IgniteChar, Char, type_code::CHAR, "Char");
newtype_field!(IgniteDate, Date, type_code::DATE, "Date");
newtype_field!(IgniteTime, Time, type_code::TIME, "Time");

// IgniteTimestamp wraps two fields, so it needs a hand-written impl rather
// than the single-field newtype macro.
impl FieldWrite for IgniteTimestamp {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        b.set_value(name, &IgniteValue::Timestamp(self.0, self.1))
    }

    fn field_type_code() -> i32 {
        type_code::TIMESTAMP as i32
    }
}

impl FieldRead for IgniteTimestamp {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::Timestamp(ms, ns)) => Ok(Self(ms, ns)),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "Timestamp",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

impl FieldWrite for String {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        b.set_value(name, &IgniteValue::String(self.clone()))
    }

    fn field_type_code() -> i32 {
        type_code::STRING as i32
    }
}

impl FieldRead for String {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::String(v)) => Ok(v),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "String",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

impl FieldWrite for Uuid {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        b.set_value(name, &IgniteValue::Uuid(*self))
    }

    fn field_type_code() -> i32 {
        type_code::UUID as i32
    }
}

impl FieldRead for Uuid {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::Uuid(v)) => Ok(v),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "Uuid",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

impl FieldWrite for BigDecimal {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        b.set_value(name, &IgniteValue::Decimal(self.clone()))
    }

    fn field_type_code() -> i32 {
        type_code::DECIMAL as i32
    }
}

impl FieldRead for BigDecimal {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::Decimal(v)) => Ok(v),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "Decimal",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

/// `None` writes as `IgniteValue::Null` (the field is present but null,
/// rather than omitted) so the schema always includes it. On read, both a
/// null value and a missing field map to `None`.
impl<T: FieldWrite> FieldWrite for Option<T> {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        match self {
            Some(v) => v.write_field(b, name),
            None => b.set_value(name, &IgniteValue::Null),
        }
    }

    fn field_type_code() -> i32 {
        T::field_type_code()
    }
}

impl<T: FieldRead> FieldRead for Option<T> {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            None | Some(IgniteValue::Null) => Ok(None),
            Some(_) => Ok(Some(T::read_field(r, name)?)),
        }
    }
}

// ─── Collection / array / map FieldWrite / FieldRead impls ─────────────────
//
// Java's `AllTypes` has both `int[]` and `List<Integer>`, which are BOTH
// `Vec<i32>` in Rust — an ambiguity resolved by giving each Ignite wire shape
// a distinct Rust type: `Vec<i32>` maps to the Ignite primitive INT_ARRAY,
// while [`IgniteList<i32>`] maps to a Java `Collection` (`List`/`Set`).
//
// As with the leaf impls above, a present-but-wrong-variant field is a
// `TypeMismatch`, and a missing field is `UnexpectedNull` (these are all
// required-field reads; wrap in `Option<T>` for an optional field).

impl FieldWrite for Vec<i32> {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        b.set_value(name, &IgniteValue::IntArray(self.clone()))
    }

    fn field_type_code() -> i32 {
        type_code::INT_ARRAY as i32
    }
}

impl FieldRead for Vec<i32> {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::IntArray(v)) => Ok(v),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "IntArray",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

/// Maps onto Ignite's STRING_ARRAY, which is nullable-element
/// (`Vec<Option<String>>` at the [`IgniteValue`] level). Writing produces an
/// array with every element present (`Some`); reading a null element is a
/// `TypeMismatch` (expected `"String"`, got `"Null"`) since `Vec<String>` has
/// no representation for an absent element — use `Vec<Option<String>>`
/// directly (not yet implemented) if nulls must round-trip.
impl FieldWrite for Vec<String> {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        let arr: Vec<Option<String>> = self.iter().cloned().map(Some).collect();
        b.set_value(name, &IgniteValue::StringArray(arr))
    }

    fn field_type_code() -> i32 {
        type_code::STRING_ARRAY as i32
    }
}

impl FieldRead for Vec<String> {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::StringArray(v)) => v
                .into_iter()
                .map(|e| {
                    e.ok_or_else(|| {
                        ProtocolError::TypeMismatch {
                            expected: "String",
                            got: "Null",
                        }
                        .into()
                    })
                })
                .collect(),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "StringArray",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

impl FieldWrite for std::collections::HashMap<String, i32> {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        let pairs: Vec<(IgniteValue, IgniteValue)> = self
            .iter()
            .map(|(k, v)| (IgniteValue::String(k.clone()), IgniteValue::Int(*v)))
            .collect();
        // Map type 1 = HASH_MAP; iteration order is unspecified for a Rust
        // `HashMap` anyway, so this only affects the raw type byte, not
        // round-trip correctness.
        b.set_value(name, &IgniteValue::Map(1, pairs))
    }

    fn field_type_code() -> i32 {
        type_code::MAP as i32
    }
}

impl FieldRead for std::collections::HashMap<String, i32> {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::Map(_, pairs)) => pairs
                .into_iter()
                .map(|(k, v)| {
                    let key = match k {
                        IgniteValue::String(s) => s,
                        other => {
                            return Err(ProtocolError::TypeMismatch {
                                expected: "String",
                                got: value_type_name(&other),
                            }
                            .into());
                        }
                    };
                    let val = match v {
                        IgniteValue::Int(i) => i,
                        other => {
                            return Err(ProtocolError::TypeMismatch {
                                expected: "Int",
                                got: value_type_name(&other),
                            }
                            .into());
                        }
                    };
                    Ok((key, val))
                })
                .collect(),
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "Map",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

/// A Java `Collection` (`List`/`Set`), distinct from the Ignite primitive
/// array types. Java's `AllTypes` has both `int[]` (→ `Vec<i32>` /
/// `IntArray`) and `List<Integer>` (→ `IgniteList<i32>` / `Collection`) —
/// both would be `Vec<i32>` in Rust without this newtype, making the mapping
/// ambiguous.
///
/// `FieldWrite`/`FieldRead` are implemented concretely for `IgniteList<i32>`
/// rather than generically over `T: FieldWrite`/`FieldRead`, to avoid the
/// complexity of a generic-over-element-trait impl for v1; extend with more
/// concrete element types (or generalise) as the gate requires them.
#[derive(Debug, Clone, PartialEq)]
pub struct IgniteList<T>(pub Vec<T>);

impl FieldWrite for IgniteList<i32> {
    fn write_field(&self, b: BinaryObjectBuilder, name: &str) -> BinaryObjectBuilder {
        let vals: Vec<IgniteValue> = self.0.iter().map(|x| IgniteValue::Int(*x)).collect();
        // Collection type 2 = ARR_LIST.
        b.set_value(name, &IgniteValue::Collection(2, vals))
    }

    fn field_type_code() -> i32 {
        type_code::COLLECTION as i32
    }
}

impl FieldRead for IgniteList<i32> {
    fn read_field(r: &BinaryObjectReader, name: &str) -> Result<Self> {
        match r.field(name)? {
            Some(IgniteValue::Collection(_, vals)) => {
                let items: Vec<i32> = vals
                    .into_iter()
                    .map(|v| match v {
                        IgniteValue::Int(i) => Ok(i),
                        other => Err(ProtocolError::TypeMismatch {
                            expected: "Int",
                            got: value_type_name(&other),
                        }
                        .into()),
                    })
                    .collect::<Result<Vec<i32>>>()?;
                Ok(IgniteList(items))
            }
            Some(other) => Err(ProtocolError::TypeMismatch {
                expected: "Collection",
                got: value_type_name(&other),
            }
            .into()),
            None => Err(ProtocolError::UnexpectedNull.into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::binary::{reader::BinaryObjectReader, writer::BinaryObjectBuilder};

    #[test]
    fn field_write_read_i32_and_string() {
        let b = BinaryObjectBuilder::new("t.T");
        let b = 42i32.write_field(b, "n");
        let b = "hi".to_string().write_field(b, "s");
        let obj = b.build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        assert_eq!(i32::read_field(&r, "n").unwrap(), 42);
        assert_eq!(String::read_field(&r, "s").unwrap(), "hi");
    }

    #[test]
    fn field_write_read_option_none() {
        let b = Option::<i32>::None.write_field(BinaryObjectBuilder::new("t.T"), "n");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(Option::<i32>::read_field(&r, "n").unwrap(), None);
    }

    #[test]
    fn field_write_read_option_some() {
        let b = Some(7i32).write_field(BinaryObjectBuilder::new("t.T"), "n");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(Option::<i32>::read_field(&r, "n").unwrap(), Some(7));
    }

    #[test]
    fn field_read_option_missing_field_is_none() {
        // Field "n" is never written; reading it as Option must yield None
        // (not an error) — distinct from the explicit-Null case above, which
        // exercises `r.field(name)` returning `Some(IgniteValue::Null)`
        // rather than `None`.
        let obj = BinaryObjectBuilder::new("t.T").set_i32("other", 1).build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        assert_eq!(Option::<i32>::read_field(&r, "n").unwrap(), None);
    }

    #[test]
    fn field_write_read_all_numeric_leaves() {
        let b = BinaryObjectBuilder::new("t.T");
        let b = true.write_field(b, "bo");
        let b = 1i8.write_field(b, "i8");
        let b = 2i16.write_field(b, "i16");
        let b = 3i32.write_field(b, "i32");
        let b = 4i64.write_field(b, "i64");
        let b = 5.5f32.write_field(b, "f32");
        let b = 6.5f64.write_field(b, "f64");
        let obj = b.build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        assert_eq!(bool::read_field(&r, "bo").unwrap(), true);
        assert_eq!(i8::read_field(&r, "i8").unwrap(), 1);
        assert_eq!(i16::read_field(&r, "i16").unwrap(), 2);
        assert_eq!(i32::read_field(&r, "i32").unwrap(), 3);
        assert_eq!(i64::read_field(&r, "i64").unwrap(), 4);
        assert_eq!(f32::read_field(&r, "f32").unwrap(), 5.5);
        assert_eq!(f64::read_field(&r, "f64").unwrap(), 6.5);
    }

    #[test]
    fn field_write_read_newtypes() {
        let b = BinaryObjectBuilder::new("t.T");
        let b = IgniteChar(65).write_field(b, "c");
        let b = IgniteDate(1_705_276_800_000).write_field(b, "d");
        let b = IgniteTime(1_234_567_890).write_field(b, "t");
        let b = IgniteTimestamp(1_700_000_000_000, 123).write_field(b, "ts");
        let obj = b.build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        assert_eq!(IgniteChar::read_field(&r, "c").unwrap(), IgniteChar(65));
        assert_eq!(
            IgniteDate::read_field(&r, "d").unwrap(),
            IgniteDate(1_705_276_800_000)
        );
        assert_eq!(
            IgniteTime::read_field(&r, "t").unwrap(),
            IgniteTime(1_234_567_890)
        );
        assert_eq!(
            IgniteTimestamp::read_field(&r, "ts").unwrap(),
            IgniteTimestamp(1_700_000_000_000, 123)
        );
    }

    #[test]
    fn field_write_read_uuid_and_decimal() {
        use std::str::FromStr;

        let u = Uuid::new_v4();
        let d = BigDecimal::from_str("12.34").unwrap();
        let b = BinaryObjectBuilder::new("t.T");
        let b = u.write_field(b, "u");
        let b = d.write_field(b, "d");
        let obj = b.build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        assert_eq!(Uuid::read_field(&r, "u").unwrap(), u);
        assert_eq!(
            BigDecimal::read_field(&r, "d").unwrap().normalized(),
            d.normalized()
        );
    }

    #[test]
    fn field_read_missing_required_field_errors() {
        let obj = BinaryObjectBuilder::new("t.T").build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        let err = i32::read_field(&r, "missing").unwrap_err();
        assert!(matches!(
            err,
            crate::IgniteError::Protocol(ProtocolError::UnexpectedNull)
        ));
    }

    #[test]
    fn field_read_wrong_variant_is_type_mismatch() {
        let obj = BinaryObjectBuilder::new("t.T").set_i32("n", 1).build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        let err = String::read_field(&r, "n").unwrap_err();
        assert!(matches!(
            err,
            crate::IgniteError::Protocol(ProtocolError::TypeMismatch {
                expected: "String",
                got: "Int"
            })
        ));
    }

    // ─── Task 18a: collection/array/map field impls ────────────────────────

    #[test]
    fn field_write_read_vec_i32() {
        let b = vec![1i32, -2, 3].write_field(BinaryObjectBuilder::new("t.T"), "a");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(<Vec<i32>>::read_field(&r, "a").unwrap(), vec![1, -2, 3]);
        assert_eq!(<Vec<i32>>::field_type_code(), type_code::INT_ARRAY as i32);
    }

    #[test]
    fn field_write_read_vec_i32_empty() {
        let b = Vec::<i32>::new().write_field(BinaryObjectBuilder::new("t.T"), "a");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(<Vec<i32>>::read_field(&r, "a").unwrap(), Vec::<i32>::new());
    }

    #[test]
    fn field_write_read_vec_string() {
        let v = vec!["foo".to_string(), "bar".to_string()];
        let b = v.write_field(BinaryObjectBuilder::new("t.T"), "s");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(<Vec<String>>::read_field(&r, "s").unwrap(), v);
        assert_eq!(
            <Vec<String>>::field_type_code(),
            type_code::STRING_ARRAY as i32
        );
    }

    #[test]
    fn field_read_vec_string_null_element_errors() {
        // A StringArray containing a null element cannot round-trip into
        // Vec<String> (which has no room for absent elements) — this must
        // surface as a TypeMismatch rather than silently dropping/panicking.
        let obj = BinaryObjectBuilder::new("t.T")
            .set_string_array("s", &[Some("a".to_string()), None])
            .build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        let err = <Vec<String>>::read_field(&r, "s").unwrap_err();
        assert!(matches!(
            err,
            crate::IgniteError::Protocol(ProtocolError::TypeMismatch {
                expected: "String",
                got: "Null"
            })
        ));
    }

    #[test]
    fn field_write_read_hashmap_string_i32() {
        use std::collections::HashMap;

        let mut m = HashMap::new();
        m.insert("one".to_string(), 1i32);
        m.insert("two".to_string(), 2i32);
        let b = m.write_field(BinaryObjectBuilder::new("t.T"), "m");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(<HashMap<String, i32>>::read_field(&r, "m").unwrap(), m);
        assert_eq!(
            <HashMap<String, i32>>::field_type_code(),
            type_code::MAP as i32
        );
    }

    #[test]
    fn field_write_read_ignite_list_i32() {
        let list = IgniteList(vec![10i32, 20, 30]);
        let b = list.write_field(BinaryObjectBuilder::new("t.T"), "l");
        let r = BinaryObjectReader::new(b.build().bytes).unwrap();
        assert_eq!(IgniteList::<i32>::read_field(&r, "l").unwrap(), list);
        assert_eq!(
            IgniteList::<i32>::field_type_code(),
            type_code::COLLECTION as i32
        );
    }

    #[test]
    fn field_read_vec_i32_missing_field_errors() {
        let obj = BinaryObjectBuilder::new("t.T").build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        let err = <Vec<i32>>::read_field(&r, "missing").unwrap_err();
        assert!(matches!(
            err,
            crate::IgniteError::Protocol(ProtocolError::UnexpectedNull)
        ));
    }

    #[test]
    fn field_read_hashmap_wrong_variant_is_type_mismatch() {
        let obj = BinaryObjectBuilder::new("t.T").set_i32("m", 1).build();
        let r = BinaryObjectReader::new(obj.bytes).unwrap();
        use std::collections::HashMap;
        let err = <HashMap<String, i32>>::read_field(&r, "m").unwrap_err();
        assert!(matches!(
            err,
            crate::IgniteError::Protocol(ProtocolError::TypeMismatch {
                expected: "Map",
                got: "Int"
            })
        ));
    }
}