sunchao commented on a change in pull request #1384: URL: https://github.com/apache/arrow-rs/pull/1384#discussion_r838814140
########## File path: arrow/src/ffi_stream.rs ########## @@ -0,0 +1,538 @@ +// 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::{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 stream = Arc::new(FFI_ArrowArrayStream::new(reader)); +//! let stream_ptr = FFI_ArrowArrayStream::to_raw(stream) as *mut FFI_ArrowArrayStream; +//! +//! // consumed and used by something else... +//! +//! // import it +//! let stream_reader = unsafe { ArrowArrayStreamReader::from_raw(stream_ptr).unwrap() }; +//! let imported_schema = stream_reader.schema(); +//! +//! let mut produced_batches = vec![]; +//! for batch in stream_reader { +//! produced_batches.push(batch.unwrap()); +//! } +//! +//! // (drop/release) +//! Ok(()) +//! } +//! ``` + +use std::{ + convert::TryFrom, + ffi::CString, + os::raw::{c_char, c_int, c_void}, + sync::Arc, +}; + +use crate::array::Array; +use crate::array::StructArray; +use crate::datatypes::{Schema, SchemaRef}; +use crate::error::ArrowError; +use crate::error::Result; +use crate::ffi::*; +use crate::record_batch::{RecordBatch, RecordBatchReader}; + +const ENOMEM: i32 = 12; +const EIO: i32 = 5; +const EINVAL: i32 = 22; +const ENOSYS: i32 = 78; + +/// ABI-compatible struct for `ArrayStream` from C Stream Interface +/// This interface is experimental +/// See <https://arrow.apache.org/docs/format/CStreamInterface.html#structure-definitions> +/// This was created by bindgen +#[repr(C)] +#[derive(Debug)] +pub struct FFI_ArrowArrayStream { + pub get_schema: Option< + unsafe extern "C" fn( + arg1: *mut FFI_ArrowArrayStream, + out: *mut FFI_ArrowSchema, + ) -> c_int, + >, + pub get_next: Option< + unsafe extern "C" fn( + arg1: *mut FFI_ArrowArrayStream, + out: *mut FFI_ArrowArray, + ) -> c_int, + >, + pub get_last_error: + Option<unsafe extern "C" fn(arg1: *mut FFI_ArrowArrayStream) -> *const c_char>, + pub release: Option<unsafe extern "C" fn(arg1: *mut FFI_ArrowArrayStream)>, + pub private_data: *mut c_void, +} + +// 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 = &mut *stream; + + stream.get_schema = None; + stream.get_next = None; + stream.get_last_error = None; + + let private_data = Box::from_raw(stream.private_data as *mut StreamPrivateData); + drop(private_data); + + stream.release = None; +} + +struct StreamPrivateData { + batch_reader: Box<dyn RecordBatchReader>, + last_error: String, +} + +// 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 }; + let last_error = ffi_stream.get_last_error(); + CString::new(last_error.as_str()).unwrap().into_raw() +} + +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>) -> Self { + let private_data = Box::new(StreamPrivateData { + batch_reader, + last_error: String::new(), + }); + + 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) as *mut c_void, + } + } + + /// 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(), + } + } +} + +struct ExportedArrayStream { + stream: *mut FFI_ArrowArrayStream, +} + +impl ExportedArrayStream { + fn get_private_data(&mut self) -> &mut StreamPrivateData { + unsafe { &mut *((*self.stream).private_data as *mut StreamPrivateData) } + } + + pub fn get_schema(&mut self, out: *mut FFI_ArrowSchema) -> i32 { + unsafe { + match (*out).release { + None => (), + Some(release) => release(out), + }; + }; + + let mut 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(mut schema) => unsafe { + std::ptr::copy(&schema as *const FFI_ArrowSchema, out, 1); + schema.release = None; + 0 + }, + Err(ref err) => { + private_data.last_error = err.to_string(); + get_error_code(err) + } + } + } + + pub fn get_next(&mut self, out: *mut FFI_ArrowArray) -> i32 { + unsafe { + match (*out).release { + None => (), + Some(release) => release(out), + }; + }; + + let mut private_data = self.get_private_data(); + let reader = &mut private_data.batch_reader; + + let ret_code = match reader.next() { + None => 0, + Some(next_batch) => { + if let Ok(batch) = next_batch { + let struct_array = StructArray::from(batch); + let mut array = FFI_ArrowArray::new(struct_array.data()); + + unsafe { + std::ptr::copy(&array as *const FFI_ArrowArray, out, 1); + array.release = None; + 0 + } + } else { + let err = &next_batch.unwrap_err(); + private_data.last_error = err.to_string(); + get_error_code(err) + } + } + }; + + ret_code + } + + pub fn get_last_error(&mut self) -> &String { + &self.get_private_data().last_error + } +} + +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: Arc<FFI_ArrowArrayStream>, Review comment: Ah I see. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org