pitrou commented on code in PR #39091:
URL: https://github.com/apache/arrow/pull/39091#discussion_r1489686080


##########
swift/Arrow/Sources/Arrow/ArrowCImporter.swift:
##########
@@ -0,0 +1,144 @@
+// 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.
+
+import Foundation
+import ArrowC
+
+public class ArrowCImporter {
+    private func appendToBuffer(
+        _ cBuffer: UnsafeRawPointer?,
+        arrowBuffers: inout [ArrowBuffer],
+        byteCount: Int,
+        length: UInt,
+        nullCount: UInt? = nil) {
+        if cBuffer == nil {
+            arrowBuffers.append(ArrowBuffer.createEmptyBuffer())
+            return
+        }
+
+        let pointer = UnsafeMutableRawPointer(mutating: cBuffer)!
+        arrowBuffers.append(
+            ArrowBuffer(length: length, capacity: UInt(byteCount), rawPointer: 
pointer, isMemoryOwner: false))
+    }
+
+    public init() {}
+
+    public func importType(_ cArrow: String, name: String = "") ->
+        Result<ArrowField, ArrowError> {
+        do {
+            let type = try ArrowType.fromCDataFormatId(cArrow)
+            return .success(ArrowField(name, type: ArrowType(type.info), 
isNullable: true))
+        } catch {
+            return .failure(.invalid("\(error)"))
+        }
+    }
+
+    public func importField(_ cSchema: ArrowC.ArrowSchema) ->
+        Result<ArrowField, ArrowError> {
+        if cSchema.n_children > 0 {
+            return .failure(.invalid("Children currently not supported"))
+        } else if cSchema.dictionary != nil {
+            return .failure(.invalid("Dictinoary types currently not 
supported"))
+        }
+
+        switch importType(
+            String(cString: cSchema.format), name: String(cString: 
cSchema.name)) {
+        case .success(let field):
+            release(cSchema)
+            return .success(field)
+        case .failure(let err):
+            return .failure(err)
+        }
+    }
+
+    public func importArray(
+        _ cArray: ArrowC.ArrowArray,
+        arrowType: ArrowType,
+        isNullable: Bool = false) -> Result<ArrowArrayHolder, ArrowError> {
+        let arrowField = ArrowField("", type: arrowType, isNullable: 
isNullable)
+        return importArray(cArray, arrowField: arrowField)
+    }
+
+    public func importArray(
+        _ cArray: ArrowC.ArrowArray,
+        arrowField: ArrowField) -> Result<ArrowArrayHolder, ArrowError> {
+        if cArray.null_count < 0 {
+            return .failure(.invalid("Uncomputed null count is not supported"))
+        } else if cArray.n_children > 0 {
+            return .failure(.invalid("Children currently not supported"))
+        } else if cArray.dictionary != nil {
+            return .failure(.invalid("Dictionary types currently not 
supported"))
+        } else if cArray.offset != 0 {
+            return .failure(.invalid("Offset of 0 is required but found 
offset: \(cArray.offset)"))
+        }
+
+        let arrowType = arrowField.type
+        let length = UInt(cArray.length)
+        let nullCount = UInt(cArray.null_count)
+        let nullBytes = Int(ceil(Double(length) / 8))
+        var arrowBuffers = [ArrowBuffer]()
+
+        if cArray.n_buffers > 0 {
+            if cArray.buffers == nil {
+                return .failure(.invalid("C array buffers is nil"))
+            }
+
+            switch arrowType.info {
+            case .variableInfo:
+                if cArray.n_buffers != 3 {
+                    return .failure(
+                        .invalid("Variable buffer count expected 3 but found 
\(cArray.n_buffers)"))
+                }
+
+                appendToBuffer(cArray.buffers[0], arrowBuffers: &arrowBuffers, 
byteCount: nullBytes, length: length,
+                               nullCount: nullCount)
+                let byteCount = MemoryLayout<Int32>.stride * Int(length + 1)
+                appendToBuffer(cArray.buffers[1], arrowBuffers: &arrowBuffers, 
byteCount: byteCount, length: length)
+                let offsetIndex = MemoryLayout<Int32>.stride * Int(length - 1)
+                let endIndex = arrowBuffers[1].rawPointer.advanced(by: 
offsetIndex).load(as: Int32.self)
+                appendToBuffer(cArray.buffers[2], arrowBuffers: &arrowBuffers, 
byteCount: Int(endIndex), length: length)
+            default:
+                if cArray.n_buffers != 2 {
+                    return .failure(.invalid("Expected buffer count 2 but 
found \(cArray.n_buffers)"))
+                }
+
+                appendToBuffer(cArray.buffers[0], arrowBuffers: &arrowBuffers, 
byteCount: nullBytes, length: length,
+                               nullCount: nullCount)
+                let byteCount = arrowType.getStride() * Int(length)
+                appendToBuffer(cArray.buffers[1], arrowBuffers: &arrowBuffers, 
byteCount: byteCount, length: length)
+            }
+        }
+
+        return makeArrayHolder(arrowField, buffers: arrowBuffers, nullCount: 
nullCount)

Review Comment:
   Hmm, so the general idea is that, once the producer has exported the data, 
the consumer is responsible for calling the `release` callback once it is done 
with the imported data.
   
   When designing a higher-level API to abstract away details of the C Data 
Interface like this, the expectation is that the higher-level API level returns 
some kind of object (depending on the particular Arrow runtime) that ensure 
proper lifetime management of the data backing the imported array.
   
   What "proper lifetime management" means depends on the language and runtime, 
but it should make it so that an imported array has similar semantics as a 
natively-allocated array. If a natively-allocated array has automatic memory 
management through reference counting, then so should an imported array.
   
   For example, in Arrow C++, importing a C array backs the resulting C++ Array 
object with a dedicated [Buffer 
subclass](https://github.com/apache/arrow/blob/91bf1c9c170c1917ad47bb0dbb38aa5c9fbbbfb2/cpp/src/arrow/c/bridge.cc#L1462-L1481)
 that keeps the imported data alive and [calls the `release` 
pointer](https://github.com/apache/arrow/blob/91bf1c9c170c1917ad47bb0dbb38aa5c9fbbbfb2/cpp/src/arrow/c/bridge.cc#L1448-L1455)
 when the last `shared_ptr` reference to it vanishes. The result is that when 
an [imported C++ 
Array](https://github.com/apache/arrow/blob/91bf1c9c170c1917ad47bb0dbb38aa5c9fbbbfb2/cpp/src/arrow/c/bridge.h#L126-L128)
 is destroyed, the backing data automatically has its `release` pointer called. 
Just like, when a natively-allocated C++ Array is destroyed, the data backing 
its buffers is [automatically 
dellocated](https://github.com/apache/arrow/blob/91bf1c9c170c1917ad47bb0dbb38aa5c9fbbbfb2/cpp/src/arrow/memory_pool.cc#L844-L855).
   
   From the looks of it, but I may be misreading, this PR currently doesn't 
ensure this equivalence between imported arrays and natively-allocated arrays.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to