arrow-array 60.0.0

Array abstractions for Apache Arrow
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Contains declarations to bind to the [C Stream Interface](https://arrow.apache.org/docs/format/CStreamInterface.html).
//!
//! This module has two main interfaces:
//! One interface maps C ABI to native Rust types, i.e. convert c-pointers, c_char, to native rust.
//! This is handled by [FFI_ArrowArrayStream].
//!
//! The second interface is used to import `FFI_ArrowArrayStream` as Rust implementation `RecordBatch` reader.
//! This is handled by `ArrowArrayStreamReader`.
//!
//! ```ignore
//! # use std::fs::File;
//! # use std::sync::Arc;
//! # use arrow::error::Result;
//! # use arrow::ffi_stream::{export_reader_into_raw, ArrowArrayStreamReader, FFI_ArrowArrayStream};
//! # use arrow::ipc::reader::FileReader;
//! # use arrow::record_batch::RecordBatchReader;
//! # fn main() -> Result<()> {
//! // create an record batch reader natively
//! let file = File::open("arrow_file").unwrap();
//! let reader = Box::new(FileReader::try_new(file).unwrap());
//!
//! // export it
//! let mut stream = FFI_ArrowArrayStream::empty();
//! unsafe { export_reader_into_raw(reader, &mut stream) };
//!
//! // consumed and used by something else...
//!
//! // import it
//! let stream_reader = unsafe { ArrowArrayStreamReader::from_raw(&mut stream).unwrap() };
//! let imported_schema = stream_reader.schema();
//!
//! let mut produced_batches = vec![];
//! for batch in stream_reader {
//!      produced_batches.push(batch.unwrap());
//! }
//! Ok(())
//! }
//! ```

use arrow_schema::DataType;
use std::ffi::CStr;
use std::ptr::addr_of;
use std::{
    ffi::CString,
    os::raw::{c_char, c_int, c_void},
    sync::Arc,
};

use arrow_data::ffi::FFI_ArrowArray;
use arrow_schema::{ArrowError, Schema, SchemaRef, ffi::FFI_ArrowSchema};

use crate::RecordBatchOptions;
use crate::array::Array;
use crate::array::StructArray;
use crate::ffi::from_ffi_and_data_type;
use crate::record_batch::{RecordBatch, RecordBatchReader};

type Result<T> = std::result::Result<T, ArrowError>;

// Errno values returned through the C stream interface, taken from libc so they match
// the platform the consumer interprets them against.
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
use libc::{EINVAL, EIO, ENOMEM, ENOSYS};

// wasm32-unknown-unknown has no libc, and no OS to interpret the codes either — any
// non-zero value works there, so use Linux's.
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
const ENOMEM: i32 = 12;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
const EIO: i32 = 5;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
const EINVAL: i32 = 22;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
const ENOSYS: i32 = 38;

/// ABI-compatible struct for `ArrayStream` from C Stream Interface
/// See <https://arrow.apache.org/docs/format/CStreamInterface.html#structure-definitions>
/// This was created by bindgen
#[repr(C)]
#[derive(Debug)]
pub struct FFI_ArrowArrayStream {
    // Fields are intentionally private so safety guarantees can be upheld via
    // explicit unsafe functions.
    /// C function to get schema from the stream
    get_schema: Option<unsafe extern "C" fn(arg1: *mut Self, out: *mut FFI_ArrowSchema) -> c_int>,
    /// C function to get next array from the stream
    get_next: Option<unsafe extern "C" fn(arg1: *mut Self, out: *mut FFI_ArrowArray) -> c_int>,
    /// C function to get the error from last operation on the stream
    get_last_error: Option<unsafe extern "C" fn(arg1: *mut Self) -> *const c_char>,
    /// C function to release the stream
    release: Option<unsafe extern "C" fn(arg1: *mut Self)>,
    /// Private data used by the stream, owned by the release callback.
    private_data: *mut c_void,
}

unsafe impl Send for FFI_ArrowArrayStream {}

// callback used to drop [FFI_ArrowArrayStream] when it is exported.
unsafe extern "C" fn release_stream(stream: *mut FFI_ArrowArrayStream) {
    if stream.is_null() {
        return;
    }
    let stream = unsafe { &mut *stream };

    stream.get_schema = None;
    stream.get_next = None;
    stream.get_last_error = None;

    let private_data = unsafe { Box::from_raw(stream.private_data.cast::<StreamPrivateData>()) };
    drop(private_data);

    stream.release = None;
}

struct StreamPrivateData {
    batch_reader: Box<dyn RecordBatchReader + Send>,
    last_error: Option<CString>,
}

// The callback used to get array schema
unsafe extern "C" fn get_schema(
    stream: *mut FFI_ArrowArrayStream,
    schema: *mut FFI_ArrowSchema,
) -> c_int {
    ExportedArrayStream { stream }.get_schema(schema)
}

// The callback used to get next array
unsafe extern "C" fn get_next(
    stream: *mut FFI_ArrowArrayStream,
    array: *mut FFI_ArrowArray,
) -> c_int {
    ExportedArrayStream { stream }.get_next(array)
}

// The callback used to get the error from last operation on the `FFI_ArrowArrayStream`
unsafe extern "C" fn get_last_error(stream: *mut FFI_ArrowArrayStream) -> *const c_char {
    let mut ffi_stream = ExportedArrayStream { stream };
    // The consumer should not take ownership of this string, we should return
    // a const pointer to it.
    match ffi_stream.get_last_error() {
        Some(err_string) => err_string.as_ptr(),
        None => std::ptr::null(),
    }
}

impl Drop for FFI_ArrowArrayStream {
    fn drop(&mut self) {
        match self.release {
            None => (),
            Some(release) => unsafe { release(self) },
        }
    }
}

impl FFI_ArrowArrayStream {
    /// Creates a new [`FFI_ArrowArrayStream`].
    pub fn new(batch_reader: Box<dyn RecordBatchReader + Send>) -> Self {
        let private_data = Box::new(StreamPrivateData {
            batch_reader,
            last_error: None,
        });

        Self {
            get_schema: Some(get_schema),
            get_next: Some(get_next),
            get_last_error: Some(get_last_error),
            release: Some(release_stream),
            private_data: Box::into_raw(private_data).cast::<c_void>(),
        }
    }

    /// Takes ownership of the pointed to [`FFI_ArrowArrayStream`]
    ///
    /// This acts to [move] the data out of `raw_stream`, setting the release callback to NULL
    ///
    /// # Safety
    ///
    /// * `raw_stream` must be [valid] for reads and writes
    /// * `raw_stream` must be properly aligned
    /// * `raw_stream` must point to a properly initialized value of [`FFI_ArrowArrayStream`]
    ///
    /// [move]: https://arrow.apache.org/docs/format/CDataInterface.html#moving-an-array
    /// [valid]: https://doc.rust-lang.org/std/ptr/index.html#safety
    pub unsafe fn from_raw(raw_stream: *mut FFI_ArrowArrayStream) -> Self {
        unsafe { std::ptr::replace(raw_stream, Self::empty()) }
    }

    /// Creates a new empty [FFI_ArrowArrayStream]. Used to import from the C Stream Interface.
    pub fn empty() -> Self {
        Self {
            get_schema: None,
            get_next: None,
            get_last_error: None,
            release: None,
            private_data: std::ptr::null_mut(),
        }
    }

    /// Returns the producer-provided release callback, if any.
    pub fn release(&self) -> Option<unsafe extern "C" fn(arg1: *mut Self)> {
        self.release
    }

    /// Returns the opaque producer-provided private data pointer.
    pub fn private_data(&self) -> *mut c_void {
        self.private_data
    }

    /// Replaces the release callback, returning the previous one.
    ///
    /// Lets a consumer wrap release: save the old callback, install its own, and
    /// chain back on drop. See <https://github.com/apache/arrow-rs/issues/9771>.
    ///
    /// # Safety
    ///
    /// [`Drop`] calls this callback with a pointer to `self`. The new callback
    /// must correctly release this stream (usually by chaining to the returned
    /// one) and must match the [`FFI_ArrowArrayStream::private_data`] it reads.
    /// A wrong callback is undefined behavior on drop.
    pub unsafe fn set_release(
        &mut self,
        release: Option<unsafe extern "C" fn(arg1: *mut Self)>,
    ) -> Option<unsafe extern "C" fn(arg1: *mut Self)> {
        std::mem::replace(&mut self.release, release)
    }

    /// Replaces the private data pointer, returning the previous one.
    ///
    /// # Safety
    ///
    /// The old pointer is returned without being freed; the caller owns it from
    /// here. The new pointer must match what the current
    /// [`FFI_ArrowArrayStream::release`] callback expects.
    pub unsafe fn set_private_data(&mut self, private_data: *mut c_void) -> *mut c_void {
        std::mem::replace(&mut self.private_data, private_data)
    }
}

struct ExportedArrayStream {
    stream: *mut FFI_ArrowArrayStream,
}

impl ExportedArrayStream {
    fn get_private_data(&mut self) -> &mut StreamPrivateData {
        unsafe { &mut *(*self.stream).private_data.cast::<StreamPrivateData>() }
    }

    pub fn get_schema(&mut self, out: *mut FFI_ArrowSchema) -> i32 {
        let private_data = self.get_private_data();
        let reader = &private_data.batch_reader;

        let schema = FFI_ArrowSchema::try_from(reader.schema().as_ref());

        match schema {
            Ok(schema) => {
                unsafe { std::ptr::copy(addr_of!(schema), out, 1) };
                std::mem::forget(schema);
                0
            }
            Err(ref err) => {
                private_data.last_error = Some(
                    CString::new(err.to_string()).expect("Error string has a null byte in it."),
                );
                get_error_code(err)
            }
        }
    }

    pub fn get_next(&mut self, out: *mut FFI_ArrowArray) -> i32 {
        let private_data = self.get_private_data();
        let reader = &mut private_data.batch_reader;

        match reader.next() {
            None => {
                // Marks ArrowArray released to indicate reaching the end of stream.
                unsafe { std::ptr::write(out, FFI_ArrowArray::empty()) }
                0
            }
            Some(next_batch) => {
                if let Ok(batch) = next_batch {
                    let struct_array = StructArray::from(batch);
                    let array = FFI_ArrowArray::new(&struct_array.to_data());

                    unsafe { std::ptr::write_unaligned(out, array) };
                    0
                } else {
                    let err = &next_batch.unwrap_err();
                    private_data.last_error = Some(
                        CString::new(err.to_string()).expect("Error string has a null byte in it."),
                    );
                    get_error_code(err)
                }
            }
        }
    }

    pub fn get_last_error(&mut self) -> Option<&CString> {
        self.get_private_data().last_error.as_ref()
    }
}

fn get_error_code(err: &ArrowError) -> i32 {
    match err {
        ArrowError::NotYetImplemented(_) => ENOSYS,
        ArrowError::MemoryError(_) => ENOMEM,
        ArrowError::IoError(_, _) => EIO,
        _ => EINVAL,
    }
}

/// A `RecordBatchReader` which imports Arrays from `FFI_ArrowArrayStream`.
///
/// Struct used to fetch `RecordBatch` from the C Stream Interface.
/// Its main responsibility is to expose `RecordBatchReader` functionality
/// that requires [FFI_ArrowArrayStream].
#[derive(Debug)]
pub struct ArrowArrayStreamReader {
    stream: FFI_ArrowArrayStream,
    schema: SchemaRef,
}

/// Returns the producer's message for the last failed call on a `FFI_ArrowArrayStream`.
///
/// Returns `None` when the producer supplies no message, either because it installs no
/// `get_last_error` callback or because that callback returns NULL: the C Stream Interface
/// lets `get_last_error` return NULL when no detailed description is available.
///
/// # Safety
///
/// `stream_ptr` must point to a valid, not yet released [`FFI_ArrowArrayStream`], and the last
/// operation on it must have returned an error: the C Stream Interface forbids calling
/// `get_last_error` in any other case.
unsafe fn producer_error(stream_ptr: *mut FFI_ArrowArrayStream) -> Option<String> {
    let get_last_error = unsafe { (*stream_ptr).get_last_error }?;

    let error_str = unsafe { get_last_error(stream_ptr) };
    if error_str.is_null() {
        return None;
    }

    Some(
        unsafe { CStr::from_ptr(error_str) }
            .to_string_lossy()
            .into_owned(),
    )
}

/// Gets schema from a raw pointer of `FFI_ArrowArrayStream`. This is used when constructing
/// `ArrowArrayStreamReader` to cache schema.
fn get_stream_schema(stream_ptr: *mut FFI_ArrowArrayStream) -> Result<SchemaRef> {
    let mut schema = FFI_ArrowSchema::empty();

    let ret_code = unsafe { (*stream_ptr).get_schema.unwrap()(stream_ptr, &raw mut schema) };

    if ret_code == 0 {
        let schema = Schema::try_from(&schema)?;
        Ok(Arc::new(schema))
    } else {
        let message = format!("Cannot get schema from input stream. Error code: {ret_code}");
        // SAFETY: `stream_ptr` is valid and unreleased, and the `get_schema` call above
        // returned a non-zero code.
        let message = match unsafe { producer_error(stream_ptr) } {
            Some(producer_message) => format!("{message}. Producer error: {producer_message}"),
            None => message,
        };
        Err(ArrowError::CDataInterface(message))
    }
}

impl ArrowArrayStreamReader {
    /// Creates a new `ArrowArrayStreamReader` from a `FFI_ArrowArrayStream`.
    /// This is used to import from the C Stream Interface.
    pub fn try_new(mut stream: FFI_ArrowArrayStream) -> Result<Self> {
        if stream.release.is_none() {
            return Err(ArrowError::CDataInterface(
                "input stream is already released".to_string(),
            ));
        }

        let schema = get_stream_schema(&raw mut stream)?;

        Ok(Self { stream, schema })
    }

    /// Creates a new `ArrowArrayStreamReader` from a raw pointer of `FFI_ArrowArrayStream`.
    ///
    /// Assumes that the pointer represents valid C Stream Interfaces.
    /// This function copies the content from the raw pointer and cleans up it to prevent
    /// double-dropping. The caller is responsible for freeing up the memory allocated for
    /// the pointer.
    ///
    /// # Safety
    ///
    /// See [`FFI_ArrowArrayStream::from_raw`]
    pub unsafe fn from_raw(raw_stream: *mut FFI_ArrowArrayStream) -> Result<Self> {
        Self::try_new(unsafe { FFI_ArrowArrayStream::from_raw(raw_stream) })
    }
}

impl Iterator for ArrowArrayStreamReader {
    type Item = Result<RecordBatch>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut array = FFI_ArrowArray::empty();

        let ret_code =
            unsafe { self.stream.get_next.unwrap()(&raw mut self.stream, &raw mut array) };

        if ret_code == 0 {
            // The end of stream has been reached
            if array.is_released() {
                return None;
            }

            let result = unsafe {
                from_ffi_and_data_type(array, DataType::Struct(self.schema().fields().clone()))
            };
            Some(result.and_then(|data| {
                let len = data.len();
                RecordBatch::try_new_with_options(
                    self.schema.clone(),
                    StructArray::from(data).into_parts().1,
                    &RecordBatchOptions::new().with_row_count(Some(len)),
                )
            }))
        } else {
            let message =
                format!("Cannot get next batch from input stream. Error code: {ret_code}");
            // SAFETY: `self.stream` is valid and unreleased by construction, and the
            // `get_next` call above returned a non-zero code.
            let message = match unsafe { producer_error(&raw mut self.stream) } {
                Some(producer_message) => format!("{message}. Producer error: {producer_message}"),
                None => message,
            };
            Some(Err(ArrowError::CDataInterface(message)))
        }
    }
}

