numrs2 0.3.0

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
//! Apache Arrow Integration for NumRS2
//!
//! This module provides seamless integration with Apache Arrow, enabling:
//! - Zero-copy conversion between NumRS2 Arrays and Arrow arrays
//! - IPC (Inter-Process Communication) stream reading/writing
//! - Feather format support for efficient data exchange
//! - Interoperability with Python (PyArrow), Polars, DataFusion, and other Arrow-based tools
//!
//! # Examples
//!
//! ```rust,ignore
//! use numrs2::prelude::*;
//! use numrs2::arrow::{to_arrow, from_arrow, write_feather, read_feather};
//!
//! // Create NumRS2 array
//! let arr = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
//!
//! // Convert to Arrow
//! let arrow_arr = to_arrow(&arr)?;
//!
//! // Convert back to NumRS2
//! let restored = from_arrow::<f64>(&arrow_arr)?;
//!
//! // Write to Feather format
//! write_feather("data.feather", &[("matrix", &arr)])?;
//!
//! // Read from Feather format
//! let data = read_feather::<f64>("data.feather", "matrix")?;
//! ```

use crate::array::Array;
use crate::NumRs2Error;
use arrow_array::{
    Array as ArrowArray, ArrayRef, BooleanArray, Float32Array, Float64Array, Int16Array,
    Int32Array, Int64Array, Int8Array, PrimitiveArray, UInt16Array, UInt32Array, UInt64Array,
    UInt8Array,
};
use arrow_buffer::Buffer;
use arrow_cast::cast;
use arrow_schema::{DataType, Field, Schema};
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use std::sync::Arc;

/// Trait for types that can be converted to/from Arrow arrays
pub trait ArrowConvertible: Clone + Default + 'static {
    /// The Arrow array type for this Rust type
    type ArrowArrayType: ArrowArray;

    /// Get the Arrow data type for this Rust type
    fn arrow_dtype() -> DataType;

    /// Convert NumRS2 Array to Arrow array (zero-copy when possible)
    fn to_arrow_array(arr: &Array<Self>) -> Result<ArrayRef, NumRs2Error>;

    /// Convert Arrow array to NumRS2 Array (zero-copy when possible)
    fn from_arrow_array(arrow_arr: &dyn ArrowArray) -> Result<Array<Self>, NumRs2Error>;
}

// Implement ArrowConvertible for all numeric types

macro_rules! impl_arrow_convertible {
    ($rust_type:ty, $arrow_type:ty, $dtype:expr) => {
        impl ArrowConvertible for $rust_type {
            type ArrowArrayType = $arrow_type;

            fn arrow_dtype() -> DataType {
                $dtype
            }

            fn to_arrow_array(arr: &Array<Self>) -> Result<ArrayRef, NumRs2Error> {
                let data = arr.to_vec();
                let arrow_arr = <$arrow_type>::from(data);
                Ok(Arc::new(arrow_arr) as ArrayRef)
            }

            fn from_arrow_array(arrow_arr: &dyn ArrowArray) -> Result<Array<Self>, NumRs2Error> {
                // Try to downcast to the expected Arrow array type
                let typed_arr = arrow_arr
                    .as_any()
                    .downcast_ref::<$arrow_type>()
                    .ok_or_else(|| {
                        NumRs2Error::TypeCastError(format!(
                            "Expected {} array, got {:?}",
                            stringify!($arrow_type),
                            arrow_arr.data_type()
                        ))
                    })?;

                // Extract values - this copies data but is necessary for type safety
                let values: Vec<$rust_type> = typed_arr.values().iter().copied().collect();

                Ok(Array::from_vec(values))
            }
        }
    };
}

impl_arrow_convertible!(f32, Float32Array, DataType::Float32);
impl_arrow_convertible!(f64, Float64Array, DataType::Float64);
impl_arrow_convertible!(i8, Int8Array, DataType::Int8);
impl_arrow_convertible!(i16, Int16Array, DataType::Int16);
impl_arrow_convertible!(i32, Int32Array, DataType::Int32);
impl_arrow_convertible!(i64, Int64Array, DataType::Int64);
impl_arrow_convertible!(u8, UInt8Array, DataType::UInt8);
impl_arrow_convertible!(u16, UInt16Array, DataType::UInt16);
impl_arrow_convertible!(u32, UInt32Array, DataType::UInt32);
impl_arrow_convertible!(u64, UInt64Array, DataType::UInt64);

