clickhouse-native-client 0.1.0

Async ClickHouse client using the native TCP protocol with LZ4/ZSTD compression and TLS support
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
//! Numeric column implementations
//!
//! **ClickHouse Documentation:**
//! - [Integer Types](https://clickhouse.com/docs/en/sql-reference/data-types/int-uint)
//!   - Int8/16/32/64/128, UInt8/16/32/64/128
//! - [Floating-Point Types](https://clickhouse.com/docs/en/sql-reference/data-types/float)
//!   - Float32, Float64
//! - [Decimal Types](https://clickhouse.com/docs/en/sql-reference/data-types/decimal)
//!   - Fixed-point numbers
//!
//! ## Integer Types
//!
//! All integer types are stored in **little-endian** format:
//!
//! | Type | Rust Type | Storage | Min | Max |
//! |------|-----------|---------|-----|-----|
//! | `Int8` | `i8` | 1 byte | -128 | 127 |
//! | `Int16` | `i16` | 2 bytes | -32,768 | 32,767 |
//! | `Int32` | `i32` | 4 bytes | -2³¹ | 2³¹-1 |
//! | `Int64` | `i64` | 8 bytes | -2⁶³ | 2⁶³-1 |
//! | `Int128` | `i128` | 16 bytes | -2¹²⁷ | 2¹²⁷-1 |
//! | `UInt8` | `u8` | 1 byte | 0 | 255 |
//! | `UInt16` | `u16` | 2 bytes | 0 | 65,535 |
//! | `UInt32` | `u32` | 4 bytes | 0 | 2³²-1 |
//! | `UInt64` | `u64` | 8 bytes | 0 | 2⁶⁴-1 |
//! | `UInt128` | `u128` | 16 bytes | 0 | 2¹²⁸-1 |
//!
//! ## Floating-Point Types
//!
//! IEEE 754 floating-point numbers, stored in little-endian:
//! - `Float32` - Single precision (32-bit)
//! - `Float64` - Double precision (64-bit)
//!
//! ## Bool Type
//!
//! `Bool` is an alias for `UInt8` where 0 = false, 1 = true.

use super::{
    Column,
    ColumnRef,
    ColumnTyped,
};
use crate::{
    types::{
        ToType,
        Type,
    },
    Error,
    Result,
};
use bytes::{
    Buf,
    BufMut,
    BytesMut,
};
use std::sync::Arc;

/// Trait for types that can be read/written as fixed-size values (synchronous
/// version for columns)
///
/// All numeric types are stored in **little-endian** format in ClickHouse wire
/// protocol.
pub trait FixedSize: Sized + Clone + Send + Sync + 'static {
    /// Read a single fixed-size value from the buffer in little-endian byte
    /// order.
    fn read_from(buffer: &mut &[u8]) -> Result<Self>;
    /// Write a single fixed-size value to the buffer in little-endian byte
    /// order.
    fn write_to(&self, buffer: &mut BytesMut);
}

// Implement FixedSize for primitive types
macro_rules! impl_fixed_size {
    ($type:ty, $get:ident, $put:ident) => {
        impl FixedSize for $type {
            fn read_from(buffer: &mut &[u8]) -> Result<Self> {
                if buffer.len() < std::mem::size_of::<$type>() {
                    return Err(Error::Protocol(
                        "Buffer underflow".to_string(),
                    ));
                }
                Ok(buffer.$get())
            }

            fn write_to(&self, buffer: &mut BytesMut) {
                buffer.$put(*self);
            }
        }
    };
}

impl_fixed_size!(u8, get_u8, put_u8);
impl_fixed_size!(u16, get_u16_le, put_u16_le);
impl_fixed_size!(u32, get_u32_le, put_u32_le);
impl_fixed_size!(u64, get_u64_le, put_u64_le);
impl_fixed_size!(i8, get_i8, put_i8);
impl_fixed_size!(i16, get_i16_le, put_i16_le);
impl_fixed_size!(i32, get_i32_le, put_i32_le);
impl_fixed_size!(i64, get_i64_le, put_i64_le);
impl_fixed_size!(f32, get_f32_le, put_f32_le);
impl_fixed_size!(f64, get_f64_le, put_f64_le);