impl RecordBatchReader for ArrowArrayStreamReader {
    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }
}

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

    use arrow_schema::Field;

    use crate::array::Int32Array;
    use crate::ffi::from_ffi;

    struct TestRecordBatchReader {
        schema: SchemaRef,
        iter: Box<dyn Iterator<Item = Result<RecordBatch>> + Send>,
    }

    impl TestRecordBatchReader {
        pub fn new(
            schema: SchemaRef,
            iter: Box<dyn Iterator<Item = Result<RecordBatch>> + Send>,
        ) -> TestRecordBatchReader {
            TestRecordBatchReader { schema, iter }
        }
    }

    impl Iterator for TestRecordBatchReader {
        type Item = Result<RecordBatch>;

        fn next(&mut self) -> Option<Self::Item> {
            self.iter.next()
        }
    }

    impl RecordBatchReader for TestRecordBatchReader {
        fn schema(&self) -> SchemaRef {
            self.schema.clone()
        }
    }

    fn _test_round_trip_export(batch: RecordBatch, schema: Arc<Schema>) -> Result<()> {
        let iter = Box::new(vec![batch.clone(), batch.clone()].into_iter().map(Ok)) as _;

        let reader = Box::new(TestRecordBatchReader::new(schema.clone(), iter));

        // Export a `RecordBatchReader` through `FFI_ArrowArrayStream`
        let mut ffi_stream = FFI_ArrowArrayStream::new(reader);

        // Get schema from `FFI_ArrowArrayStream`
        let mut ffi_schema = FFI_ArrowSchema::empty();
        let ret_code = unsafe { get_schema(&raw mut ffi_stream, &raw mut ffi_schema) };
        assert_eq!(ret_code, 0);

        let exported_schema = Schema::try_from(&ffi_schema).unwrap();
        assert_eq!(&exported_schema, schema.as_ref());

        // Get array from `FFI_ArrowArrayStream`
        let mut produced_batches = vec![];
        loop {
            let mut ffi_array = FFI_ArrowArray::empty();
            let ret_code = unsafe { get_next(&raw mut ffi_stream, &raw mut ffi_array) };
            assert_eq!(ret_code, 0);

            // The end of stream has been reached
            if ffi_array.is_released() {
                break;
            }

            let array = unsafe { from_ffi(ffi_array, &ffi_schema) }.unwrap();
            let len = array.len();

            let record_batch = RecordBatch::try_new_with_options(
                SchemaRef::from(exported_schema.clone()),
                StructArray::from(array).into_parts().1,
                &RecordBatchOptions::new().with_row_count(Some(len)),
            )
            .unwrap();
            produced_batches.push(record_batch);
        }

        assert_eq!(produced_batches, vec![batch.clone(), batch]);

        Ok(())
    }

    fn _test_round_trip_import(batch: RecordBatch, schema: Arc<Schema>) -> Result<()> {
        let iter = Box::new(vec![batch.clone(), batch.clone()].into_iter().map(Ok)) as _;

        let reader = Box::new(TestRecordBatchReader::new(schema.clone(), iter));

        // Import through `FFI_ArrowArrayStream` as `ArrowArrayStreamReader`
        let stream = FFI_ArrowArrayStream::new(reader);
        let stream_reader = ArrowArrayStreamReader::try_new(stream).unwrap();

        let imported_schema = stream_reader.schema();
        assert_eq!(imported_schema, schema);

        let mut produced_batches = vec![];
        for batch in stream_reader {
            produced_batches.push(batch.unwrap());
        }

        assert_eq!(produced_batches, vec![batch.clone(), batch]);

        Ok(())
    }

    #[test]
    fn test_stream_round_trip() {
        let array = Int32Array::from(vec![Some(2), None, Some(1), None]);
        let array: Arc<dyn Array> = Arc::new(array);
        let metadata = HashMap::from([("foo".to_owned(), "bar".to_owned())]);

        let schema = Arc::new(Schema::new_with_metadata(
            vec![
                Field::new("a", array.data_type().clone(), true).with_metadata(metadata.clone()),
                Field::new("b", array.data_type().clone(), true).with_metadata(metadata.clone()),
                Field::new("c", array.data_type().clone(), true).with_metadata(metadata.clone()),
            ],
            metadata,
        ));
        let batch = RecordBatch::try_new(schema.clone(), vec![array.clone(), array.clone(), array])
            .unwrap();

        _test_round_trip_export(batch.clone(), schema.clone()).unwrap();
        _test_round_trip_import(batch, schema).unwrap();
    }

    #[test]
    fn test_stream_round_trip_no_columns() {
        let metadata = HashMap::from([("foo".to_owned(), "bar".to_owned())]);

        let schema = Arc::new(Schema::new_with_metadata(Vec::<Field>::new(), metadata));
        let batch = RecordBatch::try_new_with_options(
            schema.clone(),
            Vec::<Arc<dyn Array>>::new(),
            &RecordBatchOptions::new().with_row_count(Some(10)),
        )
        .unwrap();

        _test_round_trip_export(batch.clone(), schema.clone()).unwrap();
        _test_round_trip_import(batch, schema).unwrap();
    }

    #[test]
    fn test_error_import() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));

        let iter =
            Box::new(vec![Err(ArrowError::MemoryError("out of memory".to_string()))].into_iter());

        let reader = Box::new(TestRecordBatchReader::new(schema.clone(), iter));

        // Import through `FFI_ArrowArrayStream` as `ArrowArrayStreamReader`
        let stream = FFI_ArrowArrayStream::new(reader);
        let stream_reader = ArrowArrayStreamReader::try_new(stream).unwrap();

        let imported_schema = stream_reader.schema();
        assert_eq!(imported_schema, schema);

        let mut produced_batches = vec![];
        for batch in stream_reader {
            produced_batches.push(batch);
        }

        // The results should outlive the lifetime of the stream itself.
        assert_eq!(produced_batches.len(), 1);
        assert_eq!(
            produced_batches[0].as_ref().unwrap_err().to_string(),
            format!(
                "C Data interface error: Cannot get next batch from input stream. \
                 Error code: {ENOMEM}. Producer error: Memory error: out of memory"
            )
        );

        Ok(())
    }

    unsafe extern "C" fn failing_get_schema(
        _stream: *mut FFI_ArrowArrayStream,
        _out: *mut FFI_ArrowSchema,
    ) -> c_int {
        EIO
    }

    unsafe extern "C" fn working_get_schema(
        _stream: *mut FFI_ArrowArrayStream,
        out: *mut FFI_ArrowSchema,
    ) -> c_int {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
        unsafe { std::ptr::write(out, FFI_ArrowSchema::try_from(&schema).unwrap()) };
        0
    }

    unsafe extern "C" fn failing_get_next(
        _stream: *mut FFI_ArrowArrayStream,
        _out: *mut FFI_ArrowArray,
    ) -> c_int {
        EIO
    }

    unsafe extern "C" fn producer_last_error(_stream: *mut FFI_ArrowArrayStream) -> *const c_char {
        c"the producer failed".as_ptr()
    }

    unsafe extern "C" fn null_last_error(_stream: *mut FFI_ArrowArrayStream) -> *const c_char {
        std::ptr::null()
    }

    unsafe extern "C" fn mark_released(stream: *mut FFI_ArrowArrayStream) {
        unsafe { (*stream).release = None };
    }

    fn failing_stream(
        get_last_error: Option<unsafe extern "C" fn(*mut FFI_ArrowArrayStream) -> *const c_char>,
    ) -> FFI_ArrowArrayStream {
        let mut stream = FFI_ArrowArrayStream::empty();
        stream.get_schema = Some(failing_get_schema);
        stream.get_next = Some(failing_get_next);
        stream.get_last_error = get_last_error;
        stream.release = Some(mark_released);
        stream
    }

    #[test]
    fn test_import_schema_error_reports_producer_message() {
        let err =
            ArrowArrayStreamReader::try_new(failing_stream(Some(producer_last_error))).unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "C Data interface error: Cannot get schema from input stream. \
                 Error code: {EIO}. Producer error: the producer failed"
            )
        );
    }

    #[test]
    fn test_import_schema_error_without_producer_message() {
        // A producer need not supply a message: `get_last_error` may return NULL when no
        // detailed description is available.
        let err =
            ArrowArrayStreamReader::try_new(failing_stream(Some(null_last_error))).unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "C Data interface error: Cannot get schema from input stream. Error code: {EIO}"
            )
        );
    }

    #[test]
    fn test_import_schema_error_without_error_callback() {
        let err = ArrowArrayStreamReader::try_new(failing_stream(None)).unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "C Data interface error: Cannot get schema from input stream. Error code: {EIO}"
            )
        );
    }

    #[test]
    fn test_import_next_error_without_producer_message() {
        // Previously panicked: the message was unwrapped without checking that the producer
        // supplied one.
        let mut stream = failing_stream(Some(null_last_error));
        stream.get_schema = Some(working_get_schema);

        let err = ArrowArrayStreamReader::try_new(stream)
            .unwrap()
            .next()
            .unwrap()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "C Data interface error: Cannot get next batch from input stream. Error code: {EIO}"
            )
        );
    }

    // A consumer wraps the release callback with its own, then chains back to
    // the original on drop. This is the same wrap-release pattern the
    // release/private_data accessors exist for (#9771).
    static STREAM_WRAPPER_RAN: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    struct StreamWrapperData {
        original_release: Option<unsafe extern "C" fn(*mut FFI_ArrowArrayStream)>,
        original_private_data: *mut c_void,
    }

    unsafe extern "C" fn wrapping_release(stream: *mut FFI_ArrowArrayStream) {
        use std::sync::atomic::Ordering;
        let stream = unsafe { &mut *stream };
        let data = unsafe { Box::from_raw(stream.private_data().cast::<StreamWrapperData>()) };
        STREAM_WRAPPER_RAN.store(true, Ordering::SeqCst);
        unsafe { stream.set_release(data.original_release) };
        unsafe { stream.set_private_data(data.original_private_data) };
        if let Some(release) = stream.release() {
            unsafe { release(stream) };
        }
    }

    #[test]
    fn test_wrap_release_callback() {
        use std::sync::atomic::Ordering;

        let batch_reader = Box::new(TestRecordBatchReader::new(
            Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])),
            Box::new(std::iter::empty()),
        ));
        let mut stream = FFI_ArrowArrayStream::new(batch_reader);

        let data = Box::new(StreamWrapperData {
            original_release: stream.release(),
            original_private_data: stream.private_data(),
        });
        unsafe { stream.set_release(Some(wrapping_release)) };
        unsafe { stream.set_private_data(Box::into_raw(data).cast::<c_void>()) };

        drop(stream); // runs wrapping_release, which chains to the original
        assert!(STREAM_WRAPPER_RAN.load(Ordering::SeqCst));
    }
}