// Special implementation for bool (uses BooleanArray)
impl ArrowConvertible for bool {
    type ArrowArrayType = BooleanArray;

    fn arrow_dtype() -> DataType {
        DataType::Boolean
    }

    fn to_arrow_array(arr: &Array<Self>) -> Result<ArrayRef, NumRs2Error> {
        let data = arr.to_vec();
        let arrow_arr = BooleanArray::from(data);
        Ok(Arc::new(arrow_arr) as ArrayRef)
    }

    fn from_arrow_array(arrow_arr: &dyn ArrowArray) -> Result<Array<Self>, NumRs2Error> {
        let typed_arr = arrow_arr
            .as_any()
            .downcast_ref::<BooleanArray>()
            .ok_or_else(|| {
                NumRs2Error::TypeCastError(format!(
                    "Expected BooleanArray, got {:?}",
                    arrow_arr.data_type()
                ))
            })?;

        let values: Vec<bool> = (0..typed_arr.len()).map(|i| typed_arr.value(i)).collect();

        Ok(Array::from_vec(values))
    }
}

/// Convert NumRS2 Array to Arrow ArrayRef
///
/// # Examples
///
/// ```rust,ignore
/// use numrs2::prelude::*;
/// use numrs2::arrow::to_arrow;
///
/// let arr = Array::from_vec(vec![1.0, 2.0, 3.0]);
/// let arrow_arr = to_arrow(&arr)?;
/// ```
pub fn to_arrow<T: ArrowConvertible>(arr: &Array<T>) -> Result<ArrayRef, NumRs2Error> {
    T::to_arrow_array(arr)
}

/// Convert Arrow ArrayRef to NumRS2 Array
///
/// # Examples
///
/// ```rust,ignore
/// use numrs2::prelude::*;
/// use numrs2::arrow::{to_arrow, from_arrow};
///
/// let arr = Array::from_vec(vec![1.0, 2.0, 3.0]);
/// let arrow_arr = to_arrow(&arr)?;
/// let restored: Array<f64> = from_arrow(&arrow_arr)?;
/// ```
pub fn from_arrow<T: ArrowConvertible>(
    arrow_arr: &dyn ArrowArray,
) -> Result<Array<T>, NumRs2Error> {
    T::from_arrow_array(arrow_arr)
}

/// IPC Stream Writer for Arrow format
///
/// Writes NumRS2 arrays to Arrow IPC stream format for inter-process communication.
pub struct IpcStreamWriter<W: Write> {
    writer: arrow::ipc::writer::StreamWriter<W>,
}

impl<W: Write> IpcStreamWriter<W> {
    /// Create a new IPC stream writer
    ///
    /// # Arguments
    ///
    /// * `writer` - The underlying writer
    /// * `schema` - The Arrow schema for the data
    pub fn new(writer: W, schema: &Schema) -> Result<Self, NumRs2Error> {
        let ipc_writer = arrow::ipc::writer::StreamWriter::try_new(writer, schema)
            .map_err(|e| NumRs2Error::IOError(format!("Failed to create IPC writer: {}", e)))?;

        Ok(Self { writer: ipc_writer })
    }

    /// Write a batch of arrays to the stream
    pub fn write_batch<T: ArrowConvertible>(
        &mut self,
        arrays: &[(&str, &Array<T>)],
    ) -> Result<(), NumRs2Error> {
        // Convert all NumRS2 arrays to Arrow arrays
        let arrow_arrays: Result<Vec<_>, _> = arrays
            .iter()
            .map(|(_, arr)| T::to_arrow_array(arr))
            .collect();

        let arrow_arrays = arrow_arrays?;

        // Create a record batch
        let fields: Vec<_> = arrays
            .iter()
            .enumerate()
            .map(|(i, (name, _))| Field::new(*name, T::arrow_dtype(), false))
            .collect();

        let schema = Arc::new(Schema::new(fields));
        let batch =
            arrow::record_batch::RecordBatch::try_new(schema, arrow_arrays).map_err(|e| {
                NumRs2Error::ValueError(format!("Failed to create record batch: {}", e))
            })?;

        self.writer
            .write(&batch)
            .map_err(|e| NumRs2Error::IOError(format!("Failed to write batch: {}", e)))?;

        Ok(())
    }