impl FixedSize for i128 {
    fn read_from(buffer: &mut &[u8]) -> Result<Self> {
        if buffer.len() < 16 {
            return Err(Error::Protocol("Buffer underflow".to_string()));
        }
        Ok(buffer.get_i128_le())
    }

    fn write_to(&self, buffer: &mut BytesMut) {
        buffer.put_i128_le(*self);
    }
}

impl FixedSize for u128 {
    fn read_from(buffer: &mut &[u8]) -> Result<Self> {
        if buffer.len() < 16 {
            return Err(Error::Protocol("Buffer underflow".to_string()));
        }
        Ok(buffer.get_u128_le())
    }

    fn write_to(&self, buffer: &mut BytesMut) {
        buffer.put_u128_le(*self);
    }
}

/// Generic column for numeric types
pub struct ColumnVector<T: FixedSize> {
    type_: Type,
    data: Vec<T>,
}

impl<T: FixedSize + Clone + Send + Sync + 'static> ColumnVector<T> {
    /// Create a column from an explicit type and a pre-built vector of values.
    pub fn from_vec(type_: Type, data: Vec<T>) -> Self {
        Self { type_, data }
    }

    /// Create a column with initial data (builder pattern)
    pub fn with_data(mut self, data: Vec<T>) -> Self {
        self.data = data;
        self
    }

    /// Reserve capacity for additional elements (for
    /// benchmarking/optimization)
    pub fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
    }

    /// Clear the column while preserving capacity (for
    /// benchmarking/optimization)
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Return a reference to the value at the given index, or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<&T> {
        self.data.get(index)
    }

    /// Get value at index (panics if out of bounds - for tests)
    pub fn at(&self, index: usize) -> T {
        self.data[index].clone()
    }

    /// Get the number of elements (alias for size())
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Check if the column is empty
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Append a single value to the end of the column.
    pub fn append(&mut self, value: T) {
        self.data.push(value);
    }

    /// Return an iterator over references to the column values.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.data.iter()
    }

    /// Return a slice reference to the underlying data.
    pub fn data(&self) -> &[T] {
        &self.data
    }

    /// Return a mutable reference to the underlying data vector.
    pub fn data_mut(&mut self) -> &mut Vec<T> {
        &mut self.data
    }
}

/// Type-inferred constructors for ColumnVector
/// Implements the type map pattern from C++ `Type::CreateSimple<T>()`
impl<T: FixedSize + ToType + Clone + Send + Sync + 'static> ColumnVector<T> {
    /// Create a new column with type inferred from T
    /// Equivalent to C++ pattern where type is determined from template
    /// parameter
    ///
    /// # Examples
    ///
    /// ```
    /// use clickhouse_native_client::column::{Column, ColumnVector};
    /// use clickhouse_native_client::types::Type;
    ///
    /// let col = ColumnVector::<i32>::new();
    /// assert_eq!(col.column_type(), &Type::int32());
    /// ```
    pub fn new() -> Self {
        Self { type_: T::to_type(), data: Vec::new() }
    }

    /// Create a new column with type inferred from T and specified capacity
    ///
    /// # Examples
    ///
    /// ```
    /// use clickhouse_native_client::column::ColumnVector;
    ///
    /// let col = ColumnVector::<u64>::with_capacity(100);
    /// assert_eq!(col.len(), 0);
    /// ```
    pub fn with_capacity(capacity: usize) -> Self {
        Self { type_: T::to_type(), data: Vec::with_capacity(capacity) }
    }
}

