This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 7d82742467 feat(bindings/swift): Add a blocking reader for
caller-owned buffers (#9408)
7d82742467 is described below
commit 7d82742467f7bc952ecabc5f57a8cd99294ad7ce
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 30 08:04:53 2026 +0800
feat(bindings/swift): Add a blocking reader for caller-owned buffers (#9408)
feat(bindings/swift): add blocking reader
---
.../OpenDAL/Sources/OpenDAL/BlockingReader.swift | 51 +++++++++++++++++++++
.../swift/OpenDAL/Sources/OpenDAL/Operator.swift | 17 +++++++
.../OpenDAL/Tests/OpenDALTests/OpenDALTests.swift | 53 ++++++++++++++++++++++
bindings/swift/README.md | 19 ++++++++
4 files changed, 140 insertions(+)
diff --git a/bindings/swift/OpenDAL/Sources/OpenDAL/BlockingReader.swift
b/bindings/swift/OpenDAL/Sources/OpenDAL/BlockingReader.swift
new file mode 100644
index 0000000000..e8aff70548
--- /dev/null
+++ b/bindings/swift/OpenDAL/Sources/OpenDAL/BlockingReader.swift
@@ -0,0 +1,51 @@
+// 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 COpenDAL
+
+/// A sequential reader that can outlive the operator that opened it.
+/// Call `read(into:)` serially. The reader releases its resources on
deinitialization.
+public final class BlockingReader {
+ private let nativeReader: UnsafeMutablePointer<opendal_reader>
+
+ init(consuming reader: UnsafeMutablePointer<opendal_reader>) {
+ self.nativeReader = reader
+ }
+
+ deinit {
+ opendal_reader_free(nativeReader)
+ }
+
+ /// Reads from the current position into a contiguous buffer of
initialized,
+ /// writable bytes. The reader borrows the buffer for the duration of this
call.
+ ///
+ /// Returns the number of bytes written, which can be less than the
buffer's
+ /// count. With a nonempty buffer, zero indicates end of file. An empty
buffer
+ /// returns zero immediately. Throws `OperatorError` if reading fails.
+ /// The underlying service can fetch more data than fits in the buffer.
+ public func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int
{
+ guard !buffer.isEmpty else { return 0 }
+
+ // Pass the address to C as bytes and preserve the caller's memory
binding.
+ let bytes =
UnsafeMutablePointer<UInt8>(OpaquePointer(buffer.baseAddress))
+ var count: UInt = 0
+ if let err = opendal_reader_read(nativeReader, bytes,
UInt(buffer.count), &count) {
+ throw OperatorError(consuming: err)
+ }
+ return Int(count)
+ }
+}
diff --git a/bindings/swift/OpenDAL/Sources/OpenDAL/Operator.swift
b/bindings/swift/OpenDAL/Sources/OpenDAL/Operator.swift
index ccdd432c51..b9fb9efd1f 100644
--- a/bindings/swift/OpenDAL/Sources/OpenDAL/Operator.swift
+++ b/bindings/swift/OpenDAL/Sources/OpenDAL/Operator.swift
@@ -100,6 +100,23 @@ public class Operator {
return Data(openDALBytes: data)
}
+ /// Opens a sequential reader for a file. The service must support read.
+ /// Throws `OperatorError` if opening fails or the path contains a NUL
+ /// character (U+0000). A missing file can surface as an error on the
+ /// first nonempty read.
+ public func blockingReader(_ path: String) throws -> BlockingReader {
+ try Self.validatePath(path)
+
+ var result: UnsafeMutablePointer<opendal_reader>? = nil
+ if let err = opendal_operator_reader(nativeOp, path, &result) {
+ throw OperatorError(consuming: err)
+ }
+ guard let reader = result else {
+ throw OperatorError(code: OPENDAL_UNEXPECTED, message: "Open
returned no reader.")
+ }
+ return BlockingReader(consuming: reader)
+ }
+
/// Returns metadata for an existing path.
/// Use a trailing slash for a named directory. The service must support
stat.
/// Throws `OperatorError` on failure, including a missing path or a path
diff --git a/bindings/swift/OpenDAL/Tests/OpenDALTests/OpenDALTests.swift
b/bindings/swift/OpenDAL/Tests/OpenDALTests/OpenDALTests.swift
index 8ab875e18e..43e7db721d 100644
--- a/bindings/swift/OpenDAL/Tests/OpenDALTests/OpenDALTests.swift
+++ b/bindings/swift/OpenDAL/Tests/OpenDALTests/OpenDALTests.swift
@@ -66,6 +66,59 @@ final class OpenDALTests: XCTestCase {
}
}
+ func testBlockingReaderReadsSequentiallyAfterOperatorRelease() throws {
+ weak var operatorReference: Operator?
+ let reader: BlockingReader
+ do {
+ let op = try Operator(scheme: "memory")
+ operatorReference = op
+ var data = Data([1, 2])
+ try op.blockingWrite(&data, to: "file")
+ reader = try op.blockingReader("file")
+ }
+ XCTAssertNil(operatorReference)
+
+ var byte: UInt8 = 0
+ try withUnsafeMutableBytes(of: &byte) { buffer in
+ XCTAssertEqual(try reader.read(into: buffer), 1)
+ XCTAssertEqual(buffer[0], 1)
+ XCTAssertEqual(try reader.read(into: buffer), 1)
+ XCTAssertEqual(buffer[0], 2)
+ XCTAssertEqual(try reader.read(into: buffer), 0)
+ XCTAssertEqual(try reader.read(into: buffer), 0)
+ }
+ }
+
+ func testBlockingReaderThrowsOnFirstNonemptyReadOfMissingFile() throws {
+ let op = try Operator(scheme: "memory")
+ let reader = try op.blockingReader("missing")
+ XCTAssertEqual(try reader.read(into: .init(start: nil, count: 0)), 0)
+
+ var byte: UInt8 = 0
+ try withUnsafeMutableBytes(of: &byte) { buffer in
+ XCTAssertThrowsError(try reader.read(into: buffer)) { error in
+ XCTAssertEqual((error as? OperatorError)?.code,
OPENDAL_NOT_FOUND.rawValue)
+ }
+ }
+ }
+
+ func testBlockingReaderRejectsInvalidPaths() throws {
+ let op = try Operator(scheme: "memory")
+
+ XCTAssertThrowsError(try op.blockingReader("directory/")) { error in
+ XCTAssertEqual((error as? OperatorError)?.code,
OPENDAL_IS_A_DIRECTORY.rawValue)
+ }
+ XCTAssertThrowsError(try op.blockingReader("file\0suffix")) { error in
+ guard let opendalError = error as? OperatorError else {
+ XCTFail("expected OperatorError, got \(error)")
+ return
+ }
+ XCTAssertEqual(opendalError.code, OPENDAL_UNEXPECTED.rawValue)
+ let message = String(decoding: opendalError.message, as: UTF8.self)
+ XCTAssertTrue(message.contains("U+0000"), "unexpected error
message: \(message)")
+ }
+ }
+
func testBlockingStatReturnsFileAndDirectoryMetadata() throws {
let op = try Operator(scheme: "memory")
let path = "文档/café-🦀"
diff --git a/bindings/swift/README.md b/bindings/swift/README.md
index 8a67d586a9..ee6b5a5c69 100644
--- a/bindings/swift/README.md
+++ b/bindings/swift/README.md
@@ -106,6 +106,25 @@ See the [user
guide](https://opendal.apache.org/docs/bindings/swift) for more
examples, and [Services](https://opendal.apache.org/services) for the full list
of backends and their configuration keys.
+## Read into a reusable buffer
+
+Use `blockingReader` to process a file one chunk at a time. Process only the
+bytes returned by each read and stop when a read into a nonempty buffer returns
+zero.
+
+```swift
+let reader = try op.blockingReader("/demo")
+var buffer = [UInt8](repeating: 0, count: 8192)
+while true {
+ let count = try buffer.withUnsafeMutableBytes { try reader.read(into: $0) }
+ if count == 0 { break }
+ print(buffer.prefix(count))
+}
+```
+
+Opening and reading can both throw `OperatorError`. Release the reader when
+you finish or stop early.
+
## List entries
Use `blockingLister` to open a nonrecursive listing. Use a trailing slash