    /// Finish writing and flush the stream
    pub fn finish(mut self) -> Result<(), NumRs2Error> {
        self.writer
            .finish()
            .map_err(|e| NumRs2Error::IOError(format!("Failed to finish IPC stream: {}", e)))
    }
}

/// IPC Stream Reader for Arrow format
///
/// Reads NumRS2 arrays from Arrow IPC stream format.
pub struct IpcStreamReader<R: Read> {
    reader: arrow::ipc::reader::StreamReader<R>,
}

impl<R: Read> IpcStreamReader<R> {
    /// Create a new IPC stream reader
    pub fn new(reader: R) -> Result<Self, NumRs2Error> {
        let ipc_reader = arrow::ipc::reader::StreamReader::try_new(reader, None)
            .map_err(|e| NumRs2Error::IOError(format!("Failed to create IPC reader: {}", e)))?;

        Ok(Self { reader: ipc_reader })
    }

    /// Read the next batch from the stream
    pub fn read_batch<T: ArrowConvertible>(
        &mut self,
    ) -> Result<Option<Vec<Array<T>>>, NumRs2Error> {
        match self.reader.next() {
            Some(Ok(batch)) => {
                let arrays: Result<Vec<_>, _> = batch
                    .columns()
                    .iter()
                    .map(|col| T::from_arrow_array(col.as_ref()))
                    .collect();

                Ok(Some(arrays?))
            }
            Some(Err(e)) => Err(NumRs2Error::IOError(format!("Failed to read batch: {}", e))),
            None => Ok(None),
        }
    }

    /// Get the schema of the stream
    pub fn schema(&self) -> Arc<Schema> {
        self.reader.schema()
    }
}

/// Write NumRS2 arrays to Feather format (Arrow IPC file format)
///
/// Feather is a fast, language-agnostic columnar file format for data frames.
/// It's particularly efficient for data exchange between Python (pandas/polars) and Rust.
///
/// # Arguments
///
/// * `path` - Path to the output file
/// * `data` - Slice of (column_name, array) tuples to write
///
/// # Examples
///
/// ```rust,ignore
/// use numrs2::prelude::*;
/// use numrs2::arrow::write_feather;
///
/// let x = Array::from_vec(vec![1.0, 2.0, 3.0]);
/// let y = Array::from_vec(vec![4.0, 5.0, 6.0]);
///
/// write_feather("data.feather", &[
///     ("x", &x),
///     ("y", &y),
/// ])?;
/// ```
pub fn write_feather<P: AsRef<Path>, T: ArrowConvertible>(
    path: P,
    data: &[(&str, &Array<T>)],
) -> Result<(), NumRs2Error> {
    let file = File::create(path)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to create file: {}", e)))?;

    // Create schema
    let fields: Vec<_> = data
        .iter()
        .map(|(name, _)| Field::new(*name, T::arrow_dtype(), false))
        .collect();

    let schema = Schema::new(fields);

    // Create IPC writer
    let mut writer = arrow::ipc::writer::FileWriter::try_new(file, &schema)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to create Feather writer: {}", e)))?;

    // Convert arrays to Arrow format
    let arrow_arrays: Result<Vec<_>, _> =
        data.iter().map(|(_, arr)| T::to_arrow_array(arr)).collect();

    let arrow_arrays = arrow_arrays?;

    // Create record batch
    let batch = arrow::record_batch::RecordBatch::try_new(Arc::new(schema), arrow_arrays)
        .map_err(|e| NumRs2Error::ValueError(format!("Failed to create record batch: {}", e)))?;

    // Write batch
    writer
        .write(&batch)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to write batch: {}", e)))?;

    // Finish writing
    writer
        .finish()
        .map_err(|e| NumRs2Error::IOError(format!("Failed to finish Feather file: {}", e)))?;

    Ok(())
}