impl<T: FixedSize + ToType + Clone + Send + Sync + 'static> Default
    for ColumnVector<T>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T: FixedSize + ToType> Column for ColumnVector<T> {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.len()
    }

    fn clear(&mut self) {
        self.data.clear()
    }

    fn reserve(&mut self, new_cap: usize) {
        self.data.reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other = other
            .as_any()
            .downcast_ref::<ColumnVector<T>>()
            .ok_or_else(|| Error::TypeMismatch {
                expected: self.type_.name(),
                actual: other.column_type().name(),
            })?;

        self.data.extend_from_slice(&other.data);
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        // Optimize: Use bulk read instead of loop for massive performance gain
        // C++ does: WireFormat::ReadBytes(*input, data_.data(), rows *
        // sizeof(T))
        let bytes_needed = rows * std::mem::size_of::<T>();

        if buffer.len() < bytes_needed {
            return Err(Error::Protocol(format!(
                "Buffer underflow: need {} bytes, have {}",
                bytes_needed,
                buffer.len()
            )));
        }

        // Pre-allocate and read directly into Vec's memory
        self.data.clear();
        self.data.reserve(rows);

        unsafe {
            // Read bytes directly into Vec's uninitialized memory
            let dest_ptr = self.data.as_mut_ptr() as *mut u8;
            std::ptr::copy_nonoverlapping(
                buffer.as_ptr(),
                dest_ptr,
                bytes_needed,
            );
            self.data.set_len(rows);
        }

        // Advance buffer
        *buffer = &buffer[bytes_needed..];
        Ok(())
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        // Optimize: Use bulk write instead of loop for massive performance
        // gain C++ does: WireFormat::WriteBytes(*output, data_.data(),
        // data_.size() * sizeof(T)) This achieves the same with
        // extend_from_slice on the raw bytes
        if !self.data.is_empty() {
            let byte_slice = unsafe {
                std::slice::from_raw_parts(
                    self.data.as_ptr() as *const u8,
                    self.data.len() * std::mem::size_of::<T>(),
                )
            };
            buffer.extend_from_slice(byte_slice);
        }
        Ok(())
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnVector::<T>::new())
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        if begin + len > self.data.len() {
            return Err(Error::InvalidArgument(format!(
                "Slice range out of bounds: begin={}, len={}, size={}",
                begin,
                len,
                self.data.len()
            )));
        }

        let sliced_data = self.data[begin..begin + len].to_vec();
        Ok(Arc::new(ColumnVector::<T>::from_vec(
            self.type_.clone(),
            sliced_data,
        )))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

impl<T: FixedSize + ToType + Clone + Send + Sync + 'static> ColumnTyped<T>
    for ColumnVector<T>
{
    fn get(&self, index: usize) -> Option<T> {
        self.data.get(index).cloned()
    }

    fn append(&mut self, value: T) {
        self.data.push(value);
    }
}

/// Column of `UInt8` values (1-byte unsigned integers).
pub type ColumnUInt8 = ColumnVector<u8>;
/// Column of `UInt16` values (2-byte unsigned integers, little-endian).
pub type ColumnUInt16 = ColumnVector<u16>;
/// Column of `UInt32` values (4-byte unsigned integers, little-endian).
pub type ColumnUInt32 = ColumnVector<u32>;
/// Column of `UInt64` values (8-byte unsigned integers, little-endian).
pub type ColumnUInt64 = ColumnVector<u64>;
/// Column of `UInt128` values (16-byte unsigned integers, little-endian).
pub type ColumnUInt128 = ColumnVector<u128>;

/// Column of `Int8` values (1-byte signed integers).
pub type ColumnInt8 = ColumnVector<i8>;
/// Column of `Int16` values (2-byte signed integers, little-endian).
pub type ColumnInt16 = ColumnVector<i16>;
/// Column of `Int32` values (4-byte signed integers, little-endian).
pub type ColumnInt32 = ColumnVector<i32>;
/// Column of `Int64` values (8-byte signed integers, little-endian).
pub type ColumnInt64 = ColumnVector<i64>;
/// Column of `Int128` values (16-byte signed integers, little-endian).
pub type ColumnInt128 = ColumnVector<i128>;

/// Column of `Float32` values (IEEE 754 single-precision, little-endian).
pub type ColumnFloat32 = ColumnVector<f32>;
/// Column of `Float64` values (IEEE 754 double-precision, little-endian).
pub type ColumnFloat64 = ColumnVector<f64>;

