Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bindings/swift): add Swift binding #2470

Merged
merged 5 commits into from
Jun 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions bindings/swift/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc

/include
/lib
50 changes: 50 additions & 0 deletions bindings/swift/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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.

C_BINDING_SRC_DIR=../c
ROOT_DIR=../..

INCLUDE_DIR=./include
LIB_DIR=./lib
DIRS=$(INCLUDE_DIR) $(LIB_DIR)

.PHONY: all
all: build-swift

.PHONY: build-c
build-c: $(DIRS)
cd $(C_BINDING_SRC_DIR)
cargo build --release --manifest-path $(C_BINDING_SRC_DIR)/Cargo.toml
cp $(C_BINDING_SRC_DIR)/include/* $(INCLUDE_DIR)
cp $(ROOT_DIR)/target/release/libopendal_c.a $(LIB_DIR)

.PHONY: build-swift
build-swift: build-c
swift build

.PHONY: test
test: build-c
swift test

$(DIRS):
mkdir $@

.PHONY: clean
clean:
cargo clean
rm -rf $(INCLUDE_DIR)
rm -rf $(LIB_DIR)
42 changes: 42 additions & 0 deletions bindings/swift/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// swift-tools-version: 5.7

// 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 PackageDescription

let package = Package(
name: "OpenDAL",
products: [
.library(
name: "OpenDAL",
targets: ["OpenDAL"]),
],
targets: [
.systemLibrary(name: "COpenDAL"),
.target(
name: "OpenDAL",
dependencies: ["COpenDAL"],
linkerSettings: [
.unsafeFlags(["-L./lib"]),
.linkedLibrary("opendal_c"),
]),
.testTarget(
name: "OpenDALTests",
dependencies: ["OpenDAL"]),
]
)
64 changes: 64 additions & 0 deletions bindings/swift/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# OpenDAL Swift Binding

## Using the Package

### Build C Dependencies

The Swift binding depends on the C binding to OpenDAL. Before using this package, you need to build the C library first:

```
cd bindings/swift
make build-c
```

To check whether the package is ready to use, simply run the test:

```
make test
```

### Add Dependency to Your Project

The package manifest is not located at the root directory of its repository. To use it, add the path of this package to the `Package.swift` manifest of your project:

```swift
// swift-tools-version:5.7
import PackageDescription

let package = Package(
name: "MyTool",
dependencies: [
.package(path: "/path/to/opendal/bindings/swift/OpenDAL"),
Xuanwo marked this conversation as resolved.
Show resolved Hide resolved
],
targets: [
.target(name: "MyTool", dependencies: [
.product(name: "OpenDAL", package: "OpenDAL"),
]),
]
)
```

## Example

The demo below shows how to write a key to the memory storage, and read it back:

```swift
import OpenDAL

// Create an operator with `memory` backend.
let op = try Operator(scheme: "memory")

// Write some data into path `/demo`.
let someData = Data([1, 2, 3, 4])
try op.blockingWrite(someData, to: "/demo")

// Read the data back.
let readData = try op.blockingRead("/demo")

// You can use the read data here.
print(readData!)
```

## License

[Apache v2.0](https://www.apache.org/licenses/LICENSE-2.0)
23 changes: 23 additions & 0 deletions bindings/swift/Sources/COpenDAL/module.modulemap
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// 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.

module COpenDAL [system] {
Xuanwo marked this conversation as resolved.
Show resolved Hide resolved
header "../../include/opendal.h"
link "opendal_c"

export *
}
39 changes: 39 additions & 0 deletions bindings/swift/Sources/OpenDAL/Data+OpenDAL.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 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 COpenDAL

extension Data {
Xuanwo marked this conversation as resolved.
Show resolved Hide resolved
/// Creates a new data by managing `opendal_bytes` as its
/// underlying buffer.
///
/// This can be used to read data from Rust with zero-copying.
/// The underlying buffer will be freed when the data gets
/// deallocated.
init?(openDALBytes: UnsafeMutablePointer<opendal_bytes>) {
guard let address = UnsafeRawPointer(openDALBytes.pointee.data) else {
return nil
}
let length = Int(openDALBytes.pointee.len)
self.init(bytesNoCopy: .init(mutating: address),
count: length,
deallocator: .custom({ _, _ in
opendal_bytes_free(openDALBytes)
}))
}
}
89 changes: 89 additions & 0 deletions bindings/swift/Sources/OpenDAL/Operator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// 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 COpenDAL

public enum OperatorError: Error {
case failedToBuild
case operationError(UInt32)
}

/// A type used to access almost all OpenDAL APIs.
public class Operator {
var nativeOp: opendal_operator_ptr

deinit {
withUnsafePointer(to: &nativeOp) { nativeOpPtr in
opendal_operator_free(nativeOpPtr)
}
}

/// Creates an operator with the given options.
///
/// - Parameter options: The option map for creating the operator.
/// - Throws: `OperatorError` value that indicates an error if failed.
public init(scheme: String, options: [String : String] = [:]) throws {
var nativeOptions = opendal_operator_options_new()
nativeOp = withUnsafeMutablePointer(to: &nativeOptions) { nativeOptionsPtr in
defer {
opendal_operator_options_free(nativeOptionsPtr)
}

for option in options {
opendal_operator_options_set(nativeOptionsPtr, option.key, option.value)
}

return opendal_operator_new(scheme, nativeOptionsPtr)
}

guard nativeOp.ptr != nil else {
throw OperatorError.failedToBuild
}
}

/// Blockingly write the data to a given path.
///
/// - Parameter data: The content to be written.
/// - Parameter path: The destination path for writing the data.
/// - Throws: `OperatorError` value that indicates an error if failed to write.
public func blockingWrite(_ data: Data, to path: String) throws {
Xuanwo marked this conversation as resolved.
Show resolved Hide resolved
let code = data.withUnsafeBytes { dataPointer in
let address = dataPointer.baseAddress!.assumingMemoryBound(to: UInt8.self)
let bytes = opendal_bytes(data: address, len: UInt(dataPointer.count))
return opendal_operator_blocking_write(nativeOp, path, bytes)
}

guard code == OPENDAL_OK else {
throw OperatorError.operationError(code.rawValue)
}
}

/// Blockingly read the data from a given path.
///
/// - Parameter path: Path of the data to read.
/// - Returns: `NativeData` object if the data exists.
/// - Throws: `OperatorError` value that indicates an error if failed to read.
public func blockingRead(_ path: String) throws -> Data? {
let result = opendal_operator_blocking_read(nativeOp, path)
guard result.code == OPENDAL_OK else {
throw OperatorError.operationError(result.code.rawValue)
}

return .init(openDALBytes: result.data)
}
}
41 changes: 41 additions & 0 deletions bindings/swift/Tests/OpenDALTests/OpenDALTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// 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 XCTest
@testable import OpenDAL

final class OpenDALTests: XCTestCase {
func testSimple() throws {
let op = try Operator(scheme: "memory", options: [
"root": "/myroot"
])

let testContents = Data([1, 2, 3, 4])
try op.blockingWrite(testContents, to: "test")

guard let readContents = try op.blockingRead("test") else {
XCTFail("Expected a `Data`")
return
}

for (testByte, readByte) in zip(testContents, readContents) {
XCTAssertEqual(testByte, readByte)
}

XCTAssertThrowsError(try op.blockingRead("test_not_exists"))
}
}