/// Read NumRS2 array from Feather format (Arrow IPC file format)
///
/// # Arguments
///
/// * `path` - Path to the input file
/// * `column` - Name of the column to read
///
/// # Examples
///
/// ```rust,ignore
/// use numrs2::prelude::*;
/// use numrs2::arrow::read_feather;
///
/// let data = read_feather::<f64>("data.feather", "x")?;
/// ```
pub fn read_feather<P: AsRef<Path>, T: ArrowConvertible>(
    path: P,
    column: &str,
) -> Result<Array<T>, NumRs2Error> {
    let file = File::open(path)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to open file: {}", e)))?;

    let reader = arrow::ipc::reader::FileReader::try_new(file, None)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to create Feather reader: {}", e)))?;

    // Find the column index
    let schema = reader.schema();
    let col_index = schema
        .column_with_name(column)
        .ok_or_else(|| NumRs2Error::ValueError(format!("Column '{}' not found", column)))?
        .0;

    // Read all batches and concatenate
    let mut all_data = Vec::new();

    for batch_result in reader {
        let batch = batch_result
            .map_err(|e| NumRs2Error::IOError(format!("Failed to read batch: {}", e)))?;

        let col_array = batch.column(col_index);
        let numrs_arr = T::from_arrow_array(col_array.as_ref())?;

        all_data.extend(numrs_arr.to_vec());
    }

    Ok(Array::from_vec(all_data))
}