/// Column of `Date` values stored as `u16` (days since 1970-01-01).
pub type ColumnDate = ColumnVector<u16>;

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn test_column_creation() {
        // Test type-inferred constructor
        let col = ColumnUInt32::new();
        assert_eq!(col.size(), 0);
        assert_eq!(col.column_type().name(), "UInt32");

        // Test with_capacity constructor
        let col2 = ColumnUInt32::with_capacity(100);
        assert_eq!(col2.size(), 0);
        assert_eq!(col2.column_type().name(), "UInt32");
    }

    #[test]
    fn test_column_append() {
        let mut col = ColumnUInt32::new();
        col.append(42);
        col.append(100);

        assert_eq!(col.size(), 2);
        assert_eq!(col.get(0), Some(&42));
        assert_eq!(col.get(1), Some(&100));
    }

    #[test]
    fn test_column_clear() {
        let mut col = ColumnInt64::new();
        col.append(-123);
        col.append(456);
        assert_eq!(col.size(), 2);

        col.clear();
        assert_eq!(col.size(), 0);
    }

    #[test]
    fn test_column_slice() {
        let mut col = ColumnUInt64::new();
        for i in 0..10 {
            col.append(i);
        }

        let sliced = col.slice(2, 5).unwrap();
        assert_eq!(sliced.size(), 5);

        let sliced_concrete =
            sliced.as_any().downcast_ref::<ColumnUInt64>().unwrap();
        assert_eq!(sliced_concrete.get(0), Some(&2));
        assert_eq!(sliced_concrete.get(4), Some(&6));
    }

    #[test]
    fn test_column_save_load() {
        let mut col = ColumnInt32::new();
        col.append(1);
        col.append(-2);
        col.append(3);

        // Save to buffer
        let mut buf = BytesMut::new();
        col.save_to_buffer(&mut buf).unwrap();

        // Load from buffer
        let mut col2 = ColumnInt32::new();
        let mut reader = &buf[..];
        col2.load_from_buffer(&mut reader, 3).unwrap();

        assert_eq!(col2.size(), 3);
        assert_eq!(col2.get(0), Some(&1));
        assert_eq!(col2.get(1), Some(&-2));
        assert_eq!(col2.get(2), Some(&3));
    }

    #[test]
    fn test_column_append_column() {
        let mut col1 = ColumnFloat64::new();
        col1.append(1.5);
        col1.append(2.5);

        let mut col2 = ColumnFloat64::new();
        col2.append(3.5);
        col2.append(4.5);

        col1.append_column(Arc::new(col2)).unwrap();

        assert_eq!(col1.size(), 4);
        assert_eq!(col1.get(0), Some(&1.5));
        assert_eq!(col1.get(3), Some(&4.5));
    }

    // Bulk copy tests - verify set_len safety
    #[test]
    fn test_bulk_load_large_dataset() {
        // Test with 10,000 elements to ensure bulk copy works correctly
        let mut col = ColumnUInt64::new();
        let data: Vec<u64> = (0..10_000).collect();

        // Save to buffer
        let mut buf = BytesMut::new();
        for &val in &data {
            buf.put_u64_le(val);
        }

        // Load from buffer using bulk copy (internally uses set_len)
        let mut reader = &buf[..];
        col.load_from_buffer(&mut reader, 10_000).unwrap();

        assert_eq!(col.size(), 10_000);
        assert_eq!(col.get(0), Some(&0));
        assert_eq!(col.get(5_000), Some(&5_000));
        assert_eq!(col.get(9_999), Some(&9_999));
    }

    #[test]
    fn test_bulk_load_multiple_sequential() {
        // Test multiple sequential bulk loads
        let mut col = ColumnInt32::new();

        // First bulk load
        let mut buf1 = BytesMut::new();
        for i in 0..1_000 {
            buf1.put_i32_le(i);
        }
        let mut reader1 = &buf1[..];
        col.load_from_buffer(&mut reader1, 1_000).unwrap();

        assert_eq!(col.size(), 1_000);
        assert_eq!(col.get(0), Some(&0));
        assert_eq!(col.get(999), Some(&999));

        // Second bulk load (should append)
        let mut buf2 = BytesMut::new();
        for i in 1_000..2_000 {
            buf2.put_i32_le(i);
        }
        let mut reader2 = &buf2[..];
        col.load_from_buffer(&mut reader2, 1_000).unwrap();

        assert_eq!(col.size(), 1_000); // Note: load_from_buffer clears first
        assert_eq!(col.get(0), Some(&1_000));
        assert_eq!(col.get(999), Some(&1_999));
    }

    #[test]
    fn test_bulk_load_empty() {
        // Test edge case: empty load
        let mut col = ColumnUInt32::new();
        let buf = BytesMut::new();
        let mut reader = &buf[..];
        col.load_from_buffer(&mut reader, 0).unwrap();

        assert_eq!(col.size(), 0);
    }

    #[test]
    fn test_bulk_load_single_element() {
        // Test edge case: single element
        let mut col = ColumnInt64::new();
        let mut buf = BytesMut::new();
        buf.put_i64_le(42);

        let mut reader = &buf[..];
        col.load_from_buffer(&mut reader, 1).unwrap();

        assert_eq!(col.size(), 1);
        assert_eq!(col.get(0), Some(&42));
    }

    #[test]
    fn test_bulk_load_roundtrip_large() {
        // Test save/load round-trip with large data
        let mut col1 = ColumnFloat32::new();
        for i in 0..5_000 {
            col1.append(i as f32 * 1.5);
        }

        // Save to buffer
        let mut buf = BytesMut::new();
        col1.save_to_buffer(&mut buf).unwrap();

        // Load from buffer
        let mut col2 = ColumnFloat32::new();
        let mut reader = &buf[..];
        col2.load_from_buffer(&mut reader, 5_000).unwrap();

        assert_eq!(col2.size(), 5_000);
        for i in 0..5_000 {
            assert_eq!(col2.get(i), Some(&(i as f32 * 1.5)));
        }
    }

    #[test]
    fn test_bulk_load_all_numeric_types() {
        // Test bulk load for all numeric types to ensure set_len works
        // correctly

        // UInt8
        let mut col_u8 = ColumnUInt8::new();
        let mut buf = BytesMut::new();
        for i in 0..255u8 {
            buf.put_u8(i);
        }
        let mut reader = &buf[..];
        col_u8.load_from_buffer(&mut reader, 255).unwrap();
        assert_eq!(col_u8.size(), 255);

        // UInt16
        let mut col_u16 = ColumnUInt16::new();
        let mut buf = BytesMut::new();
        for i in 0..1000u16 {
            buf.put_u16_le(i);
        }
        let mut reader = &buf[..];
        col_u16.load_from_buffer(&mut reader, 1000).unwrap();
        assert_eq!(col_u16.size(), 1000);

        // Int8
        let mut col_i8 = ColumnInt8::new();
        let mut buf = BytesMut::new();
        for i in -127..127i8 {
            buf.put_i8(i);
        }
        let mut reader = &buf[..];
        col_i8.load_from_buffer(&mut reader, 254).unwrap();
        assert_eq!(col_i8.size(), 254);

        // Int16
        let mut col_i16 = ColumnInt16::new();
        let mut buf = BytesMut::new();
        for i in 0..1000i16 {
            buf.put_i16_le(i);
        }
        let mut reader = &buf[..];
        col_i16.load_from_buffer(&mut reader, 1000).unwrap();
        assert_eq!(col_i16.size(), 1000);

        // i128 and u128
        let mut col_i128 = ColumnInt128::new();
        let mut buf = BytesMut::new();
        for i in 0..100i128 {
            buf.put_i128_le(i);
        }
        let mut reader = &buf[..];
        col_i128.load_from_buffer(&mut reader, 100).unwrap();
        assert_eq!(col_i128.size(), 100);

        let mut col_u128 = ColumnUInt128::new();
        let mut buf = BytesMut::new();
        for i in 0..100u128 {
            buf.put_u128_le(i);
        }
        let mut reader = &buf[..];
        col_u128.load_from_buffer(&mut reader, 100).unwrap();
        assert_eq!(col_u128.size(), 100);
    }

    #[test]
    fn test_bulk_load_memory_safety() {
        // This test specifically validates that set_len is called AFTER memory
        // initialization If set_len was called before
        // copy_nonoverlapping, this would fail or cause UB
        let mut col = ColumnInt32::new();

        // Create test data with specific pattern
        let mut buf = BytesMut::new();
        let test_values: Vec<i32> =
            vec![i32::MIN, -1_000_000, -1, 0, 1, 1_000_000, i32::MAX];
        for &val in &test_values {
            buf.put_i32_le(val);
        }

        // Load using bulk copy
        let mut reader = &buf[..];
        col.load_from_buffer(&mut reader, test_values.len()).unwrap();

        // Verify all values are correctly initialized
        assert_eq!(col.size(), test_values.len());
        for (i, &expected) in test_values.iter().enumerate() {
            assert_eq!(
                col.get(i),
                Some(&expected),
                "Value mismatch at index {}",
                i
            );
        }
    }
}