kszucs commented on a change in pull request #439:
URL: https://github.com/apache/arrow-rs/pull/439#discussion_r655509158



##########
File path: arrow/src/datatypes/ffi.rs
##########
@@ -0,0 +1,287 @@
+// 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.
+
+use std::convert::TryFrom;
+
+use crate::{
+    datatypes::{DataType, Field, Schema, TimeUnit},
+    error::{ArrowError, Result},
+    ffi::{FFI_ArrowSchema, Flags},
+};
+
+impl TryFrom<&FFI_ArrowSchema> for DataType {
+    type Error = ArrowError;
+
+    /// See 
https://arrow.apache.org/docs/format/CDataInterface.html#data-type-description-format-strings
+    fn try_from(c_schema: &FFI_ArrowSchema) -> Result<Self> {
+        let dtype = match c_schema.format() {
+            "n" => DataType::Null,
+            "b" => DataType::Boolean,
+            "c" => DataType::Int8,
+            "C" => DataType::UInt8,
+            "s" => DataType::Int16,
+            "S" => DataType::UInt16,
+            "i" => DataType::Int32,
+            "I" => DataType::UInt32,
+            "l" => DataType::Int64,
+            "L" => DataType::UInt64,
+            "e" => DataType::Float16,
+            "f" => DataType::Float32,
+            "g" => DataType::Float64,
+            "z" => DataType::Binary,
+            "Z" => DataType::LargeBinary,
+            "u" => DataType::Utf8,
+            "U" => DataType::LargeUtf8,
+            "tdD" => DataType::Date32,
+            "tdm" => DataType::Date64,
+            "tts" => DataType::Time32(TimeUnit::Second),
+            "ttm" => DataType::Time32(TimeUnit::Millisecond),
+            "ttu" => DataType::Time64(TimeUnit::Microsecond),
+            "ttn" => DataType::Time64(TimeUnit::Nanosecond),
+            "+l" => {
+                let c_child = c_schema.child(0);
+                DataType::List(Box::new(Field::try_from(c_child)?))
+            }
+            "+L" => {
+                let c_child = c_schema.child(0);
+                DataType::LargeList(Box::new(Field::try_from(c_child)?))
+            }
+            "+s" => {
+                let fields = c_schema.children().map(Field::try_from);
+                DataType::Struct(fields.collect::<Result<Vec<_>>>()?)
+            }
+            other => {
+                return Err(ArrowError::CDataInterface(format!(
+                    "The datatype \"{:?}\" is still not supported in Rust 
implementation",
+                    other
+                )))
+            }
+        };
+        Ok(dtype)
+    }
+}
+
+impl TryFrom<&FFI_ArrowSchema> for Field {
+    type Error = ArrowError;
+
+    fn try_from(c_schema: &FFI_ArrowSchema) -> Result<Self> {
+        let dtype = DataType::try_from(c_schema)?;
+        let field = Field::new(c_schema.name(), dtype, c_schema.nullable());
+        Ok(field)

Review comment:
       https://github.com/apache/arrow-rs/issues/478

##########
File path: arrow/src/ffi.rs
##########
@@ -122,66 +132,61 @@ unsafe extern "C" fn release_schema(schema: *mut 
FFI_ArrowSchema) {
     let schema = &mut *schema;
 
     // take ownership back to release it.
-    CString::from_raw(schema.format as *mut std::os::raw::c_char);
-    CString::from_raw(schema.name as *mut std::os::raw::c_char);
-    let private = Box::from_raw(schema.private_data as *mut SchemaPrivateData);
-    for child in private.children_ptr.iter() {
-        let _ = Box::from_raw(*child);
+    CString::from_raw(schema.format as *mut c_char);
+    if !schema.name.is_null() {
+        CString::from_raw(schema.name as *mut c_char);
+    }
+    if !schema.private_data.is_null() {
+        let private_data = Box::from_raw(schema.private_data as *mut 
SchemaPrivateData);
+        for child in private_data.children.iter() {
+            drop(Box::from_raw(*child))
+        }
+        drop(private_data);
     }
 
     schema.release = None;
 }
 
 impl FFI_ArrowSchema {
     /// create a new [`Ffi_ArrowSchema`]. This fails if the fields' 
[`DataType`] is not supported.
-    fn try_new(field: Field) -> Result<FFI_ArrowSchema> {
-        let format = to_format(field.data_type())?;
-        let name = field.name().clone();
-
-        // allocate (and hold) the children
-        let children_vec = match field.data_type() {
-            DataType::List(field) => {
-                
vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)]
-            }
-            DataType::LargeList(field) => {
-                
vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)]
-            }
-            DataType::Struct(fields) => fields
-                .iter()
-                .map(|field| 
Ok(Box::new(FFI_ArrowSchema::try_new(field.clone())?)))
-                .collect::<Result<Vec<_>>>()?,
-            _ => vec![],
-        };
-        // note: this cannot be done along with the above because the above is 
fallible and this op leaks.
-        let children_ptr = children_vec
+    pub fn try_new(format: &str, children: Vec<FFI_ArrowSchema>) -> 
Result<Self> {
+        let mut this = Self::empty();
+
+        // note: this op leaks.
+        let mut children_ptr = children
             .into_iter()
+            .map(Box::new)
             .map(Box::into_raw)
             .collect::<Box<_>>();
-        let n_children = children_ptr.len() as i64;
 
-        let flags = field.is_nullable() as i64 * 2;
+        this.format = CString::new(format).unwrap().into_raw();
+        this.release = Some(release_schema);
+        this.n_children = children_ptr.len() as i64;
+        this.children = children_ptr.as_mut_ptr();
 
-        let mut private = Box::new(SchemaPrivateData {
-            field,
-            children_ptr,
+        let private_data = Box::new(SchemaPrivateData {
+            children: children_ptr,
         });
+        this.private_data = Box::into_raw(private_data) as *mut c_void;
 
-        // 
<https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema>
-        Ok(FFI_ArrowSchema {
-            format: CString::new(format).unwrap().into_raw(),
-            name: CString::new(name).unwrap().into_raw(),
-            metadata: std::ptr::null_mut(),
-            flags,
-            n_children,
-            children: private.children_ptr.as_mut_ptr(),
-            dictionary: std::ptr::null_mut(),
-            release: Some(release_schema),
-            private_data: Box::into_raw(private) as *mut 
::std::os::raw::c_void,
-        })
+        Ok(this)
+    }
+
+    pub fn with_name(mut self, name: &str) -> Result<Self> {
+        self.name = CString::new(name).unwrap().into_raw();
+        Ok(self)
+    }
+
+    pub fn with_flags(mut self, flags: Flags) -> Result<Self> {
+        self.flags = flags.bits();
+        Ok(self)
     }
 
+    // pub fn with_dictionary() {}
+    // pub fn with_metadata() {}

Review comment:
       https://github.com/apache/arrow-rs/issues/478




-- 
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.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to