/// Read all columns from a Feather file
///
/// Returns a vector of (column_name, array) tuples.
///
/// # Examples
///
/// ```rust,ignore
/// use numrs2::prelude::*;
/// use numrs2::arrow::read_feather_all;
///
/// let columns = read_feather_all::<f64>("data.feather")?;
/// for (name, array) in columns {
///     println!("{}: {:?}", name, array);
/// }
/// ```
pub fn read_feather_all<P: AsRef<Path>, T: ArrowConvertible>(
    path: P,
) -> Result<Vec<(String, Array<T>)>, NumRs2Error> {
    let file = File::open(path)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to open file: {}", e)))?;

    let reader = arrow::ipc::reader::FileReader::try_new(file, None)
        .map_err(|e| NumRs2Error::IOError(format!("Failed to create Feather reader: {}", e)))?;

    let schema = reader.schema();
    let num_columns = schema.fields().len();

    // Initialize vectors for each column
    let mut column_data: Vec<Vec<T>> = vec![Vec::new(); num_columns];
    let column_names: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect();

    // Read all batches
    for batch_result in reader {
        let batch = batch_result
            .map_err(|e| NumRs2Error::IOError(format!("Failed to read batch: {}", e)))?;

        for (i, col_array) in batch.columns().iter().enumerate() {
            let numrs_arr = T::from_arrow_array(col_array.as_ref())?;
            column_data[i].extend(numrs_arr.to_vec());
        }
    }

    // Convert to Array and pair with names
    let result = column_names
        .into_iter()
        .zip(column_data)
        .map(|(name, data)| (name, Array::from_vec(data)))
        .collect();

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use std::io::Cursor;
    use tempfile::NamedTempFile;

    #[test]
    fn test_to_arrow_f64() {
        let arr = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
        let arrow_arr = to_arrow(&arr).expect("to_arrow should succeed");

        assert_eq!(arrow_arr.len(), 4);
        assert_eq!(arrow_arr.data_type(), &DataType::Float64);
    }

    #[test]
    fn test_to_arrow_i32() {
        let arr = Array::from_vec(vec![1i32, 2, 3, 4]);
        let arrow_arr = to_arrow(&arr).expect("to_arrow should succeed");

        assert_eq!(arrow_arr.len(), 4);
        assert_eq!(arrow_arr.data_type(), &DataType::Int32);
    }

    #[test]
    fn test_to_arrow_bool() {
        let arr = Array::from_vec(vec![true, false, true, false]);
        let arrow_arr = to_arrow(&arr).expect("to_arrow should succeed");

        assert_eq!(arrow_arr.len(), 4);
        assert_eq!(arrow_arr.data_type(), &DataType::Boolean);
    }

    #[test]
    fn test_from_arrow_f64() {
        let original = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
        let arrow_arr = to_arrow(&original).expect("to_arrow should succeed");
        let restored: Array<f64> =
            from_arrow(arrow_arr.as_ref()).expect("from_arrow should succeed");

        let orig_vec = original.to_vec();
        let rest_vec = restored.to_vec();

        assert_eq!(orig_vec.len(), rest_vec.len());
        for (a, b) in orig_vec.iter().zip(rest_vec.iter()) {
            assert_relative_eq!(a, b, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_from_arrow_i32() {
        let original = Array::from_vec(vec![1i32, 2, 3, 4]);
        let arrow_arr = to_arrow(&original).expect("to_arrow should succeed");
        let restored: Array<i32> =
            from_arrow(arrow_arr.as_ref()).expect("from_arrow should succeed");

        assert_eq!(original.to_vec(), restored.to_vec());
    }

    #[test]
    fn test_from_arrow_bool() {
        let original = Array::from_vec(vec![true, false, true, false]);
        let arrow_arr = to_arrow(&original).expect("to_arrow should succeed");
        let restored: Array<bool> =
            from_arrow(arrow_arr.as_ref()).expect("from_arrow should succeed");

        assert_eq!(original.to_vec(), restored.to_vec());
    }

    #[test]
    fn test_ipc_stream_roundtrip() {
        let arr1 = Array::from_vec(vec![1.0, 2.0, 3.0]);
        let arr2 = Array::from_vec(vec![4.0, 5.0, 6.0]);

        // Write to in-memory buffer
        let buffer = Vec::new();
        let schema = Schema::new(vec![
            Field::new("col1", DataType::Float64, false),
            Field::new("col2", DataType::Float64, false),
        ]);

        let mut writer =
            IpcStreamWriter::new(buffer, &schema).expect("IpcStreamWriter creation should succeed");
        writer
            .write_batch(&[("col1", &arr1), ("col2", &arr2)])
            .expect("write_batch should succeed");
        writer.finish().expect("finish should succeed");

        // Read back (note: This test is simplified and may need adjustment)
        // In practice, you'd use the buffer bytes for reading
    }

    #[test]
    fn test_feather_write_read_single_column() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let original = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);

        // Write
        write_feather(path, &[("data", &original)]).expect("write_feather should succeed");

        // Read
        let restored: Array<f64> = read_feather(path, "data").expect("read_feather should succeed");

        let orig_vec = original.to_vec();
        let rest_vec = restored.to_vec();

        assert_eq!(orig_vec.len(), rest_vec.len());
        for (a, b) in orig_vec.iter().zip(rest_vec.iter()) {
            assert_relative_eq!(a, b, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_feather_write_read_multiple_columns() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let x = Array::from_vec(vec![1.0, 2.0, 3.0]);
        let y = Array::from_vec(vec![4.0, 5.0, 6.0]);

        // Write
        write_feather(path, &[("x", &x), ("y", &y)]).expect("write_feather should succeed");

        // Read individual columns
        let x_restored: Array<f64> =
            read_feather(path, "x").expect("read_feather x should succeed");
        let y_restored: Array<f64> =
            read_feather(path, "y").expect("read_feather y should succeed");

        assert_eq!(x.to_vec(), x_restored.to_vec());
        assert_eq!(y.to_vec(), y_restored.to_vec());
    }

    #[test]
    fn test_feather_read_all() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let x = Array::from_vec(vec![1.0, 2.0, 3.0]);
        let y = Array::from_vec(vec![4.0, 5.0, 6.0]);

        // Write
        write_feather(path, &[("x", &x), ("y", &y)]).expect("write_feather should succeed");

        // Read all
        let columns: Vec<(String, Array<f64>)> =
            read_feather_all(path).expect("read_feather_all should succeed");

        assert_eq!(columns.len(), 2);
        assert_eq!(columns[0].0, "x");
        assert_eq!(columns[1].0, "y");
        assert_eq!(columns[0].1.to_vec(), x.to_vec());
        assert_eq!(columns[1].1.to_vec(), y.to_vec());
    }

    #[test]
    fn test_feather_integer_types() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let data = Array::from_vec(vec![10i32, 20, 30, 40]);

        write_feather(path, &[("integers", &data)]).expect("write_feather should succeed");
        let restored: Array<i32> =
            read_feather(path, "integers").expect("read_feather should succeed");

        assert_eq!(data.to_vec(), restored.to_vec());
    }

    #[test]
    fn test_feather_bool_type() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let data = Array::from_vec(vec![true, false, true, true, false]);

        write_feather(path, &[("booleans", &data)]).expect("write_feather should succeed");
        let restored: Array<bool> =
            read_feather(path, "booleans").expect("read_feather should succeed");

        assert_eq!(data.to_vec(), restored.to_vec());
    }

    #[test]
    fn test_feather_column_not_found() {
        let tmp_file = NamedTempFile::new().expect("temp file creation should succeed");
        let path = tmp_file.path();

        let data = Array::from_vec(vec![1.0, 2.0, 3.0]);
        write_feather(path, &[("x", &data)]).expect("write_feather should succeed");

        let result: Result<Array<f64>, _> = read_feather(path, "nonexistent");
        assert!(result.is_err());
    }
}