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 fdca6ea091 feat(bindings/c,go): generate ListOptions from core (#9335)
fdca6ea091 is described below
commit fdca6ea0910a0d2f526cad932330fe62f7d49334
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:11:49 2026 +0530
feat(bindings/c,go): generate ListOptions from core (#9335)
* feat(bindings/c,go): generate ListOptions from core
Render opendal_list_options, its functions, and its conversion to core
(bindings/c/src/options.rs), and the Go ListWith* options that fill it
(bindings/go/options.go), from core ListOptions with `generate -l c`.
A table in dev/src/generate/c/options.rs records the released member
order and C representation, so the C layout, functions, and Go
signatures stay unchanged. glob, the only core field it does not list,
keeps its core default. The other option structs stay hand-written.
Docs now come from the core doc comments, with rustdoc links rewritten
as code spans, plus how C and Go encode an unset option, so opendal.h
and the Go docs change in comments only.
Move opendal_string_free and opendal_bytes from types.rs to buffer.rs,
because cbindgen writes functions in module order.
Pin the released list layout and prototypes in tests/list.cpp and the
Go option signatures in options_test.go.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/c,go): name C and Go items in ListOptions docs
- Render code spans that name a released list option or a core
capability with their binding names: C keeps the member name and
writes `opendal_capability.list_with_start_after`; Go writes
`ListWithStartAfter` and `Capability.ListWithStartAfter`.
- Test that every kind change of a released field fails generation,
including `start_after` becoming a `bool`.
- Pin exactly five `opendal_list_options` members in tests/list.cpp,
so a member that fits into the trailing padding still fails.
- Pin the exact set of exported Go `ListWith*` options, list a memory
operator with each option through the live C library, and check that
a non-zero limit reaches the C setter.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/c): make the list options conversion unsafe
The generated `From<&opendal_list_options>` let safe Rust read
`start_after` through a raw pointer that a shared reference cannot
vouch for. Generate `opendal_list_options::to_core` as a
`pub(crate) unsafe fn` whose `# Safety` section requires a non-null
`start_after` to be a readable, nul-terminated C string for the
duration of the copy, and call it from
`opendal_operator_list_with_cancel` under that caller contract.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/c/include/opendal.h | 74 ++--
bindings/c/src/buffer.rs | 164 +++++++++
bindings/c/src/cancel.rs | 2 +-
bindings/c/src/error.rs | 2 +-
bindings/c/src/lib.rs | 10 +-
bindings/c/src/operator.rs | 25 +-
bindings/c/src/options.rs | 244 ++++++++++++++
bindings/c/src/types.rs | 327 ++----------------
bindings/c/tests/list.cpp | 58 ++++
bindings/go/lister.go | 110 +-----
bindings/go/options.go | 157 +++++++++
bindings/go/options_test.go | 163 +++++++++
dev/src/generate/c.rs | 5 +-
dev/src/generate/c/options.rs | 710 +++++++++++++++++++++++++++++++++++++++
dev/src/generate/c/options_go.j2 | 105 ++++++
dev/src/generate/c/options_rs.j2 | 141 ++++++++
16 files changed, 1853 insertions(+), 444 deletions(-)
diff --git a/bindings/c/include/opendal.h b/bindings/c/include/opendal.h
index 2151ab4134..899be77ff1 100644
--- a/bindings/c/include/opendal.h
+++ b/bindings/c/include/opendal.h
@@ -672,10 +672,16 @@ typedef struct opendal_stat_options {
} opendal_stat_options;
/**
- * \brief The options for the list operation.
+ * \brief Options for list operations.
+ *
+ * # Groups
+ * - Traversal: `recursive`.
+ * - Pagination: `limit`, `start_after`.
+ * - Versioning: `versions`, `deleted`.
+ *
+ * The operation fails with `crate::ErrorKind::Unsupported` when an option
+ * requires a capability that the operator lacks.
*
- * This struct carries the options for the list operation, including whether to
- * list recursively, an optional result limit, and an optional start-after key.
* Use `opendal_list_options_new()` to construct and
`opendal_list_options_free()` to free.
*
* @see opendal_operator_list_with
@@ -689,23 +695,36 @@ typedef struct opendal_stat_options {
*/
typedef struct opendal_list_options {
/**
- * Whether to list recursively under the prefix; default false.
+ * Whether to list recursively under the prefix; default `false`.
+ *
+ * Setting this option to `true` requires the operator's effective
+ * `opendal_capability.list_with_recursive` capability.
*/
bool recursive;
/**
- * Optional hint for maximum results per request; 0 means unset.
+ * Maximum results per request (backend hint) to control memory and
throttling.
+ *
+ * `0` means unset.
*/
uintptr_t limit;
/**
- * Optional key to start listing from; NULL means unset.
+ * Start listing after this key, excluding the key itself.
+ *
+ * Setting this requires `opendal_capability.list_with_start_after`.
+ *
+ * NULL means unset.
*/
char *start_after;
/**
- * Include object versions when supported by version-aware backends; default
false.
+ * Include object versions; default `false`.
+ *
+ * Requires `opendal_capability.list_with_versions`.
*/
bool versions;
/**
- * Include delete markers when supported by version-aware backends; default
false.
+ * Include delete markers; default `false`.
+ *
+ * Requires `opendal_capability.list_with_deleted`.
*/
bool deleted;
} opendal_list_options;
@@ -2914,45 +2933,62 @@ void opendal_bytes_free(struct opendal_bytes *ptr);
struct opendal_list_options *opendal_list_options_new(void);
/**
- * \brief Set the recursive option.
+ * \brief Set `recursive`.
+ *
+ * Whether to list recursively under the prefix; default `false`.
+ *
+ * Setting this option to `true` requires the operator's effective
+ * `opendal_capability.list_with_recursive` capability.
*
* @param opts The opendal_list_options to modify.
- * @param recursive Whether to list recursively.
+ * @param recursive The value to set.
*/
void opendal_list_options_set_recursive(struct opendal_list_options *opts,
bool recursive);
/**
- * \brief Set the limit option.
+ * \brief Set `limit`.
+ *
+ * Maximum results per request (backend hint) to control memory and throttling.
*
* @param opts The opendal_list_options to modify.
- * @param limit Maximum number of results per request; 0 means unset.
+ * @param limit The value to set; `0` unsets it.
*/
void opendal_list_options_set_limit(struct opendal_list_options *opts,
uintptr_t limit);
/**
- * \brief Set the start_after option.
+ * \brief Set `start_after`.
+ *
+ * Start listing after this key, excluding the key itself.
*
- * Passes the specified key to the underlying service to start listing from.
+ * Setting this requires `opendal_capability.list_with_start_after`.
*
* @param opts The opendal_list_options to modify.
- * @param start_after The key to start listing from; NULL to unset.
+ * @param start_after The string to copy; NULL unsets it.
*/
void opendal_list_options_set_start_after(struct opendal_list_options *opts,
const char *start_after);
/**
- * \brief Set the versions option.
+ * \brief Set `versions`.
+ *
+ * Include object versions; default `false`.
+ *
+ * Requires `opendal_capability.list_with_versions`.
*
* @param opts The opendal_list_options to modify.
- * @param versions Whether to include object versions.
+ * @param versions The value to set.
*/
void opendal_list_options_set_versions(struct opendal_list_options *opts, bool
versions);
/**
- * \brief Set the deleted option.
+ * \brief Set `deleted`.
+ *
+ * Include delete markers; default `false`.
+ *
+ * Requires `opendal_capability.list_with_deleted`.
*
* @param opts The opendal_list_options to modify.
- * @param deleted Whether to include delete markers.
+ * @param deleted The value to set.
*/
void opendal_list_options_set_deleted(struct opendal_list_options *opts, bool
deleted);
diff --git a/bindings/c/src/buffer.rs b/bindings/c/src/buffer.rs
new file mode 100644
index 0000000000..02cdbabbdb
--- /dev/null
+++ b/bindings/c/src/buffer.rs
@@ -0,0 +1,164 @@
+// 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::ffi::CString;
+use std::os::raw::c_char;
+
+use opendal::{Buffer, Error, ErrorKind};
+
+/// \brief Frees a heap-allocated string returned by OpenDAL C APIs.
+///
+/// \note Only pass pointers returned from OpenDAL APIs that transfer string
ownership.
+#[no_mangle]
+pub unsafe extern "C" fn opendal_string_free(ptr: *mut c_char) {
+ if !ptr.is_null() {
+ drop(unsafe { CString::from_raw(ptr) });
+ }
+}
+
+/// \brief opendal_bytes carries raw-bytes with its length
+///
+/// The opendal_bytes type is a C-compatible substitute for Vec type in Rust.
+/// For buffers returned by OpenDAL C APIs, call opendal_bytes_free() to free
+/// the heap memory and avoid memory leaks. If you reuse an `opendal_bytes`
+/// output variable across multiple read calls, call `opendal_bytes_free()`
+/// on the previous result before passing it again as an output parameter.
+/// For caller-owned input buffers passed to OpenDAL C APIs, the caller keeps
+/// ownership and must not call opendal_bytes_free() on them.
+///
+/// @see opendal_bytes_free
+#[repr(C)]
+pub struct opendal_bytes {
+ /// Pointing to the byte array on heap
+ pub data: *mut u8,
+ /// The length of the byte array
+ pub len: usize,
+ /// The capacity of the byte array
+ pub capacity: usize,
+}
+
+impl opendal_bytes {
+ pub(crate) fn empty() -> Self {
+ Self {
+ data: std::ptr::null_mut(),
+ len: 0,
+ capacity: 0,
+ }
+ }
+
+ /// Construct a [`opendal_bytes`] from the Rust [`Vec`] of bytes
+ pub(crate) fn new(b: Buffer) -> Self {
+ if b.is_empty() {
+ return Self::empty();
+ }
+
+ let mut b = std::mem::ManuallyDrop::new(b.to_vec());
+ Self {
+ data: b.as_mut_ptr(),
+ len: b.len(),
+ capacity: b.capacity(),
+ }
+ }
+
+ /// \brief Frees the heap memory used by the opendal_bytes
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_bytes_free(ptr: *mut opendal_bytes) {
+ unsafe {
+ if !ptr.is_null() {
+ let bs = &mut *ptr;
+ if !bs.data.is_null() {
+ drop(Vec::from_raw_parts(bs.data, bs.len, bs.capacity));
+ }
+ bs.data = std::ptr::null_mut();
+ bs.len = 0;
+ bs.capacity = 0;
+ }
+ }
+ }
+
+ pub(crate) fn to_buffer(&self) -> opendal::Result<Buffer> {
+ if self.len == 0 {
+ if self.data.is_null() {
+ return Ok(Buffer::new());
+ }
+
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "empty opendal_bytes must have null data",
+ ));
+ }
+
+ if self.data.is_null() {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "non-empty opendal_bytes has null data",
+ ));
+ }
+
+ let slice = unsafe { std::slice::from_raw_parts(self.data, self.len) };
+ Ok(Buffer::from(bytes::Bytes::copy_from_slice(slice)))
+ }
+}
+
+impl Drop for opendal_bytes {
+ fn drop(&mut self) {
+ unsafe {
+ // Safety: the pointer is always valid
+ Self::opendal_bytes_free(self);
+ }
+ }
+}
+
+#[cfg(test)]
+mod bytes_tests {
+ use super::*;
+
+ #[test]
+ fn test_empty_buffer_has_null_data() {
+ let mut bytes = opendal_bytes::new(Buffer::new());
+
+ assert!(bytes.data.is_null());
+ assert_eq!(bytes.len, 0);
+ assert_eq!(bytes.capacity, 0);
+
+ let buffer = bytes.to_buffer().expect("empty bytes should convert");
+ assert!(buffer.is_empty());
+
+ unsafe { opendal_bytes::opendal_bytes_free(&mut bytes) };
+ assert!(bytes.data.is_null());
+ assert_eq!(bytes.len, 0);
+ assert_eq!(bytes.capacity, 0);
+ }
+
+ #[test]
+ fn test_non_empty_buffer_round_trips() {
+ let mut bytes = opendal_bytes::new(Buffer::from("hello"));
+
+ assert!(!bytes.data.is_null());
+ assert_eq!(bytes.len, 5);
+ assert_eq!(
+ unsafe { std::slice::from_raw_parts(bytes.data, bytes.len) },
+ b"hello"
+ );
+ assert_eq!(bytes.to_buffer().unwrap().to_vec(), b"hello");
+
+ unsafe { opendal_bytes::opendal_bytes_free(&mut bytes) };
+ assert!(bytes.data.is_null());
+ assert_eq!(bytes.len, 0);
+ assert_eq!(bytes.capacity, 0);
+ }
+}
diff --git a/bindings/c/src/cancel.rs b/bindings/c/src/cancel.rs
index 2c41a4a7e8..0913e02495 100644
--- a/bindings/c/src/cancel.rs
+++ b/bindings/c/src/cancel.rs
@@ -192,6 +192,7 @@ mod tests {
use core::raw::{self, oio};
use super::*;
+ use crate::buffer::opendal_bytes;
use crate::copier::opendal_copier;
use crate::deleter::opendal_deleter;
use crate::error::{opendal_code, opendal_error};
@@ -201,7 +202,6 @@ mod tests {
opendal_operator_stat_with_cancel,
};
use crate::reader::opendal_reader;
- use crate::types::opendal_bytes;
#[derive(Debug)]
struct Gate {
diff --git a/bindings/c/src/error.rs b/bindings/c/src/error.rs
index e8e37a2cdd..722034153c 100644
--- a/bindings/c/src/error.rs
+++ b/bindings/c/src/error.rs
@@ -18,7 +18,7 @@
use ::opendal as core;
use opendal::Buffer;
-use crate::types::opendal_bytes;
+use crate::buffer::opendal_bytes;
/// \brief The error code for all opendal APIs in C binding.
/// \todo The error handling is not complete, the error with error message
will be
diff --git a/bindings/c/src/lib.rs b/bindings/c/src/lib.rs
index 77ac6cc9b9..723387dc37 100644
--- a/bindings/c/src/lib.rs
+++ b/bindings/c/src/lib.rs
@@ -66,11 +66,17 @@ mod presign;
pub use presign::opendal_http_header_pair;
pub use presign::opendal_presigned_request;
+// cbindgen writes functions in module order, so `buffer`, the generated
+// `options`, and `types` stay in this order to keep the order of opendal.h.
+mod buffer;
+pub use buffer::opendal_bytes;
+
+mod options;
+pub use options::opendal_list_options;
+
mod types;
-pub use types::opendal_bytes;
pub use types::opendal_copy_options;
pub use types::opendal_delete_options;
-pub use types::opendal_list_options;
pub use types::opendal_operator_options;
pub use types::opendal_read_options;
pub use types::opendal_reader_options;
diff --git a/bindings/c/src/operator.rs b/bindings/c/src/operator.rs
index a2f35db4f0..7f09cbaa1f 100644
--- a/bindings/c/src/operator.rs
+++ b/bindings/c/src/operator.rs
@@ -1270,26 +1270,11 @@ pub unsafe extern "C" fn
opendal_operator_list_with_cancel(
let list_opts = if opts.is_null() {
core::options::ListOptions::default()
} else {
- let o = &*opts;
- let limit = if o.limit == 0 { None } else { Some(o.limit) };
- let start_after = if o.start_after.is_null() {
- None
- } else {
- Some(
- std::ffi::CStr::from_ptr(o.start_after)
- .to_str()
- .expect("malformed start_after")
- .to_owned(),
- )
- };
- core::options::ListOptions {
- recursive: o.recursive,
- limit,
- start_after,
- versions: o.versions,
- deleted: o.deleted,
- glob: None,
- }
+ // SAFETY: `opts` is non-null, and the caller of this function passes
+ // options whose non-null `start_after` is a readable, nul-terminated C
+ // string, such as the copy that `opendal_list_options_set_start_after`
+ // makes.
+ (*opts).to_core()
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
match block_on_cancellable(
diff --git a/bindings/c/src/options.rs b/bindings/c/src/options.rs
new file mode 100644
index 0000000000..c4a73e24df
--- /dev/null
+++ b/bindings/c/src/options.rs
@@ -0,0 +1,244 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/c.rs.
+
+use std::ffi::{CStr, CString};
+use std::os::raw::c_char;
+
+use opendal::options;
+
+/// \brief Options for list operations.
+///
+/// # Groups
+/// - Traversal: `recursive`.
+/// - Pagination: `limit`, `start_after`.
+/// - Versioning: `versions`, `deleted`.
+///
+/// The operation fails with `crate::ErrorKind::Unsupported` when an option
+/// requires a capability that the operator lacks.
+///
+/// Use `opendal_list_options_new()` to construct and
`opendal_list_options_free()` to free.
+///
+/// @see opendal_operator_list_with
+/// @see opendal_list_options_new
+/// @see opendal_list_options_free
+/// @see opendal_list_options_set_recursive
+/// @see opendal_list_options_set_limit
+/// @see opendal_list_options_set_start_after
+/// @see opendal_list_options_set_versions
+/// @see opendal_list_options_set_deleted
+#[repr(C)]
+pub struct opendal_list_options {
+ /// Whether to list recursively under the prefix; default `false`.
+ ///
+ /// Setting this option to `true` requires the operator's effective
+ /// `opendal_capability.list_with_recursive` capability.
+ pub recursive: bool,
+ /// Maximum results per request (backend hint) to control memory and
throttling.
+ ///
+ /// `0` means unset.
+ pub limit: usize,
+ /// Start listing after this key, excluding the key itself.
+ ///
+ /// Setting this requires `opendal_capability.list_with_start_after`.
+ ///
+ /// NULL means unset.
+ pub start_after: *mut c_char,
+ /// Include object versions; default `false`.
+ ///
+ /// Requires `opendal_capability.list_with_versions`.
+ pub versions: bool,
+ /// Include delete markers; default `false`.
+ ///
+ /// Requires `opendal_capability.list_with_deleted`.
+ pub deleted: bool,
+}
+
+impl opendal_list_options {
+ /// \brief Construct a heap-allocated opendal_list_options with default
values.
+ ///
+ /// @return A new opendal_list_options with all options set to their
defaults.
+ ///
+ /// @see opendal_list_options_free
+ #[no_mangle]
+ pub extern "C" fn opendal_list_options_new() -> *mut Self {
+ Box::into_raw(Box::new(Self::default()))
+ }
+
+ /// \brief Set `recursive`.
+ ///
+ /// Whether to list recursively under the prefix; default `false`.
+ ///
+ /// Setting this option to `true` requires the operator's effective
+ /// `opendal_capability.list_with_recursive` capability.
+ ///
+ /// @param opts The opendal_list_options to modify.
+ /// @param recursive The value to set.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_set_recursive(
+ opts: *mut opendal_list_options,
+ recursive: bool,
+ ) {
+ if !opts.is_null() {
+ (*opts).recursive = recursive;
+ }
+ }
+
+ /// \brief Set `limit`.
+ ///
+ /// Maximum results per request (backend hint) to control memory and
throttling.
+ ///
+ /// @param opts The opendal_list_options to modify.
+ /// @param limit The value to set; `0` unsets it.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_set_limit(
+ opts: *mut opendal_list_options,
+ limit: usize,
+ ) {
+ if !opts.is_null() {
+ (*opts).limit = limit;
+ }
+ }
+
+ /// \brief Set `start_after`.
+ ///
+ /// Start listing after this key, excluding the key itself.
+ ///
+ /// Setting this requires `opendal_capability.list_with_start_after`.
+ ///
+ /// @param opts The opendal_list_options to modify.
+ /// @param start_after The string to copy; NULL unsets it.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_set_start_after(
+ opts: *mut opendal_list_options,
+ start_after: *const c_char,
+ ) {
+ if opts.is_null() {
+ return;
+ }
+ // Allocate before freeing the old value so self-aliasing or substring
+ // pointers into `opts->start_after` remain valid while reading.
+ let new_ptr = if start_after.is_null() {
+ std::ptr::null_mut()
+ } else {
+ let value = option_str(start_after, "start_after");
+ CString::new(value).unwrap().into_raw()
+ };
+ let old_ptr = std::mem::replace(&mut (*opts).start_after, new_ptr);
+ if !old_ptr.is_null() {
+ drop(CString::from_raw(old_ptr));
+ }
+ }
+
+ /// \brief Set `versions`.
+ ///
+ /// Include object versions; default `false`.
+ ///
+ /// Requires `opendal_capability.list_with_versions`.
+ ///
+ /// @param opts The opendal_list_options to modify.
+ /// @param versions The value to set.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_set_versions(
+ opts: *mut opendal_list_options,
+ versions: bool,
+ ) {
+ if !opts.is_null() {
+ (*opts).versions = versions;
+ }
+ }
+
+ /// \brief Set `deleted`.
+ ///
+ /// Include delete markers; default `false`.
+ ///
+ /// Requires `opendal_capability.list_with_deleted`.
+ ///
+ /// @param opts The opendal_list_options to modify.
+ /// @param deleted The value to set.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_set_deleted(
+ opts: *mut opendal_list_options,
+ deleted: bool,
+ ) {
+ if !opts.is_null() {
+ (*opts).deleted = deleted;
+ }
+ }
+
+ /// \brief Free the heap memory used by opendal_list_options.
+ ///
+ /// @param opts The opendal_list_options to free.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_list_options_free(opts: *mut
opendal_list_options) {
+ if !opts.is_null() {
+ let o = &mut *opts;
+ if !o.start_after.is_null() {
+ drop(CString::from_raw(o.start_after));
+ o.start_after = std::ptr::null_mut();
+ }
+ drop(Box::from_raw(opts));
+ }
+ }
+}
+
+impl Default for opendal_list_options {
+ fn default() -> Self {
+ Self {
+ recursive: false,
+ limit: 0,
+ start_after: std::ptr::null_mut(),
+ versions: false,
+ deleted: false,
+ }
+ }
+}
+
+impl opendal_list_options {
+ /// Copy these options into core `ListOptions`.
+ ///
+ /// # Safety
+ ///
+ /// * A non-null `start_after` must point to a readable, nul-terminated C
string
+ /// for the duration of the copy.
+ pub(crate) unsafe fn to_core(&self) -> options::ListOptions {
+ options::ListOptions {
+ limit: (self.limit != 0).then_some(self.limit),
+ start_after: unsafe { optional_string(self.start_after,
"start_after") },
+ recursive: self.recursive,
+ versions: self.versions,
+ deleted: self.deleted,
+ glob: None,
+ }
+ }
+}
+
+/// Read a C string passed for the option `name`.
+unsafe fn option_str<'a>(ptr: *const c_char, name: &str) -> &'a str {
+ CStr::from_ptr(ptr)
+ .to_str()
+ .unwrap_or_else(|err| panic!("malformed {name}: {err:?}"))
+}
+
+unsafe fn optional_string(ptr: *const c_char, name: &str) -> Option<String> {
+ if ptr.is_null() {
+ None
+ } else {
+ Some(option_str(ptr, name).to_owned())
+ }
+}
diff --git a/bindings/c/src/types.rs b/bindings/c/src/types.rs
index 62851524ad..d65c61e23b 100644
--- a/bindings/c/src/types.rs
+++ b/bindings/c/src/types.rs
@@ -22,250 +22,7 @@ use std::os::raw::c_char;
use opendal::options;
use opendal::raw::Timestamp;
use opendal::BytesRange;
-use opendal::{Buffer, Error, ErrorKind};
-
-/// \brief Frees a heap-allocated string returned by OpenDAL C APIs.
-///
-/// \note Only pass pointers returned from OpenDAL APIs that transfer string
ownership.
-#[no_mangle]
-pub unsafe extern "C" fn opendal_string_free(ptr: *mut c_char) {
- if !ptr.is_null() {
- drop(unsafe { CString::from_raw(ptr) });
- }
-}
-
-/// \brief opendal_bytes carries raw-bytes with its length
-///
-/// The opendal_bytes type is a C-compatible substitute for Vec type in Rust.
-/// For buffers returned by OpenDAL C APIs, call opendal_bytes_free() to free
-/// the heap memory and avoid memory leaks. If you reuse an `opendal_bytes`
-/// output variable across multiple read calls, call `opendal_bytes_free()`
-/// on the previous result before passing it again as an output parameter.
-/// For caller-owned input buffers passed to OpenDAL C APIs, the caller keeps
-/// ownership and must not call opendal_bytes_free() on them.
-///
-/// @see opendal_bytes_free
-#[repr(C)]
-pub struct opendal_bytes {
- /// Pointing to the byte array on heap
- pub data: *mut u8,
- /// The length of the byte array
- pub len: usize,
- /// The capacity of the byte array
- pub capacity: usize,
-}
-
-impl opendal_bytes {
- pub(crate) fn empty() -> Self {
- Self {
- data: std::ptr::null_mut(),
- len: 0,
- capacity: 0,
- }
- }
-
- /// Construct a [`opendal_bytes`] from the Rust [`Vec`] of bytes
- pub(crate) fn new(b: Buffer) -> Self {
- if b.is_empty() {
- return Self::empty();
- }
-
- let mut b = std::mem::ManuallyDrop::new(b.to_vec());
- Self {
- data: b.as_mut_ptr(),
- len: b.len(),
- capacity: b.capacity(),
- }
- }
-
- /// \brief Frees the heap memory used by the opendal_bytes
- #[no_mangle]
- pub unsafe extern "C" fn opendal_bytes_free(ptr: *mut opendal_bytes) {
- unsafe {
- if !ptr.is_null() {
- let bs = &mut *ptr;
- if !bs.data.is_null() {
- drop(Vec::from_raw_parts(bs.data, bs.len, bs.capacity));
- }
- bs.data = std::ptr::null_mut();
- bs.len = 0;
- bs.capacity = 0;
- }
- }
- }
-
- pub(crate) fn to_buffer(&self) -> opendal::Result<Buffer> {
- if self.len == 0 {
- if self.data.is_null() {
- return Ok(Buffer::new());
- }
-
- return Err(Error::new(
- ErrorKind::Unexpected,
- "empty opendal_bytes must have null data",
- ));
- }
-
- if self.data.is_null() {
- return Err(Error::new(
- ErrorKind::Unexpected,
- "non-empty opendal_bytes has null data",
- ));
- }
-
- let slice = unsafe { std::slice::from_raw_parts(self.data, self.len) };
- Ok(Buffer::from(bytes::Bytes::copy_from_slice(slice)))
- }
-}
-
-/// \brief The options for the list operation.
-///
-/// This struct carries the options for the list operation, including whether
to
-/// list recursively, an optional result limit, and an optional start-after
key.
-/// Use `opendal_list_options_new()` to construct and
`opendal_list_options_free()` to free.
-///
-/// @see opendal_operator_list_with
-/// @see opendal_list_options_new
-/// @see opendal_list_options_free
-/// @see opendal_list_options_set_recursive
-/// @see opendal_list_options_set_limit
-/// @see opendal_list_options_set_start_after
-/// @see opendal_list_options_set_versions
-/// @see opendal_list_options_set_deleted
-#[repr(C)]
-pub struct opendal_list_options {
- /// Whether to list recursively under the prefix; default false.
- pub recursive: bool,
- /// Optional hint for maximum results per request; 0 means unset.
- pub limit: usize,
- /// Optional key to start listing from; NULL means unset.
- pub start_after: *mut c_char,
- /// Include object versions when supported by version-aware backends;
default false.
- pub versions: bool,
- /// Include delete markers when supported by version-aware backends;
default false.
- pub deleted: bool,
-}
-
-impl opendal_list_options {
- /// \brief Construct a heap-allocated opendal_list_options with default
values.
- ///
- /// @return A new opendal_list_options with all options set to their
defaults.
- ///
- /// @see opendal_list_options_free
- #[no_mangle]
- pub extern "C" fn opendal_list_options_new() -> *mut Self {
- Box::into_raw(Box::new(Self {
- recursive: false,
- limit: 0,
- start_after: std::ptr::null_mut(),
- versions: false,
- deleted: false,
- }))
- }
-
- /// \brief Set the recursive option.
- ///
- /// @param opts The opendal_list_options to modify.
- /// @param recursive Whether to list recursively.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_set_recursive(
- opts: *mut opendal_list_options,
- recursive: bool,
- ) {
- if !opts.is_null() {
- (*opts).recursive = recursive;
- }
- }
-
- /// \brief Set the limit option.
- ///
- /// @param opts The opendal_list_options to modify.
- /// @param limit Maximum number of results per request; 0 means unset.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_set_limit(
- opts: *mut opendal_list_options,
- limit: usize,
- ) {
- if !opts.is_null() {
- (*opts).limit = limit;
- }
- }
-
- /// \brief Set the start_after option.
- ///
- /// Passes the specified key to the underlying service to start listing
from.
- ///
- /// @param opts The opendal_list_options to modify.
- /// @param start_after The key to start listing from; NULL to unset.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_set_start_after(
- opts: *mut opendal_list_options,
- start_after: *const c_char,
- ) {
- if opts.is_null() {
- return;
- }
-
- // Allocate before freeing the old value so self-aliasing or substring
- // pointers into `opts->start_after` remain valid while reading.
- let new_ptr = if start_after.is_null() {
- std::ptr::null_mut()
- } else {
- let s = CStr::from_ptr(start_after)
- .to_str()
- .expect("malformed start_after");
- CString::new(s).unwrap().into_raw()
- };
- let o = &mut *opts;
- let old_ptr = std::mem::replace(&mut o.start_after, new_ptr);
- if !old_ptr.is_null() {
- drop(CString::from_raw(old_ptr));
- }
- }
-
- /// \brief Set the versions option.
- ///
- /// @param opts The opendal_list_options to modify.
- /// @param versions Whether to include object versions.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_set_versions(
- opts: *mut opendal_list_options,
- versions: bool,
- ) {
- if !opts.is_null() {
- (*opts).versions = versions;
- }
- }
-
- /// \brief Set the deleted option.
- ///
- /// @param opts The opendal_list_options to modify.
- /// @param deleted Whether to include delete markers.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_set_deleted(
- opts: *mut opendal_list_options,
- deleted: bool,
- ) {
- if !opts.is_null() {
- (*opts).deleted = deleted;
- }
- }
-
- /// \brief Free the heap memory used by opendal_list_options.
- ///
- /// @param opts The opendal_list_options to free.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_list_options_free(opts: *mut
opendal_list_options) {
- if !opts.is_null() {
- let o = &mut *opts;
- if !o.start_after.is_null() {
- drop(CString::from_raw(o.start_after));
- o.start_after = std::ptr::null_mut();
- }
- drop(Box::from_raw(opts));
- }
- }
-}
+use opendal::{Error, ErrorKind};
/// \brief The options for the delete operation.
///
@@ -1492,15 +1249,6 @@ impl From<&opendal_copy_options> for
options::CopyOptions {
}
}
-impl Drop for opendal_bytes {
- fn drop(&mut self) {
- unsafe {
- // Safety: the pointer is always valid
- Self::opendal_bytes_free(self);
- }
- }
-}
-
/// \brief The configuration for the initialization of opendal_operator.
///
/// \note This is also a heap-allocated struct, please free it after you use it
@@ -1595,46 +1343,6 @@ impl opendal_operator_options {
}
}
-#[cfg(test)]
-mod bytes_tests {
- use super::*;
-
- #[test]
- fn test_empty_buffer_has_null_data() {
- let mut bytes = opendal_bytes::new(Buffer::new());
-
- assert!(bytes.data.is_null());
- assert_eq!(bytes.len, 0);
- assert_eq!(bytes.capacity, 0);
-
- let buffer = bytes.to_buffer().expect("empty bytes should convert");
- assert!(buffer.is_empty());
-
- unsafe { opendal_bytes::opendal_bytes_free(&mut bytes) };
- assert!(bytes.data.is_null());
- assert_eq!(bytes.len, 0);
- assert_eq!(bytes.capacity, 0);
- }
-
- #[test]
- fn test_non_empty_buffer_round_trips() {
- let mut bytes = opendal_bytes::new(Buffer::from("hello"));
-
- assert!(!bytes.data.is_null());
- assert_eq!(bytes.len, 5);
- assert_eq!(
- unsafe { std::slice::from_raw_parts(bytes.data, bytes.len) },
- b"hello"
- );
- assert_eq!(bytes.to_buffer().unwrap().to_vec(), b"hello");
-
- unsafe { opendal_bytes::opendal_bytes_free(&mut bytes) };
- assert!(bytes.data.is_null());
- assert_eq!(bytes.len, 0);
- assert_eq!(bytes.capacity, 0);
- }
-}
-
#[cfg(test)]
mod option_tests {
use super::*;
@@ -1643,6 +1351,7 @@ mod option_tests {
opendal_operator, opendal_operator_read_with,
opendal_operator_reader_with,
opendal_operator_stat_with,
};
+ use crate::{opendal_bytes, opendal_list_options};
#[test]
fn test_list_options_set_start_after_self_alias_and_substring() {
@@ -1685,6 +1394,38 @@ mod option_tests {
}
}
+ #[test]
+ fn test_list_options_to_core() {
+ unsafe {
+ let opts = opendal_list_options::opendal_list_options_new();
+ assert_eq!((*opts).to_core(), options::ListOptions::default());
+
+ // A limit of 0 means unset, also when it is set explicitly.
+ opendal_list_options::opendal_list_options_set_limit(opts, 0);
+ assert_eq!((*opts).to_core().limit, None);
+
+ let start_after = CString::new("dir/a").unwrap();
+ opendal_list_options::opendal_list_options_set_recursive(opts,
true);
+ opendal_list_options::opendal_list_options_set_limit(opts, 2);
+ opendal_list_options::opendal_list_options_set_start_after(opts,
start_after.as_ptr());
+ opendal_list_options::opendal_list_options_set_versions(opts,
true);
+ opendal_list_options::opendal_list_options_set_deleted(opts, true);
+ assert_eq!(
+ (*opts).to_core(),
+ options::ListOptions {
+ recursive: true,
+ limit: Some(2),
+ start_after: Some("dir/a".to_string()),
+ versions: true,
+ deleted: true,
+ glob: None,
+ }
+ );
+
+ opendal_list_options::opendal_list_options_free(opts);
+ }
+ }
+
#[test]
fn test_delete_options_set_version_self_alias_and_substring() {
unsafe {
diff --git a/bindings/c/tests/list.cpp b/bindings/c/tests/list.cpp
index e66ae8ed81..dad7aa2f47 100644
--- a/bindings/c/tests/list.cpp
+++ b/bindings/c/tests/list.cpp
@@ -19,12 +19,70 @@
#include "common.hpp"
#include "gtest/gtest.h"
+#include <cstddef>
+#include <cstdint>
#include <cstring>
+#include <type_traits>
+#include <utility>
extern "C" {
#include "opendal.h"
}
+// opendal_list_options as released before options.rs was generated from core.
+// Its members are C ABI, so the generator must keep their order, types, and
+// offsets, and these functions with these exact prototypes.
+#define ASSERT_SIGNATURE(fn, type) \
+ static_assert(std::is_same<decltype(&fn), type>::value, #fn " changed its
signature")
+#define ASSERT_MEMBER_TYPE(member, type)
\
+ static_assert(std::is_same<decltype(opendal_list_options::member),
type>::value, \
+ "opendal_list_options." #member " changed its type")
+
+ASSERT_MEMBER_TYPE(recursive, bool);
+ASSERT_MEMBER_TYPE(limit, uintptr_t);
+ASSERT_MEMBER_TYPE(start_after, char*);
+ASSERT_MEMBER_TYPE(versions, bool);
+ASSERT_MEMBER_TYPE(deleted, bool);
+
+// Converts to any member type, so brace initialization with N of these
+// compiles only when the aggregate has at least N members.
+struct any_member {
+ template <typename T>
+ operator T() const;
+};
+
+template <typename T, typename... Args>
+auto brace_initializable(int) -> decltype(void(T { std::declval<Args>()... }),
std::true_type {});
+template <typename T, typename... Args>
+std::false_type brace_initializable(...);
+
+// Exactly the five members above: a sixth member, even one that fits into
+// the trailing padding, fails here.
+static_assert(decltype(brace_initializable<opendal_list_options,
+ any_member, any_member, any_member, any_member,
any_member>(0))::value,
+ "opendal_list_options lost a member");
+static_assert(!decltype(brace_initializable<opendal_list_options,
+ any_member, any_member, any_member, any_member, any_member,
any_member>(0))::value,
+ "opendal_list_options gained a member");
+
+#if UINTPTR_MAX == UINT64_MAX
+static_assert(sizeof(opendal_list_options) == 32, "opendal_list_options
changed its size");
+static_assert(offsetof(opendal_list_options, recursive) == 0, "recursive
moved");
+static_assert(offsetof(opendal_list_options, limit) == 8, "limit moved");
+static_assert(offsetof(opendal_list_options, start_after) == 16, "start_after
moved");
+static_assert(offsetof(opendal_list_options, versions) == 24, "versions
moved");
+static_assert(offsetof(opendal_list_options, deleted) == 25, "deleted moved");
+#endif
+
+ASSERT_SIGNATURE(opendal_list_options_new, struct opendal_list_options*
(*)(void));
+ASSERT_SIGNATURE(opendal_list_options_set_recursive, void (*)(struct
opendal_list_options*, bool));
+ASSERT_SIGNATURE(opendal_list_options_set_limit, void (*)(struct
opendal_list_options*, uintptr_t));
+ASSERT_SIGNATURE(opendal_list_options_set_start_after,
+ void (*)(struct opendal_list_options*, const char*));
+ASSERT_SIGNATURE(opendal_list_options_set_versions, void (*)(struct
opendal_list_options*, bool));
+ASSERT_SIGNATURE(opendal_list_options_set_deleted, void (*)(struct
opendal_list_options*, bool));
+ASSERT_SIGNATURE(opendal_list_options_free, void (*)(struct
opendal_list_options*));
+
class OpendalListTest : public ::testing::Test {
protected:
const opendal_operator* p;
diff --git a/bindings/go/lister.go b/bindings/go/lister.go
index 2120312382..100644414b 100644
--- a/bindings/go/lister.go
+++ b/bindings/go/lister.go
@@ -27,68 +27,6 @@ import (
// ErrListerClosed reports that a Lister is used after Close released it.
var ErrListerClosed = errors.New("opendal: lister is closed")
-// List returns a Lister to iterate over entries that start with the given
path in the parent directory.
-//
-// WithListFn is a functional option for the List operation.
-type WithListFn func(*listOptions)
-
-// ListWithRecursive sets the recursive flag for the list operation.
-//
-// When recursive is true, the list operation will descend into
sub-directories.
-func ListWithRecursive(recursive bool) WithListFn {
- return func(o *listOptions) {
- o.recursive = recursive
- }
-}
-
-// ListWithLimit sets the maximum number of results per request hint for the
list operation.
-//
-// This is a hint to the backend; the actual number of results may differ.
-// A value of 0 means no limit is set.
-func ListWithLimit(limit uint) WithListFn {
- return func(o *listOptions) {
- o.limit = limit
- }
-}
-
-// ListWithStartAfter sets the start-after key for the list operation.
-//
-// Passes the specified key to the underlying service to start listing from.
-func ListWithStartAfter(startAfter string) WithListFn {
- return func(o *listOptions) {
- o.startAfter = &startAfter
- }
-}
-
-// ListWithVersions sets the versions flag for the list operation.
-//
-// When versions is true, the list operation will include all object versions.
-// This option is only meaningful on version-aware backends.
-func ListWithVersions(versions bool) WithListFn {
- return func(o *listOptions) {
- o.versions = versions
- }
-}
-
-// ListWithDeleted sets the deleted flag for the list operation.
-//
-// When deleted is true, the list operation will include delete markers.
-// This option is only meaningful on version-aware backends.
-func ListWithDeleted(deleted bool) WithListFn {
- return func(o *listOptions) {
- o.deleted = deleted
- }
-}
-
-// listOptions holds the options for a list operation.
-type listOptions struct {
- recursive bool
- limit uint
- startAfter *string
- versions bool
- deleted bool
-}
-
// List returns a Lister to iterate over entries that start with the given
path.
//
// # Parameters
@@ -142,26 +80,11 @@ func (op *Operator) List(ctx context.Context, path string,
opts ...WithListFn) (
var cOpts *opendalListOptions
if len(opts) > 0 {
- o := &listOptions{}
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- opt(o)
+ cOpts, err = newOpendalListOptions(op.ctx,
parseListOptions(opts...))
+ if err != nil {
+ return nil, err
}
- cOpts = ffiListOptionsNew.symbol(op.ctx)()
defer ffiListOptionsFree.symbol(op.ctx)(cOpts)
- ffiListOptionsSetRecursive.symbol(op.ctx)(cOpts, o.recursive)
- if o.limit > 0 {
- ffiListOptionsSetLimit.symbol(op.ctx)(cOpts, o.limit)
- }
- if o.startAfter != nil {
- if err :=
ffiListOptionsSetStartAfter.symbol(op.ctx)(cOpts, *o.startAfter); err != nil {
- return nil, err
- }
- }
- ffiListOptionsSetVersions.symbol(op.ctx)(cOpts, o.versions)
- ffiListOptionsSetDeleted.symbol(op.ctx)(cOpts, o.deleted)
}
listerInner, err := withCancelTokenValue(op.ctx, ctx, func(token
*opendalCancelToken) (*opendalLister, error) {
return ffiOperatorListWith.symbol(op.ctx)(opInner, path, cOpts,
token)
@@ -389,33 +312,6 @@ func (e *Entry) Metadata() *Metadata {
return e.meta
}
-var ffiListOptionsNew = newDirectFFI[func()
*opendalListOptions]("opendal_list_options_new")
-
-var ffiListOptionsSetRecursive = newDirectFFI[func(opts *opendalListOptions,
recursive bool)]("opendal_list_options_set_recursive")
-
-var ffiListOptionsSetLimit = newDirectFFI[func(opts *opendalListOptions, limit
uint)]("opendal_list_options_set_limit")
-
-var ffiListOptionsSetStartAfter = newFFI(
- "opendal_list_options_set_start_after",
- func(_ context.Context, cFunc func(opts *opendalListOptions, startAfter
*byte)) func(opts *opendalListOptions, startAfter string) error {
- return func(opts *opendalListOptions, startAfter string) error {
- bytePtr, err := BytePtrFromString(startAfter)
- if err != nil {
- return err
- }
- cFunc(opts, bytePtr)
- runtime.KeepAlive(bytePtr)
- return nil
- }
- },
-)
-
-var ffiListOptionsSetVersions = newDirectFFI[func(opts *opendalListOptions,
versions bool)]("opendal_list_options_set_versions")
-
-var ffiListOptionsSetDeleted = newDirectFFI[func(opts *opendalListOptions,
deleted bool)]("opendal_list_options_set_deleted")
-
-var ffiListOptionsFree = newDirectFFI[func(opts
*opendalListOptions)]("opendal_list_options_free")
-
var ffiOperatorListWith = newFFI(
"opendal_operator_list_with_cancel",
func(ctx context.Context, cFunc func(op *opendalOperator, path *byte,
opts *opendalListOptions, cancel *opendalCancelToken, lister **opendalLister)
*opendalError) func(op *opendalOperator, path string, opts *opendalListOptions,
cancel *opendalCancelToken) (*opendalLister, error) {
diff --git a/bindings/go/options.go b/bindings/go/options.go
new file mode 100644
index 0000000000..7cedbbf65e
--- /dev/null
+++ b/bindings/go/options.go
@@ -0,0 +1,157 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/c.rs.
+
+package opendal
+
+import (
+ "context"
+ "runtime"
+)
+
+// WithListFn is a functional option for list operations.
+//
+// # Groups
+// - Traversal: `ListWithRecursive`.
+// - Pagination: `ListWithLimit`, `ListWithStartAfter`.
+// - Versioning: `ListWithVersions`, `ListWithDeleted`.
+//
+// The operation fails with `crate::ErrorKind::Unsupported` when an option
+// requires a capability that the operator lacks.
+type WithListFn func(*listOptions)
+
+// ListWithRecursive sets the recursive option.
+//
+// Whether to list recursively under the prefix; default `false`.
+//
+// Setting this option to `true` requires the operator's effective
+// `Capability.ListWithRecursive` capability.
+func ListWithRecursive(recursive bool) WithListFn {
+ return func(o *listOptions) {
+ o.recursive = recursive
+ }
+}
+
+// ListWithLimit sets the limit option.
+//
+// Maximum results per request (backend hint) to control memory and throttling.
+//
+// A value of 0 leaves it unset.
+func ListWithLimit(limit uint) WithListFn {
+ return func(o *listOptions) {
+ o.limit = limit
+ }
+}
+
+// ListWithStartAfter sets the start_after option.
+//
+// Start listing after this key, excluding the key itself.
+//
+// Setting this requires `Capability.ListWithStartAfter`.
+func ListWithStartAfter(startAfter string) WithListFn {
+ return func(o *listOptions) {
+ o.startAfter = &startAfter
+ }
+}
+
+// ListWithVersions sets the versions option.
+//
+// Include object versions; default `false`.
+//
+// Requires `Capability.ListWithVersions`.
+func ListWithVersions(versions bool) WithListFn {
+ return func(o *listOptions) {
+ o.versions = versions
+ }
+}
+
+// ListWithDeleted sets the deleted option.
+//
+// Include delete markers; default `false`.
+//
+// Requires `Capability.ListWithDeleted`.
+func ListWithDeleted(deleted bool) WithListFn {
+ return func(o *listOptions) {
+ o.deleted = deleted
+ }
+}
+
+type listOptions struct {
+ recursive bool
+ limit uint
+ startAfter *string
+ versions bool
+ deleted bool
+}
+
+func parseListOptions(opts ...WithListFn) *listOptions {
+ o := &listOptions{}
+ for _, opt := range opts {
+ if opt == nil {
+ continue
+ }
+ opt(o)
+ }
+ return o
+}
+
+// newOpendalListOptions builds the C options from o. On error it frees
+// them; otherwise the caller frees them.
+func newOpendalListOptions(ctx context.Context, o *listOptions)
(*opendalListOptions, error) {
+ cOpts := ffiListOptionsNew.symbol(ctx)()
+ ffiListOptionsSetRecursive.symbol(ctx)(cOpts, o.recursive)
+ if o.limit != 0 {
+ ffiListOptionsSetLimit.symbol(ctx)(cOpts, o.limit)
+ }
+ if o.startAfter != nil {
+ if err := ffiListOptionsSetStartAfter.symbol(ctx)(cOpts,
*o.startAfter); err != nil {
+ ffiListOptionsFree.symbol(ctx)(cOpts)
+ return nil, err
+ }
+ }
+ ffiListOptionsSetVersions.symbol(ctx)(cOpts, o.versions)
+ ffiListOptionsSetDeleted.symbol(ctx)(cOpts, o.deleted)
+ return cOpts, nil
+}
+
+var ffiListOptionsNew = newDirectFFI[func()
*opendalListOptions]("opendal_list_options_new")
+
+var ffiListOptionsSetRecursive = newDirectFFI[func(opts *opendalListOptions,
recursive bool)]("opendal_list_options_set_recursive")
+
+var ffiListOptionsSetLimit = newDirectFFI[func(opts *opendalListOptions, limit
uint)]("opendal_list_options_set_limit")
+
+var ffiListOptionsSetStartAfter = newFFI(
+ "opendal_list_options_set_start_after",
+ func(_ context.Context, cFunc func(opts *opendalListOptions, startAfter
*byte)) func(opts *opendalListOptions, startAfter string) error {
+ return func(opts *opendalListOptions, startAfter string) error {
+ bytePtr, err := BytePtrFromString(startAfter)
+ if err != nil {
+ return err
+ }
+ cFunc(opts, bytePtr)
+ runtime.KeepAlive(bytePtr)
+ return nil
+ }
+ },
+)
+
+var ffiListOptionsSetVersions = newDirectFFI[func(opts *opendalListOptions,
versions bool)]("opendal_list_options_set_versions")
+
+var ffiListOptionsSetDeleted = newDirectFFI[func(opts *opendalListOptions,
deleted bool)]("opendal_list_options_set_deleted")
+
+var ffiListOptionsFree = newDirectFFI[func(opts
*opendalListOptions)]("opendal_list_options_free")
diff --git a/bindings/go/options_test.go b/bindings/go/options_test.go
new file mode 100644
index 0000000000..1bc25a2748
--- /dev/null
+++ b/bindings/go/options_test.go
@@ -0,0 +1,163 @@
+// 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.
+
+package opendal
+
+import (
+ "context"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// The list options released before options.go was generated from core.
+// The generator must keep each of them with this exact signature.
+var (
+ _ func(*listOptions) = WithListFn(nil)
+ _ func(recursive bool) WithListFn = ListWithRecursive
+ _ func(limit uint) WithListFn = ListWithLimit
+ _ func(startAfter string) WithListFn = ListWithStartAfter
+ _ func(versions bool) WithListFn = ListWithVersions
+ _ func(deleted bool) WithListFn = ListWithDeleted
+)
+
+// TestListOptionsExportedSet fails when the generator adds or drops a list
+// option, such as exposing `glob` as ListWithGlob.
+func TestListOptionsExportedSet(t *testing.T) {
+ sources, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var options []string
+ for _, source := range sources {
+ if strings.HasSuffix(source, "_test.go") {
+ continue
+ }
+ file, err := parser.ParseFile(token.NewFileSet(), source, nil,
0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, decl := range file.Decls {
+ if fn, ok := decl.(*ast.FuncDecl); ok && fn.Recv == nil
&& strings.HasPrefix(fn.Name.Name, "ListWith") {
+ options = append(options, fn.Name.Name)
+ }
+ }
+ }
+ sort.Strings(options)
+ want := []string{"ListWithDeleted", "ListWithLimit",
"ListWithRecursive", "ListWithStartAfter", "ListWithVersions"}
+ if !slices.Equal(options, want) {
+ t.Fatalf("exported list options = %v, want %v", options, want)
+ }
+}
+
+// TestListOptionsOnMemory lists a memory operator with each list option
+// through the live C library.
+func TestListOptionsOnMemory(t *testing.T) {
+ ctx := context.Background()
+ op, err := NewOperator(localTestScheme{name: "memory", path:
findLocalCLibrary(t)}, OperatorOptions{"root": "/list-options"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer op.Close()
+ for _, path := range []string{"dir/a", "dir/b", "dir/sub/c"} {
+ if _, err := op.Write(ctx, path, []byte(path)); err != nil {
+ t.Fatalf("Write(%q) = %v", path, err)
+ }
+ }
+
+ list := func(opts ...WithListFn) ([]string, error) {
+ lister, err := op.List(ctx, "dir/", opts...)
+ if err != nil {
+ return nil, err
+ }
+ var paths []string
+ for lister.Next(ctx) {
+ paths = append(paths, lister.Entry().Path())
+ }
+ sort.Strings(paths)
+ return paths, errors.Join(lister.Error(), lister.Close())
+ }
+
+ for _, tc := range []struct {
+ name string
+ opts []WithListFn
+ want []string
+ }{
+ {"none", nil, []string{"dir/a", "dir/b", "dir/sub/"}},
+ {"recursive", []WithListFn{ListWithRecursive(true)},
[]string{"dir/a", "dir/b", "dir/sub/c"}},
+ {"not_recursive", []WithListFn{ListWithRecursive(true),
ListWithRecursive(false)}, []string{"dir/a", "dir/b", "dir/sub/"}},
+ // limit is a per-request hint, so the listing stays complete.
+ {"limit", []WithListFn{ListWithLimit(1)}, []string{"dir/a",
"dir/b", "dir/sub/"}},
+ {"start_after", []WithListFn{ListWithStartAfter("dir/a")},
[]string{"dir/b", "dir/sub/"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ paths, err := list(tc.opts...)
+ if err != nil || !reflect.DeepEqual(paths, tc.want) {
+ t.Fatalf("List(dir/) = %v, %v, want %v, nil",
paths, err, tc.want)
+ }
+ })
+ }
+
+ // Memory lacks Capability.ListWithVersions and
Capability.ListWithDeleted.
+ for _, tc := range []struct {
+ name string
+ opt WithListFn
+ }{
+ {"versions", ListWithVersions(true)},
+ {"deleted", ListWithDeleted(true)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ paths, err := list(tc.opt)
+ var opendalErr *Error
+ if !errors.As(err, &opendalErr) || opendalErr.Code() !=
CodeUnsupported {
+ t.Fatalf("List(dir/) = %v, %v, want Unsupported
error", paths, err)
+ }
+ })
+ }
+}
+
+// TestListWithLimitReachesC covers the option that memory ignores: a limit
+// other than 0 reaches opendal_list_options_set_limit, and 0 leaves it unset.
+func TestListWithLimitReachesC(t *testing.T) {
+ for _, tc := range []struct {
+ limit uint
+ want []uint
+ }{{0, nil}, {7, []uint{7}}} {
+ var got []uint
+ ctx := context.Background()
+ ctx = context.WithValue(ctx, ffiListOptionsNew.sym, func()
*opendalListOptions { return &opendalListOptions{} })
+ ctx = context.WithValue(ctx, ffiListOptionsSetRecursive.sym,
func(*opendalListOptions, bool) {})
+ ctx = context.WithValue(ctx, ffiListOptionsSetVersions.sym,
func(*opendalListOptions, bool) {})
+ ctx = context.WithValue(ctx, ffiListOptionsSetDeleted.sym,
func(*opendalListOptions, bool) {})
+ ctx = context.WithValue(ctx, ffiListOptionsSetLimit.sym, func(_
*opendalListOptions, limit uint) {
+ got = append(got, limit)
+ })
+ if _, err := newOpendalListOptions(ctx,
parseListOptions(ListWithLimit(tc.limit))); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got, tc.want) {
+ t.Fatalf("ListWithLimit(%d) set limits %v, want %v",
tc.limit, got, tc.want)
+ }
+ }
+}
diff --git a/dev/src/generate/c.rs b/dev/src/generate/c.rs
index 3c362a7fb8..a8fccc00b5 100644
--- a/dev/src/generate/c.rs
+++ b/dev/src/generate/c.rs
@@ -21,6 +21,8 @@
//! `opendal_capability` by memory layout, so both sides are rendered from the
//! same ordered field list to keep the layouts in lockstep.
+mod options;
+
use super::capability;
use super::metadata::{self, MetadataKind};
use anyhow::Result;
@@ -72,7 +74,8 @@ struct MetadataAccessor {
pub fn generate(workspace_dir: &Path) -> Result<()> {
generate_capability(workspace_dir)?;
- generate_metadata(workspace_dir)
+ generate_metadata(workspace_dir)?;
+ options::generate(workspace_dir)
}
fn generate_capability(workspace_dir: &Path) -> Result<()> {
diff --git a/dev/src/generate/c/options.rs b/dev/src/generate/c/options.rs
new file mode 100644
index 0000000000..8bd01f8a5f
--- /dev/null
+++ b/dev/src/generate/c/options.rs
@@ -0,0 +1,710 @@
+// 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.
+
+//! Operation options for the C binding and the Go options that fill them.
+//!
+//! Released option structs are C ABI: `opendal.h` fixes their member order
+//! and types, and C and Zig callers may read or set members directly.
+//! [`RELEASED_OPTIONS`] records that surface. Docs come from the core doc
+//! comments, plus how C and Go encode an unset option. Core fields it does not
+//! list keep their core default in the conversion and stay out of C and Go.
+//!
+//! Only `ListOptions` is generated so far. The other option structs are still
+//! written by hand in `bindings/c/src/types.rs` and the Go operation files.
+
+use std::path::Path;
+
+use anyhow::{Result, bail};
+use minijinja::value::Serde;
+use minijinja::{Environment, context};
+use serde::Serialize;
+
+use crate::generate::capability::{self, CapabilityField};
+use crate::generate::core_options::{self, OptionField, OptionKind,
OptionsStruct};
+
+/// How a released C struct stores one core field, and how Go fills it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+enum Repr {
+ /// `bool`. Go always calls the setter.
+ Bool,
+ /// `Option<usize>` as `usize`, where `0` means unset. Go skips `0`.
+ UsizeZeroUnset,
+ /// `Option<String>` as a `char *` that the setter copies and `_free`
+ /// releases. Go passes any string the caller set, including an empty one.
+ OwnedString,
+}
+
+impl Repr {
+ /// The core field shape this representation carries.
+ fn kind(self) -> OptionKind {
+ match self {
+ Repr::Bool => OptionKind::Bool,
+ Repr::UsizeZeroUnset => OptionKind::OptionUsize,
+ Repr::OwnedString => OptionKind::OptionString,
+ }
+ }
+}
+
+/// One released C option struct and the Go options that fill it.
+struct OptionsSpec {
+ /// Core struct name, e.g. `ListOptions`.
+ core: &'static str,
+ /// Released core fields in C member order.
+ fields: &'static [(&'static str, Repr)],
+}
+
+/// The released C option structs, in `opendal.h` order.
+const RELEASED_OPTIONS: &[OptionsSpec] = &[OptionsSpec {
+ core: "ListOptions",
+ fields: &[
+ ("recursive", Repr::Bool),
+ ("limit", Repr::UsizeZeroUnset),
+ ("start_after", Repr::OwnedString),
+ ("versions", Repr::Bool),
+ ("deleted", Repr::Bool),
+ ],
+}];
+
+/// Render model of one C option struct and the Go options that fill it.
+#[derive(Serialize)]
+struct OptionsModel {
+ /// Core struct name, e.g. `ListOptions`.
+ core: &'static str,
+ /// C struct name, e.g. `opendal_list_options`.
+ c_name: String,
+ c_doc: Vec<String>,
+ new_doc: Vec<String>,
+ free_doc: Vec<String>,
+ /// Go operation prefix, e.g. `List` in `ListWithLimit`.
+ go_prefix: &'static str,
+ go_fn_doc: Vec<String>,
+ /// Go private options struct, e.g. `listOptions`.
+ go_private: String,
+ fields: Vec<FieldModel>,
+ /// Conversion struct literal fields in core order, defaults included.
+ conversion: Vec<String>,
+}
+
+#[derive(Serialize)]
+struct FieldModel {
+ /// C member and core field name.
+ name: &'static str,
+ repr: Repr,
+ c_type: &'static str,
+ c_default: &'static str,
+ c_doc: Vec<String>,
+ setter_doc: Vec<String>,
+ /// Go option function, e.g. `ListWithLimit`.
+ go_option: String,
+ /// Field of the Go private options struct, e.g. `startAfter`.
+ go_field: String,
+ /// `go_field` padded so that gofmt column alignment is already satisfied.
+ go_field_padded: String,
+ /// Type of `go_field`.
+ go_type: &'static str,
+ /// FFI variable of the C setter, e.g. `ffiListOptionsSetLimit`.
+ go_ffi: String,
+ go_doc: Vec<String>,
+}
+
+pub(super) fn generate(workspace_dir: &Path) -> Result<()> {
+ let source = workspace_dir.join("core/core/src/types/options.rs");
+ let capabilities =
capability::parse(&workspace_dir.join("core/core/src/types/capability.rs"))?;
+ let models = build(&core_options::parse(&source)?, &capabilities)?;
+
+ let mut env = Environment::new();
+ env.add_template("options_rs", include_str!("options_rs.j2"))?;
+ env.add_template("options_go", include_str!("options_go.j2"))?;
+ let outputs = [
+ ("options_rs", "bindings/c/src/options.rs"),
+ ("options_go", "bindings/go/options.go"),
+ ];
+ for (template, relative) in outputs {
+ let rendered = env
+ .get_template(template)?
+ .render(context! { options => Serde(&models) })?;
+ std::fs::write(workspace_dir.join(relative), format!("{rendered}\n"))?;
+ }
+ Ok(())
+}
+
+fn build(parsed: &[OptionsStruct], capabilities: &[CapabilityField]) ->
Result<Vec<OptionsModel>> {
+ RELEASED_OPTIONS
+ .iter()
+ .map(|spec| {
+ let Some(core) = parsed.iter().find(|options| options.name ==
spec.core) else {
+ bail!("core options are missing `{}`, which C releases",
spec.core);
+ };
+ options_model(core, spec, capabilities)
+ })
+ .collect()
+}
+
+fn options_model(
+ core: &OptionsStruct,
+ spec: &OptionsSpec,
+ capabilities: &[CapabilityField],
+) -> Result<OptionsModel> {
+ let go_prefix = spec.core.strip_suffix("Options").unwrap_or(spec.core);
+ let base = heck::AsSnakeCase(go_prefix).to_string();
+ let c_name = format!("opendal_{base}_options");
+
+ let mut fields = Vec::new();
+ for &(name, repr) in spec.fields {
+ let core_field = core_field(core, name, repr)?;
+ let c_doc = binding_doc(&core_field.doc, spec, capabilities, Lang::C);
+ let go_doc = binding_doc(&core_field.doc, spec, capabilities,
Lang::Go);
+ let (c_type, c_default, go_type) = match repr {
+ Repr::Bool => ("bool", "false", "bool"),
+ Repr::UsizeZeroUnset => ("usize", "0", "uint"),
+ Repr::OwnedString => ("*mut c_char", "std::ptr::null_mut()",
"*string"),
+ };
+ // Core options have no C or Go encoding of "unset", so the binding
+ // states its own.
+ let (c_unset, c_param, go_unset) = match repr {
+ Repr::Bool => (None, "The value to set.", None),
+ Repr::UsizeZeroUnset => (
+ Some("`0` means unset."),
+ "The value to set; `0` unsets it.",
+ Some("A value of 0 leaves it unset."),
+ ),
+ Repr::OwnedString => (
+ Some("NULL means unset."),
+ "The string to copy; NULL unsets it.",
+ None,
+ ),
+ };
+ let pascal = super::to_pascal(name);
+ let go_option = format!("{go_prefix}With{pascal}");
+ fields.push(FieldModel {
+ name,
+ repr,
+ c_type,
+ c_default,
+ c_doc: with_note(&c_doc, c_unset),
+ setter_doc: [format!("\\brief Set `{name}`."), String::new()]
+ .into_iter()
+ .chain(c_doc.iter().cloned())
+ .chain([
+ String::new(),
+ format!("@param opts The {c_name} to modify."),
+ format!("@param {name} {c_param}"),
+ ])
+ .collect(),
+ go_doc: with_note(
+ &[
+ format!("{go_option} sets the {name} option."),
+ String::new(),
+ ]
+ .into_iter()
+ .chain(go_doc)
+ .collect::<Vec<_>>(),
+ go_unset,
+ ),
+ go_option,
+ go_field: super::lower_first(&pascal),
+ go_field_padded: String::new(),
+ go_type,
+ go_ffi: format!("ffi{go_prefix}OptionsSet{pascal}"),
+ });
+ }
+ // Pad the Go struct fields as gofmt aligns them.
+ let width = fields.iter().map(|f| f.go_field.len()).max().unwrap_or(0);
+ for field in &mut fields {
+ field.go_field_padded = format!("{:<width$} ", field.go_field);
+ }
+
+ let mut c_doc = binding_doc(&core.doc, spec, capabilities, Lang::C);
+ if let Some(first) = c_doc.first_mut() {
+ *first = format!("\\brief {first}");
+ }
+ c_doc.extend([
+ String::new(),
+ format!("Use `{c_name}_new()` to construct and `{c_name}_free()` to
free."),
+ String::new(),
+ format!("@see opendal_operator_{base}_with"),
+ format!("@see {c_name}_new"),
+ format!("@see {c_name}_free"),
+ ]);
+ c_doc.extend(
+ fields
+ .iter()
+ .map(|f| format!("@see {c_name}_set_{}", f.name)),
+ );
+
+ let mut go_fn_doc = binding_doc(&core.doc, spec, capabilities, Lang::Go);
+ if let Some(first) = go_fn_doc.first_mut() {
+ let purpose = first.strip_prefix("Options for ").unwrap_or(first);
+ *first = format!("With{go_prefix}Fn is a functional option for
{purpose}");
+ }
+
+ Ok(OptionsModel {
+ conversion: conversion(core, &fields)?,
+ core: spec.core,
+ new_doc: vec![
+ format!("\\brief Construct a heap-allocated {c_name} with default
values."),
+ String::new(),
+ format!("@return A new {c_name} with all options set to their
defaults."),
+ String::new(),
+ format!("@see {c_name}_free"),
+ ],
+ free_doc: vec![
+ format!("\\brief Free the heap memory used by {c_name}."),
+ String::new(),
+ format!("@param opts The {c_name} to free."),
+ ],
+ c_name,
+ c_doc,
+ go_prefix,
+ go_fn_doc,
+ go_private: format!("{}Options", super::lower_first(go_prefix)),
+ fields,
+ })
+}
+
+/// The core field of a released C member. Fail when it is gone from core or
+/// changed its shape, since the member and its setter are ABI.
+fn core_field<'a>(core: &'a OptionsStruct, name: &str, repr: Repr) ->
Result<&'a OptionField> {
+ let Some(field) = core.fields.iter().find(|f| f.name == name) else {
+ bail!("core {} is missing released C field `{name}`", core.name);
+ };
+ if field.kind != repr.kind() {
+ bail!(
+ "core {} field `{name}` has kind {:?}; its released C member needs
{:?}",
+ core.name,
+ field.kind,
+ repr.kind()
+ );
+ }
+ Ok(field)
+}
+
+/// The binding that a doc comment is rendered for.
+#[derive(Clone, Copy)]
+enum Lang {
+ C,
+ Go,
+}
+
+/// The core doc comment as `lang` shows it, one entry per line.
+///
+/// Rustdoc links become plain code spans, as in the Node.js generator,
+/// because C and Go documentation cannot resolve Rust paths:
+/// ``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
+/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span.
+/// Code spans that name a released option or a capability then use their
+/// binding name (see [`code_span`]); other code spans stay as written.
+fn binding_doc(
+ lines: &[String],
+ spec: &OptionsSpec,
+ capabilities: &[CapabilityField],
+ lang: Lang,
+) -> Vec<String> {
+ lines
+ .iter()
+ .map(|line| {
+ let mut unlinked = String::with_capacity(line.len());
+ let mut rest = line.as_str();
+ while let Some(start) = rest.find("[`") {
+ let Some(len) = rest[start + 1..].find("`]") else {
+ break;
+ };
+ unlinked.push_str(&rest[..start]);
+ unlinked.push_str(&rest[start + 1..start + len + 2]);
+ rest = &rest[start + len + 3..];
+ if let Some(target) = rest.strip_prefix('(')
+ && let Some(end) = target.find(')')
+ {
+ rest = &target[end + 1..];
+ }
+ }
+ unlinked.push_str(rest);
+
+ let mut out = String::with_capacity(unlinked.len());
+ let mut rest = unlinked.as_str();
+ while let Some(start) = rest.find('`') {
+ let Some(len) = rest[start + 1..].find('`') else {
+ break;
+ };
+ let code = &rest[start + 1..start + 1 + len];
+ out.push_str(&rest[..=start]);
+ out.push_str(
+ &code_span(code, spec, capabilities,
lang).unwrap_or_else(|| code.to_owned()),
+ );
+ out.push('`');
+ rest = &rest[start + len + 2..];
+ }
+ out.push_str(rest);
+ out
+ })
+ .collect()
+}
+
+/// The binding name of a code span that names a released field of `spec` or
+/// a core capability, or `None` to keep the code span as written.
+///
+/// - C: a released field is the struct member of the same name, such as
+/// `start_after`, and `Capability::list_with_start_after` is the
+/// `opendal_capability.list_with_start_after` member.
+/// - Go: a released field is its option function, such as
+/// `ListWithStartAfter`, and `Capability::list_with_start_after` is the
+/// `Capability.ListWithStartAfter` method that `generate_capability` emits.
+fn code_span(
+ code: &str,
+ spec: &OptionsSpec,
+ capabilities: &[CapabilityField],
+ lang: Lang,
+) -> Option<String> {
+ if spec.fields.iter().any(|&(name, _)| name == code) {
+ return Some(match lang {
+ Lang::C => code.to_owned(),
+ Lang::Go => {
+ let go_prefix =
spec.core.strip_suffix("Options").unwrap_or(spec.core);
+ format!("{go_prefix}With{}", super::to_pascal(code))
+ }
+ });
+ }
+ let name = code
+ .strip_prefix("crate::")
+ .unwrap_or(code)
+ .strip_prefix("Capability::")?;
+ capabilities
+ .iter()
+ .any(|f| f.name == name)
+ .then(|| match lang {
+ Lang::C => format!("opendal_capability.{name}"),
+ Lang::Go => format!("Capability.{}", super::to_pascal(name)),
+ })
+}
+
+/// `doc` followed by `note` as its own paragraph.
+fn with_note(doc: &[String], note: Option<&str>) -> Vec<String> {
+ let mut lines = doc.to_vec();
+ if let Some(note) = note {
+ lines.extend([String::new(), note.to_owned()]);
+ }
+ lines
+}
+
+/// Width limits of rustfmt's default configuration.
+const MAX_WIDTH: usize = 100;
+const CHAIN_WIDTH: usize = 60;
+/// Indent of the fields of the conversion struct literal.
+const FIELD_INDENT: usize = 12;
+
+/// The conversion struct literal fields in core order. Fields without a C
+/// member keep their core default.
+fn conversion(core: &OptionsStruct, fields: &[FieldModel]) ->
Result<Vec<String>> {
+ core.fields
+ .iter()
+ .map(|core_field| {
+ let name = &core_field.name;
+ let line = match fields.iter().find(|f| f.name == name) {
+ Some(field) => match field.repr {
+ Repr::Bool => format!("{name}: self.{name},"),
+ Repr::UsizeZeroUnset => {
+ let chain = format!("(self.{name} !=
0).then_some(self.{name})");
+ if chain.len() > CHAIN_WIDTH {
+ bail!("conversion of `{name}` would be rewrapped
by rustfmt");
+ }
+ format!("{name}: {chain},")
+ }
+ Repr::OwnedString => {
+ format!("{name}: unsafe {{
optional_string(self.{name}, \"{name}\") }},")
+ }
+ },
+ None => format!("{name}: {},", default_value(core_field.kind)),
+ };
+ if FIELD_INDENT + line.len() > MAX_WIDTH {
+ bail!("conversion of `{name}` would be rewrapped by rustfmt");
+ }
+ Ok(line)
+ })
+ .collect()
+}
+
+fn default_value(kind: OptionKind) -> &'static str {
+ match kind {
+ OptionKind::Bool => "false",
+ OptionKind::Usize => "0",
+ OptionKind::BytesRange => "Default::default()",
+ OptionKind::OptionUsize
+ | OptionKind::OptionU64
+ | OptionKind::OptionString
+ | OptionKind::OptionTimestamp
+ | OptionKind::OptionDuration
+ | OptionKind::OptionStringMap
+ | OptionKind::OptionMetadata => "None",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn core_options() -> Vec<OptionsStruct> {
+ let source =
crate::workspace_dir().join("core/core/src/types/options.rs");
+ core_options::parse(&source).expect("core options must parse")
+ }
+
+ fn core_capabilities() -> Vec<CapabilityField> {
+ let source =
crate::workspace_dir().join("core/core/src/types/capability.rs");
+ capability::parse(&source).expect("core capability must parse")
+ }
+
+ /// The rendered C options and Go options.
+ fn render(parsed: &[OptionsStruct]) -> (String, String) {
+ let models = context! { options => Serde(&build(parsed,
&core_capabilities()).unwrap()) };
+ let env = Environment::new();
+ let c = env
+ .render_str(include_str!("options_rs.j2"), models.clone())
+ .unwrap();
+ let go = env
+ .render_str(include_str!("options_go.j2"), models)
+ .unwrap();
+ (c, go)
+ }
+
+ /// The doc comment lines directly above the first line that starts with
+ /// `item`, without their comment prefix.
+ fn doc_above<'a>(rendered: &'a str, prefix: &str, item: &str) -> Vec<&'a
str> {
+ let lines: Vec<&str> = rendered.lines().collect();
+ let at = lines
+ .iter()
+ .position(|line| line.starts_with(item))
+ .unwrap_or_else(|| panic!("`{item}` must be rendered"));
+ let mut doc: Vec<&str> = lines[..at]
+ .iter()
+ .rev()
+ .map_while(|line| line.strip_prefix(prefix))
+ .map(str::trim)
+ .collect();
+ doc.reverse();
+ doc
+ }
+
+ /// The code spans in the doc comment lines of `rendered`.
+ fn doc_code_spans<'a>(rendered: &'a str, prefix: &str) -> Vec<&'a str> {
+ rendered
+ .lines()
+ .filter_map(|line| line.trim_start().strip_prefix(prefix))
+ .flat_map(|doc| doc.split('`').skip(1).step_by(2))
+ .collect()
+ }
+
+ #[test]
+ fn test_docs_come_from_core() {
+ let parsed = core_options();
+ let (c, go) = render(&parsed);
+ let spec = &RELEASED_OPTIONS[0];
+ let list = parsed.iter().find(|o| o.name == "ListOptions").unwrap();
+ for &(name, _) in spec.fields {
+ let core_field = list.fields.iter().find(|f| f.name ==
name).unwrap();
+
+ let doc = binding_doc(&core_field.doc, spec, &core_capabilities(),
Lang::C);
+ let doc: Vec<&str> = doc.iter().map(String::as_str).collect();
+ let member = doc_above(&c, " ///", &format!(" pub {name}:
"));
+ assert!(
+ member.starts_with(&doc),
+ "C member docs of `{name}`: {member:?}"
+ );
+
+ let doc = binding_doc(&core_field.doc, spec, &core_capabilities(),
Lang::Go);
+ let doc: Vec<&str> = doc.iter().map(String::as_str).collect();
+ let option = format!("func ListWith{}(",
super::super::to_pascal(name));
+ let option_doc = doc_above(&go, "//", &option);
+ assert!(
+ option_doc.windows(doc.len()).any(|lines| lines == doc),
+ "Go docs of `{name}`: {option_doc:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_binding_doc_strips_rustdoc_links() {
+ let lines = [
+ "Rely on
[`crate::layers::SimulateLayer`](crate::layers::SimulateLayer) and
[`Self::recursive`].",
+ "A [plain](https://opendal.apache.org) link and `code` stay.",
+ ]
+ .map(String::from);
+ let expected = [
+ "Rely on `crate::layers::SimulateLayer` and `Self::recursive`.",
+ "A [plain](https://opendal.apache.org) link and `code` stay.",
+ ];
+ for lang in [Lang::C, Lang::Go] {
+ let doc = binding_doc(&lines, &RELEASED_OPTIONS[0],
&core_capabilities(), lang);
+ assert_eq!(doc, expected);
+ }
+ }
+
+ #[test]
+ fn test_binding_doc_uses_binding_names() {
+ let lines = [
+ "- Pagination: `limit`, `start_after`.",
+ "Requires
[`Capability::list_with_limit`](crate::Capability::list_with_limit).",
+ "Requires [`crate::Capability::list_with_versions`] and
`Capability::list_with_deleted`.",
+ "Unknown `Capability::no_such_flag`, `start_after_key`, `glob`,
and prose start_after stay.",
+ ]
+ .map(String::from);
+ let spec = &RELEASED_OPTIONS[0];
+ assert_eq!(
+ binding_doc(&lines, spec, &core_capabilities(), Lang::C),
+ [
+ "- Pagination: `limit`, `start_after`.",
+ "Requires `opendal_capability.list_with_limit`.",
+ "Requires `opendal_capability.list_with_versions` and
`opendal_capability.list_with_deleted`.",
+ "Unknown `Capability::no_such_flag`, `start_after_key`,
`glob`, and prose start_after stay.",
+ ]
+ );
+ assert_eq!(
+ binding_doc(&lines, spec, &core_capabilities(), Lang::Go),
+ [
+ "- Pagination: `ListWithLimit`, `ListWithStartAfter`.",
+ "Requires `Capability.ListWithLimit`.",
+ "Requires `Capability.ListWithVersions` and
`Capability.ListWithDeleted`.",
+ "Unknown `Capability::no_such_flag`, `start_after_key`,
`glob`, and prose start_after stay.",
+ ]
+ );
+ }
+
+ #[test]
+ fn test_list_docs_name_the_generated_surface() {
+ let (c, go) = render(&core_options());
+
+ // Core writes `start_after` as a plain code span in the struct doc and
+ // the capability as a rustdoc link in the field doc.
+ assert!(c.contains("/// - Pagination: `limit`, `start_after`.\n"));
+ assert!(c.contains(
+ " /// Setting this requires
`opendal_capability.list_with_start_after`.\n"
+ ));
+ assert!(go.contains("// - Pagination: `ListWithLimit`,
`ListWithStartAfter`.\n"));
+ assert!(go.contains("// Setting this requires
`Capability.ListWithStartAfter`.\n"));
+
+ // Every option or capability that the docs name exists in the
+ // generated C header and Go capability.
+ let workspace = crate::workspace_dir();
+ let header =
+
std::fs::read_to_string(workspace.join("bindings/c/include/opendal.h")).unwrap();
+ let struct_body = |name: &str| -> String {
+ let start = header
+ .find(&format!("typedef struct {name} {{"))
+ .unwrap_or_else(|| panic!("opendal.h must define {name}"));
+ let end = start + header[start..].find(&format!("}}
{name};")).unwrap();
+ header[start..end].to_owned()
+ };
+ let c_members = |name: &str| -> Vec<String> {
+ struct_body(name)
+ .lines()
+ .filter_map(|line| line.trim().strip_suffix(';'))
+ .filter_map(|decl| decl.rsplit([' ', '*']).next())
+ .map(str::to_owned)
+ .collect()
+ };
+ let released: Vec<&str> = RELEASED_OPTIONS[0]
+ .fields
+ .iter()
+ .map(|&(name, _)| name)
+ .collect();
+ let list_members = c_members("opendal_list_options");
+ let capability_members = c_members("opendal_capability");
+ for code in doc_code_spans(&c, "///") {
+ assert!(!code.contains("Capability::"), "{code}");
+ if let Some(member) = code.strip_prefix("opendal_capability.") {
+ assert!(capability_members.iter().any(|m| m == member),
"{code}");
+ } else if released.contains(&code) {
+ assert!(list_members.iter().any(|m| m == code), "{code}");
+ }
+ }
+
+ let capability_go =
+
std::fs::read_to_string(workspace.join("bindings/go/capability.go")).unwrap();
+ for code in doc_code_spans(&go, "//") {
+ assert!(!code.contains("Capability::"), "{code}");
+ assert!(!released.contains(&code), "{code} must use its Go name");
+ if let Some(method) = code.strip_prefix("Capability.") {
+ assert!(
+ capability_go.contains(&format!("func (c *Capability)
{method}() ")),
+ "{code}"
+ );
+ } else if code.starts_with("ListWith") {
+ assert!(go.contains(&format!("\nfunc {code}(")), "{code}");
+ }
+ }
+ }
+
+ #[test]
+ fn test_conversion_defaults_unreleased_list_fields() {
+ let (rendered, _) = render(&core_options());
+ let conversion = rendered
+ .split("pub(crate) unsafe fn to_core(&self) ->
options::ListOptions {")
+ .nth(1)
+ .and_then(|rest| rest.split("\n}\n").next())
+ .expect("the list conversion must be rendered");
+ // The conversion reads `start_after` through a raw pointer, so safe
+ // code must not reach it through a `From` impl.
+ assert!(!rendered.contains("impl From<"), "{rendered}");
+ let defaulted: Vec<&str> = conversion
+ .lines()
+ .filter_map(|line| line.trim().strip_suffix(','))
+ .filter_map(|field| field.split_once(": "))
+ .filter(|(_, value)| ["None", "false", "0",
"Default::default()"].contains(value))
+ .map(|(name, _)| name)
+ .collect();
+ // `glob` is the only core list option that C and Go do not expose
(#9323).
+ assert_eq!(defaulted, ["glob"]);
+ }
+
+ #[test]
+ fn test_released_fields_must_stay_in_core() {
+ let mut parsed = core_options();
+ let list = parsed.iter_mut().find(|o| o.name ==
"ListOptions").unwrap();
+ list.fields.retain(|f| f.name != "start_after");
+ let err = build(&parsed, &core_capabilities())
+ .err()
+ .unwrap()
+ .to_string();
+ assert!(
+ err.contains("missing released C field `start_after`"),
+ "{err}"
+ );
+
+ // Any kind change fails, including one to another kind that C can
+ // encode, so `start_after` never silently becomes a `bool` member.
+ for (name, kind, message) in [
+ ("limit", OptionKind::Usize, "`limit` has kind Usize"),
+ (
+ "start_after",
+ OptionKind::Bool,
+ "`start_after` has kind Bool",
+ ),
+ ] {
+ let mut parsed = core_options();
+ let list = parsed.iter_mut().find(|o| o.name ==
"ListOptions").unwrap();
+ list.fields
+ .iter_mut()
+ .find(|f| f.name == name)
+ .unwrap()
+ .kind = kind;
+ let err = build(&parsed, &core_capabilities())
+ .err()
+ .unwrap()
+ .to_string();
+ assert!(err.contains(message), "{err}");
+ }
+ }
+}
diff --git a/dev/src/generate/c/options_go.j2 b/dev/src/generate/c/options_go.j2
new file mode 100644
index 0000000000..fb032a7f14
--- /dev/null
+++ b/dev/src/generate/c/options_go.j2
@@ -0,0 +1,105 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/c.rs.
+
+package opendal
+
+import (
+ "context"
+ "runtime"
+)
+{%- for o in options %}
+{% for line in o.go_fn_doc %}
+//{{ " " ~ line if line else "" }}
+{%- endfor %}
+type With{{ o.go_prefix }}Fn func(*{{ o.go_private }})
+{%- for f in o.fields %}
+{% for line in f.go_doc %}
+//{{ " " ~ line if line else "" }}
+{%- endfor %}
+func {{ f.go_option }}({{ f.go_field }} {{ "string" if f.repr ==
"owned_string" else f.go_type }}) With{{ o.go_prefix }}Fn {
+ return func(o *{{ o.go_private }}) {
+ o.{{ f.go_field }} = {{ "&" if f.repr == "owned_string" else ""
}}{{ f.go_field }}
+ }
+}
+{%- endfor %}
+
+type {{ o.go_private }} struct {
+{%- for f in o.fields %}
+ {{ f.go_field_padded }}{{ f.go_type }}
+{%- endfor %}
+}
+
+func parse{{ o.go_prefix }}Options(opts ...With{{ o.go_prefix }}Fn) *{{
o.go_private }} {
+ o := &{{ o.go_private }}{}
+ for _, opt := range opts {
+ if opt == nil {
+ continue
+ }
+ opt(o)
+ }
+ return o
+}
+
+// newOpendal{{ o.go_prefix }}Options builds the C options from o. On error it
frees
+// them; otherwise the caller frees them.
+func newOpendal{{ o.go_prefix }}Options(ctx context.Context, o *{{
o.go_private }}) (*opendal{{ o.go_prefix }}Options, error) {
+ cOpts := ffi{{ o.go_prefix }}OptionsNew.symbol(ctx)()
+{%- for f in o.fields %}
+{%- if f.repr == "bool" %}
+ {{ f.go_ffi }}.symbol(ctx)(cOpts, o.{{ f.go_field }})
+{%- elif f.repr == "usize_zero_unset" %}
+ if o.{{ f.go_field }} != 0 {
+ {{ f.go_ffi }}.symbol(ctx)(cOpts, o.{{ f.go_field }})
+ }
+{%- elif f.repr == "owned_string" %}
+ if o.{{ f.go_field }} != nil {
+ if err := {{ f.go_ffi }}.symbol(ctx)(cOpts, *o.{{ f.go_field
}}); err != nil {
+ ffi{{ o.go_prefix }}OptionsFree.symbol(ctx)(cOpts)
+ return nil, err
+ }
+ }
+{%- endif %}
+{%- endfor %}
+ return cOpts, nil
+}
+
+var ffi{{ o.go_prefix }}OptionsNew = newDirectFFI[func() *opendal{{
o.go_prefix }}Options]("{{ o.c_name }}_new")
+{%- for f in o.fields %}
+{% if f.repr == "owned_string" %}
+var {{ f.go_ffi }} = newFFI(
+ "{{ o.c_name }}_set_{{ f.name }}",
+ func(_ context.Context, cFunc func(opts *opendal{{ o.go_prefix
}}Options, {{ f.go_field }} *byte)) func(opts *opendal{{ o.go_prefix }}Options,
{{ f.go_field }} string) error {
+ return func(opts *opendal{{ o.go_prefix }}Options, {{
f.go_field }} string) error {
+ bytePtr, err := BytePtrFromString({{ f.go_field }})
+ if err != nil {
+ return err
+ }
+ cFunc(opts, bytePtr)
+ runtime.KeepAlive(bytePtr)
+ return nil
+ }
+ },
+)
+{%- else %}
+var {{ f.go_ffi }} = newDirectFFI[func(opts *opendal{{ o.go_prefix }}Options,
{{ f.go_field }} {{ f.go_type }})]("{{ o.c_name }}_set_{{ f.name }}")
+{%- endif %}
+{%- endfor %}
+
+var ffi{{ o.go_prefix }}OptionsFree = newDirectFFI[func(opts *opendal{{
o.go_prefix }}Options)]("{{ o.c_name }}_free")
+{%- endfor %}
diff --git a/dev/src/generate/c/options_rs.j2 b/dev/src/generate/c/options_rs.j2
new file mode 100644
index 0000000000..772355d9ab
--- /dev/null
+++ b/dev/src/generate/c/options_rs.j2
@@ -0,0 +1,141 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/c.rs.
+
+use std::ffi::{CStr, CString};
+use std::os::raw::c_char;
+
+use opendal::options;
+{%- for o in options %}
+{% for line in o.c_doc %}
+///{{ " " ~ line if line else "" }}
+{%- endfor %}
+#[repr(C)]
+pub struct {{ o.c_name }} {
+{%- for f in o.fields %}
+{%- for line in f.c_doc %}
+ ///{{ " " ~ line if line else "" }}
+{%- endfor %}
+ pub {{ f.name }}: {{ f.c_type }},
+{%- endfor %}
+}
+
+impl {{ o.c_name }} {
+{%- for line in o.new_doc %}
+ ///{{ " " ~ line if line else "" }}
+{%- endfor %}
+ #[no_mangle]
+ pub extern "C" fn {{ o.c_name }}_new() -> *mut Self {
+ Box::into_raw(Box::new(Self::default()))
+ }
+{%- for f in o.fields %}
+{% for line in f.setter_doc %}
+ ///{{ " " ~ line if line else "" }}
+{%- endfor %}
+ #[no_mangle]
+ pub unsafe extern "C" fn {{ o.c_name }}_set_{{ f.name }}(
+ opts: *mut {{ o.c_name }},
+{%- if f.repr == "owned_string" %}
+ {{ f.name }}: *const c_char,
+ ) {
+ if opts.is_null() {
+ return;
+ }
+ // Allocate before freeing the old value so self-aliasing or substring
+ // pointers into `opts->{{ f.name }}` remain valid while reading.
+ let new_ptr = if {{ f.name }}.is_null() {
+ std::ptr::null_mut()
+ } else {
+ let value = option_str({{ f.name }}, "{{ f.name }}");
+ CString::new(value).unwrap().into_raw()
+ };
+ let old_ptr = std::mem::replace(&mut (*opts).{{ f.name }}, new_ptr);
+ if !old_ptr.is_null() {
+ drop(CString::from_raw(old_ptr));
+ }
+ }
+{%- else %}
+ {{ f.name }}: {{ f.c_type }},
+ ) {
+ if !opts.is_null() {
+ (*opts).{{ f.name }} = {{ f.name }};
+ }
+ }
+{%- endif %}
+{%- endfor %}
+{% for line in o.free_doc %}
+ ///{{ " " ~ line if line else "" }}
+{%- endfor %}
+ #[no_mangle]
+ pub unsafe extern "C" fn {{ o.c_name }}_free(opts: *mut {{ o.c_name }}) {
+ if !opts.is_null() {
+ let o = &mut *opts;
+{%- for f in o.fields if f.repr == "owned_string" %}
+ if !o.{{ f.name }}.is_null() {
+ drop(CString::from_raw(o.{{ f.name }}));
+ o.{{ f.name }} = std::ptr::null_mut();
+ }
+{%- endfor %}
+ drop(Box::from_raw(opts));
+ }
+ }
+}
+
+impl Default for {{ o.c_name }} {
+ fn default() -> Self {
+ Self {
+{%- for f in o.fields %}
+ {{ f.name }}: {{ f.c_default }},
+{%- endfor %}
+ }
+ }
+}
+
+impl {{ o.c_name }} {
+ /// Copy these options into core `{{ o.core }}`.
+ ///
+ /// # Safety
+ ///
+{%- for f in o.fields if f.repr == "owned_string" %}
+ /// * A non-null `{{ f.name }}` must point to a readable, nul-terminated C
string
+ /// for the duration of the copy.
+{%- endfor %}
+ pub(crate) unsafe fn to_core(&self) -> options::{{ o.core }} {
+ options::{{ o.core }} {
+{%- for line in o.conversion %}
+ {{ line }}
+{%- endfor %}
+ }
+ }
+}
+{%- endfor %}
+
+/// Read a C string passed for the option `name`.
+unsafe fn option_str<'a>(ptr: *const c_char, name: &str) -> &'a str {
+ CStr::from_ptr(ptr)
+ .to_str()
+ .unwrap_or_else(|err| panic!("malformed {name}: {err:?}"))
+}
+
+unsafe fn optional_string(ptr: *const c_char, name: &str) -> Option<String> {
+ if ptr.is_null() {
+ None
+ } else {
+ Some(option_str(ptr, name).to_owned())
+ }
+}