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 c7752ed909 feat(bindings/c,go): generate DeleteOptions from core
(#9368)
c7752ed909 is described below
commit c7752ed909b11dab3d72c3d2a6d395225f9490f8
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 17:50:49 2026 +0530
feat(bindings/c,go): generate DeleteOptions from core (#9368)
* feat(bindings/c,go): generate DeleteOptions from core
Generate opendal_delete_options, its _new, _free, and _set_* functions,
its conversion to core, and the Go DeleteWith* options from core
DeleteOptions with the C and Go options generator, as #9335 and #9350
did for ListOptions and StatOptions.
The table records today's encodings: the C version setter copies the
string and _free frees it, and Go still returns the bytes it passed so
that callers keep them alive until the C call returns. The conversion
becomes an unsafe fn with a safety contract instead of a safe From impl
that read a raw pointer.
Docs come from core. A bare error kind code span such as `Unsupported`
now renders as the C and Go error name too, and wrapped list items keep
their indent: C keeps the Markdown list that clippy requires, and Go
writes the gofmt list form, which also turns the WithListFn groups into
a Go doc list.
No API or ABI change, and no behavior change.
Signed-off-by: Chitral Verma <[email protected]>
* chore: regenerate DeleteOptions docs from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/c,go): generate DeleteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/c,go): generate DeleteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/c,go): generate DeleteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* chore: regenerate DeleteOptions docs from core
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/c/CMakeLists.txt | 1 +
bindings/c/include/opendal.h | 150 +++++++++++-
bindings/c/src/deleter.rs | 17 +-
bindings/c/src/lib.rs | 2 +-
bindings/c/src/operator.rs | 39 +++-
bindings/c/src/options.rs | 175 ++++++++++++++
bindings/c/src/presign.rs | 38 +++-
bindings/c/src/types.rs | 141 ++++--------
bindings/c/tests/delete.cpp | 211 +++++++++++++++++
bindings/go/delete.go | 80 -------
bindings/go/options.go | 124 +++++++++-
bindings/go/options_test.go | 133 +++++++++++
dev/src/generate/c/options.rs | 478 ++++++++++++++++++++++++++++++++++++---
dev/src/generate/c/options_go.j2 | 28 ++-
dev/src/generate/c/options_rs.j2 | 6 +-
15 files changed, 1378 insertions(+), 245 deletions(-)
diff --git a/bindings/c/CMakeLists.txt b/bindings/c/CMakeLists.txt
index 1fb36f3c12..683d5f9821 100644
--- a/bindings/c/CMakeLists.txt
+++ b/bindings/c/CMakeLists.txt
@@ -94,6 +94,7 @@ set(GTEST_SRCS
tests/bdd.cpp
tests/cancel.cpp
tests/capability.cpp
+ tests/delete.cpp
tests/error_msg.cpp
tests/list.cpp
tests/logging.cpp
diff --git a/bindings/c/include/opendal.h b/bindings/c/include/opendal.h
index a9a3bbd4cc..a5d9f66b8a 100644
--- a/bindings/c/include/opendal.h
+++ b/bindings/c/include/opendal.h
@@ -597,10 +597,31 @@ typedef struct opendal_writer {
} opendal_writer;
/**
- * \brief The options for the delete operation.
+ * \brief Options for delete operations.
+ *
+ * C exposes only `version` and `recursive`, and neither is a condition, so the
+ * conditions below cannot be used from C yet. Selecting a version with
`version`
+ * fails with `OPENDAL_UNSUPPORTED` when
`opendal_capability.delete_with_version`
+ * is false, even if the path is missing.
+ *
+ * Each condition checks the file currently stored at the delete path, and
+ * every condition must hold for the delete to proceed:
+ *
+ * - A false condition fails the delete with
+ * `OPENDAL_CONDITION_NOT_MATCH`.
+ * - A condition the service does not advertise through its capability fails
+ * the delete with `OPENDAL_UNSUPPORTED`; OpenDAL never
+ * silently drops a condition. A service that cannot preserve a
+ * combination of conditions also returns `OPENDAL_UNSUPPORTED`.
+ * - A service-side conflict unrelated to these conditions surfaces as
+ * `OPENDAL_CONFLICT`.
+ *
+ * With valid, supported options, deleting a missing file remains a
+ * successful no-op once every condition holds.
+ *
+ * See the conditional operation specification
+ * for the complete cross-operation contract.
*
- * This struct carries the options for the delete operation, including an
optional
- * version string and whether to delete recursively.
* Use `opendal_delete_options_new()` to construct and
`opendal_delete_options_free()` to free.
*
* @see opendal_operator_delete_with
@@ -611,11 +632,30 @@ typedef struct opendal_writer {
*/
typedef struct opendal_delete_options {
/**
- * Optional version string to delete a specific version; NULL means unset.
+ * Delete the given version of the file instead of the current one.
+ *
+ * This selects which stored version the delete removes; it is not a
+ * condition on the file.
+ *
+ * Check `opendal_capability.delete_with_version` before using this
+ * option.
+ *
+ * NULL means unset. `opendal_delete_options_set_version()` stores a copy of
the
+ * string, and `opendal_delete_options_free()` frees it.
*/
char *version;
/**
- * Whether to delete recursively; default false.
+ * Whether to delete the target recursively.
+ *
+ * The default, `false`, deletes a single object. With `true`, a trailing
+ * slash (for example, `"a/"`) scopes deletion to a directory and its
+ * descendants across services. Prefix matching for paths without a
+ * trailing slash is service-specific. On prefix-based services such as
+ * `memory`, `"a"` also matches entries under `"ab/"`.
+ *
+ * With `true`, the operation returns `OPENDAL_UNSUPPORTED`
+ * when the service does not advertise
+ * `opendal_capability.delete_with_recursive`.
*/
bool recursive;
} opendal_delete_options;
@@ -2148,6 +2188,10 @@ struct opendal_error *opendal_operator_delete(const
struct opendal_operator *op,
*
* * The memory pointed to by `path` must contain a valid nul terminator at
the end of
* the string.
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+ * a copy of its string, which meets this.
*
* # Panic
*
@@ -2161,6 +2205,13 @@ struct opendal_error *opendal_operator_delete_with(const
struct opendal_operator
* \brief Blocking delete the object in `path` with options and optional
cancellation.
*
* Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+ * a copy of its string, which meets this.
*/
struct opendal_error *opendal_operator_delete_with_cancel(const struct
opendal_operator *op,
const char *path,
@@ -2326,6 +2377,10 @@ struct opendal_error *opendal_operator_stat(const struct
opendal_operator *op,
* * The memory pointed to by `path` must contain a valid nul terminator at
the end of
* the string.
* * `meta` must be a valid, aligned, writable pointer.
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+ * store the caller's pointer, not a copy.
*
* # Panic
*
@@ -2342,6 +2397,13 @@ struct opendal_error *opendal_operator_stat_with(const
struct opendal_operator *
* Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
* On cancellation or failure, writes NULL to `*meta` and returns an
`opendal_error *`
* (`OPENDAL_CANCELLED` on cancellation).
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+ * store the caller's pointer, not a copy.
*/
struct opendal_error *opendal_operator_stat_with_cancel(const struct
opendal_operator *op,
const char *path,
@@ -2424,6 +2486,10 @@ struct opendal_error *opendal_operator_list(const struct
opendal_operator *op,
* * The memory pointed to by `path` must contain a valid null terminator at
the end of
* the string.
* * `lister` must be a valid, aligned, writable pointer.
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_list_options_set_start_after`
+ * stores a copy of its string, which meets this.
*
* # Panic
*
@@ -2440,6 +2506,13 @@ struct opendal_error *opendal_operator_list_with(const
struct opendal_operator *
* Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
* On cancellation or failure, writes NULL to `*lister` and returns an
`opendal_error *`
* (`OPENDAL_CANCELLED` on cancellation).
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_list_options_set_start_after`
+ * stores a copy of its string, which meets this.
*/
struct opendal_error *opendal_operator_list_with_cancel(const struct
opendal_operator *op,
const char *path,
@@ -2929,6 +3002,13 @@ struct opendal_error
*opendal_operator_presign_delete(const struct opendal_opera
* writes the request to `*req` and returns NULL; free the request with
* `opendal_presigned_request_free()`. On failure, writes NULL to `*req` and
* returns an error that must be freed with `opendal_error_free()`.
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+ * a copy of its string, which meets this.
*/
struct opendal_error *opendal_operator_presign_delete_with(const struct
opendal_operator *op,
const char *path,
@@ -2942,6 +3022,13 @@ struct opendal_error
*opendal_operator_presign_delete_with(const struct opendal_
* Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
* On cancellation or failure, writes NULL to `*req` and returns an
`opendal_error *`
* (`OPENDAL_CANCELLED` on cancellation).
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+ * a copy of its string, which meets this.
*/
struct opendal_error *opendal_operator_presign_delete_with_cancel(const struct
opendal_operator *op,
const char
*path,
@@ -2970,6 +3057,13 @@ struct opendal_error
*opendal_operator_presign_stat(const struct opendal_operato
* writes the request to `*req` and returns NULL; free the request with
* `opendal_presigned_request_free()`. On failure, writes NULL to `*req` and
* returns an error that must be freed with `opendal_error_free()`.
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+ * store the caller's pointer, not a copy.
*/
struct opendal_error *opendal_operator_presign_stat_with(const struct
opendal_operator *op,
const char *path,
@@ -2983,6 +3077,13 @@ struct opendal_error
*opendal_operator_presign_stat_with(const struct opendal_op
* Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
* On cancellation or failure, writes NULL to `*req` and returns an
`opendal_error *`
* (`OPENDAL_CANCELLED` on cancellation).
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is not
+ * valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+ * store the caller's pointer, not a copy.
*/
struct opendal_error *opendal_operator_presign_stat_with_cancel(const struct
opendal_operator *op,
const char
*path,
@@ -3287,18 +3388,38 @@ void opendal_stat_options_free(struct
opendal_stat_options *opts);
struct opendal_delete_options *opendal_delete_options_new(void);
/**
- * \brief Set the version option.
+ * \brief Set `version`.
+ *
+ * Delete the given version of the file instead of the current one.
+ *
+ * This selects which stored version the delete removes; it is not a
+ * condition on the file.
+ *
+ * Check `opendal_capability.delete_with_version` before using this
+ * option.
*
* @param opts The opendal_delete_options to modify.
- * @param version The version string to delete; NULL to unset.
+ * @param version The string to copy; NULL unsets it.
*/
void opendal_delete_options_set_version(struct opendal_delete_options *opts,
const char *version);
/**
- * \brief Set the recursive option.
+ * \brief Set `recursive`.
+ *
+ * Whether to delete the target recursively.
+ *
+ * The default, `false`, deletes a single object. With `true`, a trailing
+ * slash (for example, `"a/"`) scopes deletion to a directory and its
+ * descendants across services. Prefix matching for paths without a
+ * trailing slash is service-specific. On prefix-based services such as
+ * `memory`, `"a"` also matches entries under `"ab/"`.
+ *
+ * With `true`, the operation returns `OPENDAL_UNSUPPORTED`
+ * when the service does not advertise
+ * `opendal_capability.delete_with_recursive`.
*
* @param opts The opendal_delete_options to modify.
- * @param recursive Whether to delete recursively.
+ * @param recursive The value to set.
*/
void opendal_delete_options_set_recursive(struct opendal_delete_options *opts,
bool recursive);
@@ -3910,6 +4031,10 @@ struct opendal_error
*opendal_deleter_delete_many_with_cancel(struct opendal_del
*
* * The memory pointed to by `path` must contain a valid nul terminator at the
* end of the string.
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is
+ * not valid UTF-8 makes this function panic.
`opendal_delete_options_set_version`
+ * stores a copy of its string, which meets this.
*
* # Panic
*
@@ -3928,6 +4053,13 @@ struct opendal_error *opendal_deleter_delete_with(struct
opendal_deleter *self,
* @param opts The options for this path, or NULL to use defaults
* @param cancel Optional cancel token, or NULL
* @return NULL on success, or an `opendal_error *` on cancellation or failure.
+ *
+ * # Safety
+ *
+ * * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+ * readable, nul-terminated C string until this function returns. A string
that is
+ * not valid UTF-8 makes this function panic.
`opendal_delete_options_set_version`
+ * stores a copy of its string, which meets this.
*/
struct opendal_error *opendal_deleter_delete_with_cancel(struct
opendal_deleter *self,
const char *path,
diff --git a/bindings/c/src/deleter.rs b/bindings/c/src/deleter.rs
index e341fc9c48..fd8c4b4ef6 100644
--- a/bindings/c/src/deleter.rs
+++ b/bindings/c/src/deleter.rs
@@ -186,6 +186,10 @@ impl opendal_deleter {
///
/// * The memory pointed to by `path` must contain a valid nul terminator
at the
/// end of the string.
+ /// * If `opts` is not NULL, each non-NULL string member of `*opts` must
point to a
+ /// readable, nul-terminated C string until this function returns. A
string that is
+ /// not valid UTF-8 makes this function panic.
`opendal_delete_options_set_version`
+ /// stores a copy of its string, which meets this.
///
/// # Panic
///
@@ -207,6 +211,13 @@ impl opendal_deleter {
/// @param opts The options for this path, or NULL to use defaults
/// @param cancel Optional cancel token, or NULL
/// @return NULL on success, or an `opendal_error *` on cancellation or
failure.
+ ///
+ /// # Safety
+ ///
+ /// * If `opts` is not NULL, each non-NULL string member of `*opts` must
point to a
+ /// readable, nul-terminated C string until this function returns. A
string that is
+ /// not valid UTF-8 makes this function panic.
`opendal_delete_options_set_version`
+ /// stores a copy of its string, which meets this.
#[no_mangle]
pub unsafe extern "C" fn opendal_deleter_delete_with_cancel(
&mut self,
@@ -221,7 +232,11 @@ impl opendal_deleter {
let delete_opts = if opts.is_null() {
core::options::DeleteOptions::default()
} else {
- (&*opts).into()
+ // SAFETY: `opts` is non-null, and the caller of this function
passes
+ // options whose non-null `version` is a readable, nul-terminated C
+ // string, such as the copy that
`opendal_delete_options_set_version`
+ // makes.
+ (*opts).to_core()
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
diff --git a/bindings/c/src/lib.rs b/bindings/c/src/lib.rs
index f91a9de6b0..7495865e72 100644
--- a/bindings/c/src/lib.rs
+++ b/bindings/c/src/lib.rs
@@ -72,12 +72,12 @@ mod buffer;
pub use buffer::opendal_bytes;
mod options;
+pub use options::opendal_delete_options;
pub use options::opendal_list_options;
pub use options::opendal_stat_options;
mod types;
pub use types::opendal_copy_options;
-pub use types::opendal_delete_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 891aa05c9c..fe4a749ac1 100644
--- a/bindings/c/src/operator.rs
+++ b/bindings/c/src/operator.rs
@@ -875,6 +875,10 @@ pub unsafe extern "C" fn opendal_operator_delete(
///
/// * The memory pointed to by `path` must contain a valid nul terminator at
the end of
/// the string.
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+/// a copy of its string, which meets this.
///
/// # Panic
///
@@ -891,6 +895,13 @@ pub unsafe extern "C" fn opendal_operator_delete_with(
/// \brief Blocking delete the object in `path` with options and optional
cancellation.
///
/// Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+/// a copy of its string, which meets this.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_delete_with_cancel(
op: &opendal_operator,
@@ -905,7 +916,11 @@ pub unsafe extern "C" fn
opendal_operator_delete_with_cancel(
let delete_opts = if opts.is_null() {
core::options::DeleteOptions::default()
} else {
- (&*opts).into()
+ // SAFETY: `opts` is non-null, and the caller of this function passes
+ // options whose non-null `version` is a readable, nul-terminated C
+ // string, such as the copy that `opendal_delete_options_set_version`
+ // makes.
+ (*opts).to_core()
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
match block_on_cancellable(
@@ -1102,6 +1117,10 @@ pub unsafe extern "C" fn opendal_operator_stat(
/// * The memory pointed to by `path` must contain a valid nul terminator at
the end of
/// the string.
/// * `meta` must be a valid, aligned, writable pointer.
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+/// store the caller's pointer, not a copy.
///
/// # Panic
///
@@ -1121,6 +1140,13 @@ pub unsafe extern "C" fn opendal_operator_stat_with(
/// Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
/// On cancellation or failure, writes NULL to `*meta` and returns an
`opendal_error *`
/// (`OPENDAL_CANCELLED` on cancellation).
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+/// store the caller's pointer, not a copy.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_stat_with_cancel(
op: &opendal_operator,
@@ -1237,6 +1263,10 @@ pub unsafe extern "C" fn opendal_operator_list(
/// * The memory pointed to by `path` must contain a valid null terminator at
the end of
/// the string.
/// * `lister` must be a valid, aligned, writable pointer.
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_list_options_set_start_after`
+/// stores a copy of its string, which meets this.
///
/// # Panic
///
@@ -1256,6 +1286,13 @@ pub unsafe extern "C" fn opendal_operator_list_with(
/// Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
/// On cancellation or failure, writes NULL to `*lister` and returns an
`opendal_error *`
/// (`OPENDAL_CANCELLED` on cancellation).
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_list_options_set_start_after`
+/// stores a copy of its string, which meets this.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_list_with_cancel(
op: &opendal_operator,
diff --git a/bindings/c/src/options.rs b/bindings/c/src/options.rs
index 37e323956f..430dc21676 100644
--- a/bindings/c/src/options.rs
+++ b/bindings/c/src/options.rs
@@ -661,6 +661,181 @@ impl opendal_stat_options {
}
}
+/// \brief Options for delete operations.
+///
+/// C exposes only `version` and `recursive`, and neither is a condition, so
the
+/// conditions below cannot be used from C yet. Selecting a version with
`version`
+/// fails with `OPENDAL_UNSUPPORTED` when
`opendal_capability.delete_with_version`
+/// is false, even if the path is missing.
+///
+/// Each condition checks the file currently stored at the delete path, and
+/// every condition must hold for the delete to proceed:
+///
+/// - A false condition fails the delete with
+/// `OPENDAL_CONDITION_NOT_MATCH`.
+/// - A condition the service does not advertise through its capability fails
+/// the delete with `OPENDAL_UNSUPPORTED`; OpenDAL never
+/// silently drops a condition. A service that cannot preserve a
+/// combination of conditions also returns `OPENDAL_UNSUPPORTED`.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// `OPENDAL_CONFLICT`.
+///
+/// With valid, supported options, deleting a missing file remains a
+/// successful no-op once every condition holds.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+///
+/// Use `opendal_delete_options_new()` to construct and
`opendal_delete_options_free()` to free.
+///
+/// @see opendal_operator_delete_with
+/// @see opendal_delete_options_new
+/// @see opendal_delete_options_free
+/// @see opendal_delete_options_set_version
+/// @see opendal_delete_options_set_recursive
+#[repr(C)]
+pub struct opendal_delete_options {
+ /// Delete the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the delete removes; it is not a
+ /// condition on the file.
+ ///
+ /// Check `opendal_capability.delete_with_version` before using this
+ /// option.
+ ///
+ /// NULL means unset. `opendal_delete_options_set_version()` stores a copy
of the
+ /// string, and `opendal_delete_options_free()` frees it.
+ pub version: *mut c_char,
+ /// Whether to delete the target recursively.
+ ///
+ /// The default, `false`, deletes a single object. With `true`, a trailing
+ /// slash (for example, `"a/"`) scopes deletion to a directory and its
+ /// descendants across services. Prefix matching for paths without a
+ /// trailing slash is service-specific. On prefix-based services such as
+ /// `memory`, `"a"` also matches entries under `"ab/"`.
+ ///
+ /// With `true`, the operation returns `OPENDAL_UNSUPPORTED`
+ /// when the service does not advertise
+ /// `opendal_capability.delete_with_recursive`.
+ pub recursive: bool,
+}
+
+impl opendal_delete_options {
+ /// \brief Construct a heap-allocated opendal_delete_options with default
values.
+ ///
+ /// @return A new opendal_delete_options with all options set to their
defaults.
+ ///
+ /// @see opendal_delete_options_free
+ #[no_mangle]
+ pub extern "C" fn opendal_delete_options_new() -> *mut Self {
+ Box::into_raw(Box::new(Self::default()))
+ }
+
+ /// \brief Set `version`.
+ ///
+ /// Delete the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the delete removes; it is not a
+ /// condition on the file.
+ ///
+ /// Check `opendal_capability.delete_with_version` before using this
+ /// option.
+ ///
+ /// @param opts The opendal_delete_options to modify.
+ /// @param version The string to copy; NULL unsets it.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_delete_options_set_version(
+ opts: *mut opendal_delete_options,
+ version: *const c_char,
+ ) {
+ if opts.is_null() {
+ return;
+ }
+ // Allocate before freeing the old value so self-aliasing or substring
+ // pointers into `opts->version` remain valid while reading.
+ let new_ptr = if version.is_null() {
+ std::ptr::null_mut()
+ } else {
+ let value = option_str(version, "version");
+ CString::new(value).unwrap().into_raw()
+ };
+ let old_ptr = std::mem::replace(&mut (*opts).version, new_ptr);
+ if !old_ptr.is_null() {
+ drop(CString::from_raw(old_ptr));
+ }
+ }
+
+ /// \brief Set `recursive`.
+ ///
+ /// Whether to delete the target recursively.
+ ///
+ /// The default, `false`, deletes a single object. With `true`, a trailing
+ /// slash (for example, `"a/"`) scopes deletion to a directory and its
+ /// descendants across services. Prefix matching for paths without a
+ /// trailing slash is service-specific. On prefix-based services such as
+ /// `memory`, `"a"` also matches entries under `"ab/"`.
+ ///
+ /// With `true`, the operation returns `OPENDAL_UNSUPPORTED`
+ /// when the service does not advertise
+ /// `opendal_capability.delete_with_recursive`.
+ ///
+ /// @param opts The opendal_delete_options to modify.
+ /// @param recursive The value to set.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_delete_options_set_recursive(
+ opts: *mut opendal_delete_options,
+ recursive: bool,
+ ) {
+ if !opts.is_null() {
+ (*opts).recursive = recursive;
+ }
+ }
+
+ /// \brief Free the heap memory used by opendal_delete_options.
+ ///
+ /// @param opts The opendal_delete_options to free.
+ #[no_mangle]
+ pub unsafe extern "C" fn opendal_delete_options_free(opts: *mut
opendal_delete_options) {
+ if !opts.is_null() {
+ let o = &mut *opts;
+ if !o.version.is_null() {
+ drop(CString::from_raw(o.version));
+ o.version = std::ptr::null_mut();
+ }
+ drop(Box::from_raw(opts));
+ }
+ }
+}
+
+impl Default for opendal_delete_options {
+ fn default() -> Self {
+ Self {
+ version: std::ptr::null_mut(),
+ recursive: false,
+ }
+ }
+}
+
+impl opendal_delete_options {
+ /// Copy these options into core `DeleteOptions`.
+ ///
+ /// # Safety
+ ///
+ /// * A non-null `version` must point to a readable, nul-terminated C
string
+ /// for the duration of the copy.
+ pub(crate) unsafe fn to_core(&self) -> options::DeleteOptions {
+ options::DeleteOptions {
+ version: unsafe { optional_string(self.version, "version") },
+ recursive: self.recursive,
+ if_match: None,
+ if_none_match: None,
+ if_version_match: None,
+ if_version_not_match: None,
+ if_not_changed: 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)
diff --git a/bindings/c/src/presign.rs b/bindings/c/src/presign.rs
index 402a46a16f..342e2f9058 100644
--- a/bindings/c/src/presign.rs
+++ b/bindings/c/src/presign.rs
@@ -24,8 +24,8 @@ use opendal::raw::PresignedRequest as ocorePresignedRequest;
use crate::cancel::{block_on_cancellable, opendal_cancel_token,
CancellableError};
use crate::error::opendal_error;
use crate::operator::opendal_operator;
-use crate::options::opendal_stat_options;
-use crate::types::{opendal_delete_options, opendal_read_options,
opendal_write_options};
+use crate::options::{opendal_delete_options, opendal_stat_options};
+use crate::types::{opendal_read_options, opendal_write_options};
/// \brief The key-value pair for the headers of the presigned request.
#[repr(C)]
@@ -308,6 +308,13 @@ pub unsafe extern "C" fn opendal_operator_presign_delete(
/// writes the request to `*req` and returns NULL; free the request with
/// `opendal_presigned_request_free()`. On failure, writes NULL to `*req` and
/// returns an error that must be freed with `opendal_error_free()`.
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+/// a copy of its string, which meets this.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_presign_delete_with(
op: &opendal_operator,
@@ -324,6 +331,13 @@ pub unsafe extern "C" fn
opendal_operator_presign_delete_with(
/// Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
/// On cancellation or failure, writes NULL to `*req` and returns an
`opendal_error *`
/// (`OPENDAL_CANCELLED` on cancellation).
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic.
`opendal_delete_options_set_version` stores
+/// a copy of its string, which meets this.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_presign_delete_with_cancel(
op: &opendal_operator,
@@ -341,7 +355,11 @@ pub unsafe extern "C" fn
opendal_operator_presign_delete_with_cancel(
let opts = if opts.is_null() {
core::options::DeleteOptions::default()
} else {
- (&*opts).into()
+ // SAFETY: `opts` is non-null, and the caller of this function passes
+ // options whose non-null `version` is a readable, nul-terminated C
+ // string, such as the copy that `opendal_delete_options_set_version`
+ // makes.
+ (*opts).to_core()
};
let cancel_token = opendal_cancel_token::as_inner(cancel);
@@ -382,6 +400,13 @@ pub unsafe extern "C" fn opendal_operator_presign_stat(
/// writes the request to `*req` and returns NULL; free the request with
/// `opendal_presigned_request_free()`. On failure, writes NULL to `*req` and
/// returns an error that must be freed with `opendal_error_free()`.
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+/// store the caller's pointer, not a copy.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_presign_stat_with(
op: &opendal_operator,
@@ -398,6 +423,13 @@ pub unsafe extern "C" fn
opendal_operator_presign_stat_with(
/// Pass NULL for `opts` to use defaults, and NULL for `cancel` to run without
cancellation.
/// On cancellation or failure, writes NULL to `*req` and returns an
`opendal_error *`
/// (`OPENDAL_CANCELLED` on cancellation).
+///
+/// # Safety
+///
+/// * If `opts` is not NULL, each non-NULL string member of `*opts` must point
to a
+/// readable, nul-terminated C string until this function returns. A string
that is not
+/// valid UTF-8 makes this function panic. The `opendal_stat_options` string
setters
+/// store the caller's pointer, not a copy.
#[no_mangle]
pub unsafe extern "C" fn opendal_operator_presign_stat_with_cancel(
op: &opendal_operator,
diff --git a/bindings/c/src/types.rs b/bindings/c/src/types.rs
index 798d432210..052244d5b5 100644
--- a/bindings/c/src/types.rs
+++ b/bindings/c/src/types.rs
@@ -16,7 +16,7 @@
// under the License.
use std::collections::HashMap;
-use std::ffi::{c_void, CStr, CString};
+use std::ffi::{c_void, CStr};
use std::os::raw::c_char;
use opendal::options;
@@ -24,106 +24,6 @@ use opendal::raw::Timestamp;
use opendal::BytesRange;
use opendal::{Error, ErrorKind};
-/// \brief The options for the delete operation.
-///
-/// This struct carries the options for the delete operation, including an
optional
-/// version string and whether to delete recursively.
-/// Use `opendal_delete_options_new()` to construct and
`opendal_delete_options_free()` to free.
-///
-/// @see opendal_operator_delete_with
-/// @see opendal_delete_options_new
-/// @see opendal_delete_options_free
-/// @see opendal_delete_options_set_version
-/// @see opendal_delete_options_set_recursive
-#[repr(C)]
-pub struct opendal_delete_options {
- /// Optional version string to delete a specific version; NULL means unset.
- pub version: *mut c_char,
- /// Whether to delete recursively; default false.
- pub recursive: bool,
-}
-
-impl opendal_delete_options {
- /// \brief Construct a heap-allocated opendal_delete_options with default
values.
- ///
- /// @return A new opendal_delete_options with all options set to their
defaults.
- ///
- /// @see opendal_delete_options_free
- #[no_mangle]
- pub extern "C" fn opendal_delete_options_new() -> *mut Self {
- Box::into_raw(Box::new(Self {
- version: std::ptr::null_mut(),
- recursive: false,
- }))
- }
-
- /// \brief Set the version option.
- ///
- /// @param opts The opendal_delete_options to modify.
- /// @param version The version string to delete; NULL to unset.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_delete_options_set_version(
- opts: *mut opendal_delete_options,
- version: *const c_char,
- ) {
- if opts.is_null() {
- return;
- }
- // Allocate before freeing the old value so self-aliasing or substring
- // pointers into `opts->version` remain valid while reading.
- let new_ptr = if version.is_null() {
- std::ptr::null_mut()
- } else {
- let s = CStr::from_ptr(version).to_str().expect("malformed
version");
- CString::new(s).unwrap().into_raw()
- };
- let o = &mut *opts;
- let old_ptr = std::mem::replace(&mut o.version, new_ptr);
- if !old_ptr.is_null() {
- drop(CString::from_raw(old_ptr));
- }
- }
-
- /// \brief Set the recursive option.
- ///
- /// @param opts The opendal_delete_options to modify.
- /// @param recursive Whether to delete recursively.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_delete_options_set_recursive(
- opts: *mut opendal_delete_options,
- recursive: bool,
- ) {
- if !opts.is_null() {
- (*opts).recursive = recursive;
- }
- }
-
- /// \brief Free the heap memory used by opendal_delete_options.
- ///
- /// @param opts The opendal_delete_options to free.
- #[no_mangle]
- pub unsafe extern "C" fn opendal_delete_options_free(opts: *mut
opendal_delete_options) {
- if !opts.is_null() {
- let o = &mut *opts;
- if !o.version.is_null() {
- drop(CString::from_raw(o.version));
- o.version = std::ptr::null_mut();
- }
- drop(Box::from_raw(opts));
- }
- }
-}
-
-impl From<&opendal_delete_options> for options::DeleteOptions {
- fn from(value: &opendal_delete_options) -> Self {
- Self {
- version: unsafe { optional_cstr(value.version) },
- recursive: value.recursive,
- ..Default::default()
- }
- }
-}
-
/// \brief A key-value pair for write user metadata.
#[repr(C)]
pub struct opendal_write_user_metadata_pair {
@@ -1168,13 +1068,17 @@ impl opendal_operator_options {
#[cfg(test)]
mod option_tests {
+ use std::ffi::CString;
+
use super::*;
use crate::error::{opendal_code, opendal_error};
use crate::operator::{
opendal_operator, opendal_operator_read_with,
opendal_operator_reader_with,
opendal_operator_stat_with,
};
- use crate::{opendal_bytes, opendal_list_options, opendal_stat_options};
+ use crate::{
+ opendal_bytes, opendal_delete_options, opendal_list_options,
opendal_stat_options,
+ };
#[test]
fn test_list_options_set_start_after_self_alias_and_substring() {
@@ -1316,6 +1220,39 @@ mod option_tests {
}
}
+ #[test]
+ fn test_delete_options_to_core() {
+ unsafe {
+ let opts = opendal_delete_options::opendal_delete_options_new();
+ assert_eq!((*opts).to_core(), options::DeleteOptions::default());
+
+ // The setter stores its own copy, so the caller's string may go
+ // away before the conversion.
+ let version = CString::new("v1").unwrap();
+ opendal_delete_options::opendal_delete_options_set_version(opts,
version.as_ptr());
+ assert_ne!((*opts).version.cast_const(), version.as_ptr());
+ drop(version);
+ opendal_delete_options::opendal_delete_options_set_recursive(opts,
true);
+ assert_eq!(
+ (*opts).to_core(),
+ options::DeleteOptions {
+ version: Some("v1".to_string()),
+ recursive: true,
+ if_match: None,
+ if_none_match: None,
+ if_version_match: None,
+ if_version_not_match: None,
+ if_not_changed: None,
+ }
+ );
+
+ opendal_delete_options::opendal_delete_options_set_recursive(opts,
false);
+ assert!(!(*opts).to_core().recursive);
+
+ opendal_delete_options::opendal_delete_options_free(opts);
+ }
+ }
+
#[test]
fn test_delete_options_set_version_self_alias_and_substring() {
unsafe {
diff --git a/bindings/c/tests/delete.cpp b/bindings/c/tests/delete.cpp
new file mode 100644
index 0000000000..55671b4f9e
--- /dev/null
+++ b/bindings/c/tests/delete.cpp
@@ -0,0 +1,211 @@
+/*
+ * 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.
+ */
+
+#include "gtest/gtest.h"
+#include <cstddef>
+#include <cstdint>
+#include <type_traits>
+#include <utility>
+
+extern "C" {
+#include "opendal.h"
+}
+
+// opendal_delete_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_delete_options::member),
type>::value, \
+ "opendal_delete_options." #member " changed its type")
+
+ASSERT_MEMBER_TYPE(version, char*);
+ASSERT_MEMBER_TYPE(recursive, bool);
+
+namespace {
+
+// 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(...);
+
+} // namespace
+
+// Exactly the two members above: a third member, even one that fits into the
+// trailing padding, fails here.
+static_assert(decltype(brace_initializable<opendal_delete_options, any_member,
any_member>(0))::value,
+ "opendal_delete_options lost a member");
+static_assert(!decltype(brace_initializable<opendal_delete_options,
+ any_member, any_member, any_member>(0))::value,
+ "opendal_delete_options gained a member");
+
+#if UINTPTR_MAX == UINT64_MAX
+static_assert(sizeof(opendal_delete_options) == 16, "opendal_delete_options
changed its size");
+static_assert(offsetof(opendal_delete_options, version) == 0, "version moved");
+static_assert(offsetof(opendal_delete_options, recursive) == 8, "recursive
moved");
+#endif
+
+ASSERT_SIGNATURE(opendal_delete_options_new, struct opendal_delete_options*
(*)(void));
+ASSERT_SIGNATURE(opendal_delete_options_set_version,
+ void (*)(struct opendal_delete_options*, const char*));
+ASSERT_SIGNATURE(opendal_delete_options_set_recursive,
+ void (*)(struct opendal_delete_options*, bool));
+ASSERT_SIGNATURE(opendal_delete_options_free, void (*)(struct
opendal_delete_options*));
+
+// The version setter stores its own copy, which `_free` releases: the build
+// runs these tests under AddressSanitizer, whose leak check fails on a copy
+// that `_free` keeps.
+TEST(OpendalDeleteOptionsTest, SettersStoreValues)
+{
+ char version[] = "v1";
+ opendal_delete_options_set_version(nullptr, version);
+ opendal_delete_options_set_recursive(nullptr, true);
+
+ opendal_delete_options* opts = opendal_delete_options_new();
+ ASSERT_NE(opts, nullptr);
+ EXPECT_EQ(opts->version, nullptr);
+ EXPECT_FALSE(opts->recursive);
+
+ opendal_delete_options_set_version(opts, version);
+ ASSERT_NE(opts->version, nullptr);
+ EXPECT_NE(opts->version, version);
+ version[0] = 'x';
+ EXPECT_STREQ(opts->version, "v1");
+
+ opendal_delete_options_set_recursive(opts, true);
+ EXPECT_TRUE(opts->recursive);
+ opendal_delete_options_set_recursive(opts, false);
+ EXPECT_FALSE(opts->recursive);
+
+ opendal_delete_options_set_version(opts, nullptr);
+ EXPECT_EQ(opts->version, nullptr);
+ opendal_delete_options_set_version(opts, "v2");
+ opendal_delete_options_free(opts);
+}
+
+class OpendalDeleteOptionsMemoryTest : public ::testing::Test {
+protected:
+ const opendal_operator* p;
+
+ void SetUp() override
+ {
+ opendal_operator_options* options = opendal_operator_options_new();
+ opendal_operator_options_set(options, "root", "/delete-options");
+ opendal_operator* op = nullptr;
+ ASSERT_EQ(opendal_operator_new("memory", options, &op), nullptr);
+ opendal_operator_options_free(options);
+ this->p = op;
+ }
+
+ void TearDown() override { opendal_operator_free(this->p); }
+
+ void write(const char* path)
+ {
+ uint8_t content[] = "hello";
+ opendal_bytes data = {
+ .data = content,
+ .len = 5,
+ };
+ ASSERT_EQ(opendal_operator_write(this->p, path, &data), nullptr);
+ }
+
+ bool exists(const char* path)
+ {
+ bool exists = false;
+ opendal_error* err = opendal_operator_exists(this->p, path, &exists);
+ EXPECT_EQ(err, nullptr);
+ if (err != nullptr) {
+ opendal_error_free(err);
+ }
+ return exists;
+ }
+
+ // The error code of deleting `path` with `opts`, or -1 on success.
+ int delete_code(const char* path, const opendal_delete_options* opts)
+ {
+ opendal_error* err = opendal_operator_delete_with(this->p, path, opts);
+ if (err == nullptr) {
+ return -1;
+ }
+ int code = err->code;
+ opendal_error_free(err);
+ return code;
+ }
+};
+
+// Memory lacks opendal_capability.delete_with_version, so a version fails
+// whether or not the file exists, and leaves the file alone.
+TEST_F(OpendalDeleteOptionsMemoryTest, DeleteWithVersion)
+{
+ write("file");
+ opendal_delete_options* opts = opendal_delete_options_new();
+ opendal_delete_options_set_version(opts, "v1");
+ EXPECT_EQ(delete_code("file", opts), OPENDAL_UNSUPPORTED);
+ EXPECT_EQ(delete_code("missing", opts), OPENDAL_UNSUPPORTED);
+ EXPECT_TRUE(exists("file"));
+ opendal_delete_options_free(opts);
+}
+
+// Deleting a missing path succeeds with no options and with recursive.
+TEST_F(OpendalDeleteOptionsMemoryTest, DeleteMissingPath)
+{
+ EXPECT_EQ(delete_code("missing", nullptr), -1);
+ opendal_delete_options* opts = opendal_delete_options_new();
+ EXPECT_EQ(delete_code("missing", opts), -1);
+ opendal_delete_options_set_recursive(opts, true);
+ EXPECT_EQ(delete_code("missing", opts), -1);
+ EXPECT_EQ(delete_code("missing/", opts), -1);
+ opendal_delete_options_free(opts);
+}
+
+TEST_F(OpendalDeleteOptionsMemoryTest, DeleteRecursive)
+{
+ for (const char* path : { "a/x", "a/sub/y", "ab/z" }) {
+ write(path);
+ }
+ opendal_delete_options* opts = opendal_delete_options_new();
+
+ // Not recursive: a directory's children stay. Memory fails to delete a
+ // directory that has children.
+ EXPECT_EQ(delete_code("a/", opts), OPENDAL_UNEXPECTED);
+ EXPECT_TRUE(exists("a/x"));
+ EXPECT_TRUE(exists("a/sub/y"));
+
+ // A trailing slash scopes the delete to the directory.
+ opendal_delete_options_set_recursive(opts, true);
+ EXPECT_EQ(delete_code("a/", opts), -1);
+ EXPECT_FALSE(exists("a/x"));
+ EXPECT_FALSE(exists("a/sub/y"));
+ EXPECT_TRUE(exists("ab/z"));
+
+ // On memory, "a" also matches entries under "ab/".
+ write("a/x");
+ EXPECT_EQ(delete_code("a", opts), -1);
+ EXPECT_FALSE(exists("a/x"));
+ EXPECT_FALSE(exists("ab/z"));
+ opendal_delete_options_free(opts);
+}
diff --git a/bindings/go/delete.go b/bindings/go/delete.go
index abf2c2eff6..fec7bc3a8a 100644
--- a/bindings/go/delete.go
+++ b/bindings/go/delete.go
@@ -22,35 +22,6 @@ import (
"runtime"
)
-// WithDeleteFn is a functional option for the Delete operation.
-type WithDeleteFn func(*deleteOptions)
-
-// DeleteWithVersion sets the version for the delete operation.
-//
-// When version is set, only the specified version of the object will be
deleted.
-// This is useful for versioned storage backends such as S3 versioning or GCS
object versioning.
-func DeleteWithVersion(version string) WithDeleteFn {
- return func(o *deleteOptions) {
- o.version = &version
- }
-}
-
-// DeleteWithRecursive sets the recursive flag for the delete operation.
-//
-// When recursive is true, all entries under the path (or sharing the prefix
for
-// file-like paths) will be removed.
-func DeleteWithRecursive(recursive bool) WithDeleteFn {
- return func(o *deleteOptions) {
- o.recursive = recursive
- }
-}
-
-// deleteOptions holds the options for a delete operation.
-type deleteOptions struct {
- version *string
- recursive bool
-}
-
// Delete removes the file or directory at the specified path.
//
// # Parameters
@@ -113,37 +84,6 @@ func (op *Operator) Delete(ctx context.Context, path
string, opts ...WithDeleteF
return err
}
-func parseDeleteOptions(opts ...WithDeleteFn) *deleteOptions {
- o := &deleteOptions{}
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- opt(o)
- }
- return o
-}
-
-func newOpendalDeleteOptions(ctx context.Context, o *deleteOptions)
(*opendalDeleteOptions, [][]byte, error) {
- cOpts := ffiDeleteOptionsNew.symbol(ctx)()
- var keepAlive [][]byte
-
- fail := func(err error) (*opendalDeleteOptions, [][]byte, error) {
- ffiDeleteOptionsFree.symbol(ctx)(cOpts)
- return nil, nil, err
- }
-
- ffiDeleteOptionsSetRecursive.symbol(ctx)(cOpts, o.recursive)
- if o.version != nil {
- data, err := ffiDeleteOptionsSetVersion.symbol(ctx)(cOpts,
*o.version)
- if err != nil {
- return fail(err)
- }
- keepAlive = append(keepAlive, data)
- }
- return cOpts, keepAlive, nil
-}
-
var ffiOperatorDelete = newFFI(
"opendal_operator_delete_with_cancel",
func(ctx context.Context, cFunc func(op *opendalOperator, path *byte,
opts *opendalDeleteOptions, cancel *opendalCancelToken) *opendalError) func(op
*opendalOperator, path string, opts *opendalDeleteOptions, cancel
*opendalCancelToken) error {
@@ -158,23 +98,3 @@ var ffiOperatorDelete = newFFI(
}
},
)
-
-var ffiDeleteOptionsNew = newDirectFFI[func()
*opendalDeleteOptions]("opendal_delete_options_new")
-
-var ffiDeleteOptionsSetVersion = newFFI(
- "opendal_delete_options_set_version",
- func(_ context.Context, cFunc func(opts *opendalDeleteOptions, version
*byte)) func(opts *opendalDeleteOptions, version string) ([]byte, error) {
- return func(opts *opendalDeleteOptions, version string)
([]byte, error) {
- data, err := byteSliceFromString(version)
- if err != nil {
- return nil, err
- }
- cFunc(opts, &data[0])
- return data, nil
- }
- },
-)
-
-var ffiDeleteOptionsSetRecursive = newDirectFFI[func(opts
*opendalDeleteOptions, recursive bool)]("opendal_delete_options_set_recursive")
-
-var ffiDeleteOptionsFree = newDirectFFI[func(opts
*opendalDeleteOptions)]("opendal_delete_options_free")
diff --git a/bindings/go/options.go b/bindings/go/options.go
index 37f719ccaa..5304398903 100644
--- a/bindings/go/options.go
+++ b/bindings/go/options.go
@@ -28,9 +28,9 @@ import (
// WithListFn is a functional option for list operations.
//
// # Groups
-// - Traversal: `ListWithRecursive`.
-// - Pagination: `ListWithLimit`, `ListWithStartAfter`.
-// - Versioning: `ListWithVersions`, `ListWithDeleted`.
+// - Traversal: `ListWithRecursive`.
+// - Pagination: `ListWithLimit`, `ListWithStartAfter`.
+// - Versioning: `ListWithVersions`, `ListWithDeleted`.
//
// The operation fails with an `*Error` whose `Code()` is `CodeUnsupported`
when an option
// requires a capability that the operator lacks.
@@ -498,3 +498,121 @@ var ffiStatOptionsSetOverrideContentDisposition = newFFI(
)
var ffiStatOptionsFree = newDirectFFI[func(opts
*opendalStatOptions)]("opendal_stat_options_free")
+
+// WithDeleteFn is a functional option for delete operations.
+//
+// Go exposes only `DeleteWithVersion` and `DeleteWithRecursive`, and neither
is a
+// condition, so the conditions below cannot be used from Go yet. Selecting a
+// version with `DeleteWithVersion` fails with an `*Error` whose `Code()` is
+// `CodeUnsupported` when `Capability.DeleteWithVersion` is false, even if the
path
+// is missing.
+//
+// Each condition checks the file currently stored at the delete path, and
+// every condition must hold for the delete to proceed:
+//
+// - A false condition fails the delete with
+// an `*Error` whose `Code()` is `CodeConditionNotMatch`.
+// - A condition the service does not advertise through its capability fails
+// the delete with an `*Error` whose `Code()` is `CodeUnsupported`;
OpenDAL never
+// silently drops a condition. A service that cannot preserve a
+// combination of conditions also returns an `*Error` whose `Code()` is
`CodeUnsupported`.
+// - A service-side conflict unrelated to these conditions surfaces as
+// an `*Error` whose `Code()` is `CodeConflict`.
+//
+// With valid, supported options, deleting a missing file remains a
+// successful no-op once every condition holds.
+//
+// See the conditional operation specification
+// for the complete cross-operation contract.
+type WithDeleteFn func(*deleteOptions)
+
+// DeleteWithVersion sets the version option.
+//
+// Delete the given version of the file instead of the current one.
+//
+// This selects which stored version the delete removes; it is not a
+// condition on the file.
+//
+// Check `Capability.DeleteWithVersion` before using this
+// option.
+func DeleteWithVersion(version string) WithDeleteFn {
+ return func(o *deleteOptions) {
+ o.version = &version
+ }
+}
+
+// DeleteWithRecursive sets the recursive option.
+//
+// Whether to delete the target recursively.
+//
+// The default, `false`, deletes a single object. With `true`, a trailing
+// slash (for example, `"a/"`) scopes deletion to a directory and its
+// descendants across services. Prefix matching for paths without a
+// trailing slash is service-specific. On prefix-based services such as
+// `memory`, `"a"` also matches entries under `"ab/"`.
+//
+// With `true`, the operation returns an `*Error` whose `Code()` is
`CodeUnsupported`
+// when the service does not advertise
+// `Capability.DeleteWithRecursive`.
+func DeleteWithRecursive(recursive bool) WithDeleteFn {
+ return func(o *deleteOptions) {
+ o.recursive = recursive
+ }
+}
+
+type deleteOptions struct {
+ version *string
+ recursive bool
+}
+
+func parseDeleteOptions(opts ...WithDeleteFn) *deleteOptions {
+ o := &deleteOptions{}
+ for _, opt := range opts {
+ if opt == nil {
+ continue
+ }
+ opt(o)
+ }
+ return o
+}
+
+// newOpendalDeleteOptions builds the C options from o. On error it frees
+// them; otherwise the caller frees them. The C setters copy the strings, and
+// the caller keeps the returned bytes alive until the C call that uses the
+// options returns.
+func newOpendalDeleteOptions(ctx context.Context, o *deleteOptions)
(*opendalDeleteOptions, [][]byte, error) {
+ cOpts := ffiDeleteOptionsNew.symbol(ctx)()
+ var keepAlive [][]byte
+ if o.version != nil {
+ data, err := ffiDeleteOptionsSetVersion.symbol(ctx)(cOpts,
*o.version)
+ if err != nil {
+ ffiDeleteOptionsFree.symbol(ctx)(cOpts)
+ return nil, nil, err
+ }
+ keepAlive = append(keepAlive, data)
+ }
+ ffiDeleteOptionsSetRecursive.symbol(ctx)(cOpts, o.recursive)
+ return cOpts, keepAlive, nil
+}
+
+var ffiDeleteOptionsNew = newDirectFFI[func()
*opendalDeleteOptions]("opendal_delete_options_new")
+
+// ffiDeleteOptionsSetVersion returns the nul-terminated bytes that it passes
to the C
+// setter, which copies them.
+var ffiDeleteOptionsSetVersion = newFFI(
+ "opendal_delete_options_set_version",
+ func(_ context.Context, cFunc func(opts *opendalDeleteOptions, version
*byte)) func(opts *opendalDeleteOptions, version string) ([]byte, error) {
+ return func(opts *opendalDeleteOptions, version string)
([]byte, error) {
+ data, err := byteSliceFromString(version)
+ if err != nil {
+ return nil, err
+ }
+ cFunc(opts, &data[0])
+ return data, nil
+ }
+ },
+)
+
+var ffiDeleteOptionsSetRecursive = newDirectFFI[func(opts
*opendalDeleteOptions, recursive bool)]("opendal_delete_options_set_recursive")
+
+var ffiDeleteOptionsFree = newDirectFFI[func(opts
*opendalDeleteOptions)]("opendal_delete_options_free")
diff --git a/bindings/go/options_test.go b/bindings/go/options_test.go
index 9931a424c3..b73aa2a605 100644
--- a/bindings/go/options_test.go
+++ b/bindings/go/options_test.go
@@ -57,6 +57,14 @@ var (
_ func(contentDisposition string) WithStatFn =
StatWithOverrideContentDisposition
)
+// The delete options released before options.go was generated from core.
+// The generator must keep each of them with this exact signature.
+var (
+ _ func(*deleteOptions) = WithDeleteFn(nil)
+ _ func(version string) WithDeleteFn = DeleteWithVersion
+ _ func(recursive bool) WithDeleteFn = DeleteWithRecursive
+)
+
// exportedFuncs returns the sorted package-level functions whose names start
// with prefix.
func exportedFuncs(t *testing.T, prefix string) []string {
@@ -108,6 +116,16 @@ func TestStatOptionsExportedSet(t *testing.T) {
}
}
+// TestDeleteOptionsExportedSet fails when the generator adds or drops a
+// delete option, such as exposing `if_match` as DeleteWithIfMatch.
+func TestDeleteOptionsExportedSet(t *testing.T) {
+ options := exportedFuncs(t, "DeleteWith")
+ want := []string{"DeleteWithRecursive", "DeleteWithVersion"}
+ if !slices.Equal(options, want) {
+ t.Fatalf("exported delete 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) {
@@ -330,3 +348,118 @@ func TestStatOptionsReachC(t *testing.T) {
t.Fatalf("empty options reached C setters %v, kept %d strings,
err %v", got, len(keepAlive), err)
}
}
+
+// TestDeleteOptionsOnMemory deletes on a memory operator with each delete
+// option through the live C library.
+func TestDeleteOptionsOnMemory(t *testing.T) {
+ ctx := context.Background()
+ op, err := NewOperator(localTestScheme{name: "memory", path:
findLocalCLibrary(t)}, OperatorOptions{"root": "/delete-options"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer op.Close()
+ write := func(paths ...string) {
+ t.Helper()
+ for _, path := range paths {
+ if _, err := op.Write(ctx, path, []byte(path)); err !=
nil {
+ t.Fatalf("Write(%q) = %v", path, err)
+ }
+ }
+ }
+ exists := func(path string) bool {
+ t.Helper()
+ ok, err := op.IsExist(ctx, path)
+ if err != nil {
+ t.Fatalf("IsExist(%q) = %v", path, err)
+ }
+ return ok
+ }
+
+ // Memory lacks Capability.DeleteWithVersion, so a version fails whether
+ // or not the file exists. An empty version is still a version.
+ write("file")
+ for _, version := range []string{"v1", ""} {
+ for _, path := range []string{"file", "missing"} {
+ err := op.Delete(ctx, path, DeleteWithVersion(version))
+ var opendalErr *Error
+ if !errors.As(err, &opendalErr) || opendalErr.Code() !=
CodeUnsupported {
+ t.Fatalf("Delete(%q, version %q) = %v, want
Unsupported error", path, version, err)
+ }
+ }
+ }
+ if !exists("file") {
+ t.Fatal("Delete with a version removed file")
+ }
+
+ for _, opts := range [][]WithDeleteFn{nil, {DeleteWithRecursive(true)}}
{
+ if err := op.Delete(ctx, "missing", opts...); err != nil {
+ t.Fatalf("Delete(missing) with %d options = %v",
len(opts), err)
+ }
+ }
+
+ // Not recursive, a directory's children stay; recursive with a trailing
+ // slash deletes only the directory; and on memory "a" also matches
+ // entries under "ab/".
+ write("a/x", "a/sub/y", "ab/z")
+ // Memory fails to delete a directory that has children.
+ err = op.Delete(ctx, "a/", DeleteWithRecursive(true),
DeleteWithRecursive(false))
+ var opendalErr *Error
+ if !errors.As(err, &opendalErr) || opendalErr.Code() != CodeUnexpected {
+ t.Fatalf("Delete(a/) without recursive = %v, want Unexpected
error", err)
+ }
+ if !exists("a/x") || !exists("a/sub/y") {
+ t.Fatal("Delete(a/) without recursive removed its children")
+ }
+ if err := op.Delete(ctx, "a/", DeleteWithRecursive(true)); err != nil {
+ t.Fatal(err)
+ }
+ if exists("a/x") || exists("a/sub/y") || !exists("ab/z") {
+ t.Fatal("Delete(a/) with recursive must remove a/ and keep
ab/z")
+ }
+ write("a/x")
+ if err := op.Delete(ctx, "a", DeleteWithRecursive(true)); err != nil {
+ t.Fatal(err)
+ }
+ if exists("a/x") || exists("ab/z") {
+ t.Fatal("Delete(a) with recursive must remove a/x and ab/z on
memory")
+ }
+}
+
+// TestDeleteOptionsReachC covers what memory cannot show: each option reaches
+// its C setter with its value, an empty version still reaches C, and the
+// version bytes are returned to keep alive.
+func TestDeleteOptionsReachC(t *testing.T) {
+ var versions []string
+ var recursive []bool
+ ctx := context.Background()
+ ctx = context.WithValue(ctx, ffiDeleteOptionsNew.sym, func()
*opendalDeleteOptions { return &opendalDeleteOptions{} })
+ ctx = context.WithValue(ctx, ffiDeleteOptionsSetVersion.sym, func(_
*opendalDeleteOptions, value string) ([]byte, error) {
+ versions = append(versions, value)
+ return append([]byte(value), 0), nil
+ })
+ ctx = context.WithValue(ctx, ffiDeleteOptionsSetRecursive.sym, func(_
*opendalDeleteOptions, value bool) {
+ recursive = append(recursive, value)
+ })
+
+ for _, tc := range []struct {
+ opts []WithDeleteFn
+ versions []string
+ recursive []bool
+ }{
+ {nil, nil, []bool{false}},
+ {[]WithDeleteFn{DeleteWithVersion("v1"),
DeleteWithRecursive(true)}, []string{"v1"}, []bool{true}},
+ {[]WithDeleteFn{DeleteWithVersion("")}, []string{""},
[]bool{false}},
+ } {
+ versions, recursive = nil, nil
+ _, keepAlive, err := newOpendalDeleteOptions(ctx,
parseDeleteOptions(tc.opts...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(versions, tc.versions) ||
!slices.Equal(recursive, tc.recursive) {
+ t.Fatalf("C setters got versions %q, recursive %v; want
%q, %v", versions, recursive, tc.versions, tc.recursive)
+ }
+ if len(keepAlive) != len(tc.versions) {
+ t.Fatalf("kept %d strings alive, want %d",
len(keepAlive), len(tc.versions))
+ }
+ }
+}
diff --git a/dev/src/generate/c/options.rs b/dev/src/generate/c/options.rs
index 41428cb351..de4efb7f09 100644
--- a/dev/src/generate/c/options.rs
+++ b/dev/src/generate/c/options.rs
@@ -24,9 +24,9 @@
//! Core fields it does not list keep their core default in the conversion and
//! stay out of C and Go.
//!
-//! Only `ListOptions` and `StatOptions` are generated so far. The other option
-//! structs are still written by hand in `bindings/c/src/types.rs` and the Go
-//! operation files.
+//! Only `ListOptions`, `StatOptions`, and `DeleteOptions` are 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::collections::BTreeMap;
use std::path::Path;
@@ -51,6 +51,10 @@ enum Repr {
/// `Option<String>` as a `char *` that the setter copies and `_free`
/// releases. Go passes any string the caller set, including an empty one.
OwnedString,
+ /// `Option<String>` stored in C as for `OwnedString`. Go also passes any
+ /// string the caller set, and returns the bytes it passed so that the
+ /// caller keeps them alive until the operation returns.
+ OwnedStringKeepAlive,
/// `Option<String>` as a `const char *` that the setter stores without
/// copying, so the string must outlive the operation, and `_free` leaves
/// it alone. Go skips an empty string and returns the bytes it passed so
@@ -69,7 +73,9 @@ impl Repr {
match self {
Repr::Bool => OptionKind::Bool,
Repr::UsizeZeroUnset => OptionKind::OptionUsize,
- Repr::OwnedString | Repr::BorrowedString =>
OptionKind::OptionString,
+ Repr::OwnedString | Repr::OwnedStringKeepAlive |
Repr::BorrowedString => {
+ OptionKind::OptionString
+ }
Repr::FlaggedMillis => OptionKind::OptionTimestamp,
}
}
@@ -82,6 +88,12 @@ struct OptionsSpec {
/// Released core fields in C member order, each with its representation
/// and the parameter name of its released Go option.
fields: &'static [(&'static str, Repr, &'static str)],
+ /// A binding-specific paragraph, in core's doc syntax, that follows the
+ /// summary paragraph of the C struct doc and the Go function type doc.
+ /// `{binding}` becomes `C` or `Go`. It tells callers when core's struct
+ /// doc describes options that the bindings do not expose, and it names
+ /// every field in `fields`.
+ binding_note: Option<&'static str>,
}
/// The released C option structs. cbindgen writes their functions in this
@@ -97,6 +109,7 @@ const RELEASED_OPTIONS: &[OptionsSpec] = &[
("versions", Repr::Bool, "versions"),
("deleted", Repr::Bool, "deleted"),
],
+ binding_note: None,
},
OptionsSpec {
core: "StatOptions",
@@ -118,6 +131,22 @@ const RELEASED_OPTIONS: &[OptionsSpec] = &[
"contentDisposition",
),
],
+ binding_note: None,
+ },
+ OptionsSpec {
+ core: "DeleteOptions",
+ fields: &[
+ ("version", Repr::OwnedStringKeepAlive, "version"),
+ ("recursive", Repr::Bool, "recursive"),
+ ],
+ // Core's struct doc is about delete conditions, which C and Go do not
+ // expose yet.
+ binding_note: Some(
+ "{binding} exposes only `version` and `recursive`, and neither is
a condition, \
+ so the conditions below cannot be used from {binding} yet.
Selecting a version \
+ with `version` fails with [`crate::ErrorKind::Unsupported`] when \
+ [`crate::Capability::delete_with_version`] is false, even if the
path is missing.",
+ ),
},
];
@@ -140,7 +169,10 @@ struct OptionsModel {
go_fn_doc: Vec<String>,
/// Go private options struct, e.g. `listOptions`.
go_private: String,
- /// Whether the C options borrow Go bytes that the caller keeps alive.
+ /// Whether Go returns the bytes it passed to C so that the caller keeps
+ /// them alive.
+ go_keep_alive: bool,
+ /// Whether the C options borrow those bytes.
go_borrows: bool,
fields: Vec<FieldModel>,
/// Conversion struct literal lines in core order, defaults included,
@@ -344,6 +376,17 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
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");
+ if let Some(note) = spec.binding_note
+ && let Some(&(name, _, _)) = spec
+ .fields
+ .iter()
+ .find(|&&(name, _, _)| !note.contains(&format!("`{name}`")))
+ {
+ bail!(
+ "the binding note of `{}` does not name its field `{name}`",
+ spec.core
+ );
+ }
let mut fields = Vec::new();
for &(name, repr, go_param) in spec.fields {
@@ -362,7 +405,7 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
None,
"The value to set; `0` unsets it.",
),
- Repr::OwnedString => (
+ Repr::OwnedString | Repr::OwnedStringKeepAlive => (
"*mut c_char",
"std::ptr::null_mut()",
Some(format!(
@@ -402,7 +445,7 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
),
};
let go_note = match repr {
- Repr::Bool | Repr::OwnedString => None,
+ Repr::Bool | Repr::OwnedString | Repr::OwnedStringKeepAlive =>
None,
Repr::UsizeZeroUnset => Some("A value of 0 leaves it
unset.".to_owned()),
Repr::BorrowedString => Some("An empty string leaves it
unset.".to_owned()),
Repr::FlaggedMillis => Some(format!(
@@ -431,7 +474,9 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
let (c_param_type, go_param_type, go_type, go_ffi_type) = match repr {
Repr::Bool => ("bool", "bool", "bool", "bool"),
Repr::UsizeZeroUnset => ("usize", "uint", "uint", "uint"),
- Repr::OwnedString => ("*const c_char", "string", "*string", ""),
+ Repr::OwnedString | Repr::OwnedStringKeepAlive => {
+ ("*const c_char", "string", "*string", "")
+ }
Repr::BorrowedString => ("*const c_char", "string", "string", ""),
Repr::FlaggedMillis => ("i64", "time.Time", "*time.Time", "int64"),
};
@@ -480,7 +525,7 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
field.go_field_padded = format!("{:<width$} ", field.go_field);
}
- let mut c_doc = binding_doc(&core.doc, spec, names, Lang::C);
+ let mut c_doc = struct_doc(core, spec, names, Lang::C);
if let Some(first) = c_doc.first_mut() {
*first = format!("\\brief {first}");
}
@@ -498,7 +543,7 @@ fn options_model(core: &OptionsStruct, spec: &OptionsSpec,
names: &Names) -> Res
.map(|f| format!("@see {c_name}_set_{}", f.name)),
);
- let mut go_fn_doc = binding_doc(&core.doc, spec, names, Lang::Go);
+ let mut go_fn_doc = struct_doc(core, spec, names, 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}");
@@ -519,13 +564,18 @@ fn options_model(core: &OptionsStruct, spec:
&OptionsSpec, names: &Names) -> Res
String::new(),
format!("@param opts The {c_name} to free."),
],
- owns_strings: fields.iter().any(|f| f.repr == Repr::OwnedString),
+ owns_strings: fields
+ .iter()
+ .any(|f| matches!(f.repr, Repr::OwnedString |
Repr::OwnedStringKeepAlive)),
fallible: fields.iter().any(|f| f.repr == Repr::FlaggedMillis),
c_name,
c_doc,
go_prefix,
go_fn_doc,
go_private: format!("{}Options", super::lower_first(go_prefix)),
+ go_keep_alive: fields
+ .iter()
+ .any(|f| matches!(f.repr, Repr::OwnedStringKeepAlive |
Repr::BorrowedString)),
go_borrows: fields.iter().any(|f| f.repr == Repr::BorrowedString),
fields,
};
@@ -578,6 +628,24 @@ enum Lang {
Go,
}
+/// Core's struct doc as `lang` shows it, with `spec`'s binding note as the
+/// second paragraph, wrapped at 80 columns.
+fn struct_doc(core: &OptionsStruct, spec: &OptionsSpec, names: &Names, lang:
Lang) -> Vec<String> {
+ let mut doc = binding_doc(&core.doc, spec, names, lang);
+ let Some(note) = spec.binding_note else {
+ return doc;
+ };
+ let binding = match lang {
+ Lang::C => "C",
+ Lang::Go => "Go",
+ };
+ let note = binding_doc(&[note.replace("{binding}", binding)], spec, names,
lang);
+ let summary_end =
doc.iter().position(String::is_empty).unwrap_or(doc.len());
+ let note = with_note(&[], Some(¬e[0]));
+ doc.splice(summary_end..summary_end, note);
+ doc
+}
+
/// The core doc comment as `lang` shows it, one entry per line.
///
/// Rustdoc links become plain code spans, as in the Node.js generator,
@@ -589,9 +657,10 @@ enum Lang {
/// capability, or an error kind then use their binding name (see
/// [`code_span`]); other code spans stay as written. Go callers check an
/// error kind through `(*Error).Code()`, so Go names it as "an `*Error`
-/// whose `Code()` is `CodeNotFound`".
+/// whose `Code()` is `CodeNotFound`". Core names an error kind as
+/// `ErrorKind::NotFound`, or as `NotFound` once the sentence has named it.
fn binding_doc(lines: &[String], spec: &OptionsSpec, names: &Names, lang:
Lang) -> Vec<String> {
- lines
+ let lines = lines
.iter()
.map(|line| {
let mut line = rewrite_code_spans(line, |code| code_span(code,
spec, names, lang));
@@ -601,6 +670,7 @@ fn binding_doc(lines: &[String], spec: &OptionsSpec, names:
&Names, lang: Lang)
for span in [
format!("`crate::ErrorKind::{kind}`"),
format!("`ErrorKind::{kind}`"),
+ format!("`{kind}`"),
] {
line = line.replace(&span, &error);
}
@@ -608,6 +678,37 @@ fn binding_doc(lines: &[String], spec: &OptionsSpec,
names: &Names, lang: Lang)
}
line
})
+ .collect();
+ indent_lists(lines, lang)
+}
+
+/// Core indents the wrapped lines of a list item under the item, and the core
+/// options parser trims that indent away. Put it back so that each item stays
+/// one item: C keeps the Markdown list, whose unindented wrapped lines
+/// clippy's `doc_lazy_continuation` lint rejects in the generated Rust, and Go
+/// writes the list as gofmt formats a Go doc list.
+fn indent_lists(lines: Vec<String>, lang: Lang) -> Vec<String> {
+ let mut in_item = false;
+ lines
+ .into_iter()
+ .map(|line| {
+ if line.is_empty() {
+ in_item = false;
+ return line;
+ }
+ if let Some(item) = line.strip_prefix("- ") {
+ in_item = true;
+ return match lang {
+ Lang::C => line,
+ Lang::Go => format!(" - {item}"),
+ };
+ }
+ match (in_item, lang) {
+ (false, _) => line,
+ (true, Lang::C) => format!(" {line}"),
+ (true, Lang::Go) => format!(" {line}"),
+ }
+ })
.collect()
}
@@ -618,7 +719,7 @@ fn binding_doc(lines: &[String], spec: &OptionsSpec, names:
&Names, lang: Lang)
/// - C: a released field is the struct member of the same name, such as
/// `start_after`, `Capability::list_with_start_after` is the
/// `opendal_capability.list_with_start_after` member, and
-/// `ErrorKind::NotFound` is the `OPENDAL_NOT_FOUND` code.
+/// `ErrorKind::NotFound` or `NotFound` is the `OPENDAL_NOT_FOUND` code.
/// - 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`
@@ -635,7 +736,8 @@ fn code_span(code: &str, spec: &OptionsSpec, names: &Names,
lang: Lang) -> Optio
});
}
let path = code.strip_prefix("crate::").unwrap_or(code);
- if let Some(kind) = path.strip_prefix("ErrorKind::") {
+ let kind = path.strip_prefix("ErrorKind::").unwrap_or(path);
+ if kind != path || names.c_codes.contains_key(kind) {
return match lang {
Lang::C => names.c_codes.get(kind).cloned(),
Lang::Go => None,
@@ -697,7 +799,7 @@ fn conversion(core: &OptionsStruct, fields: &[FieldModel])
-> Result<Vec<String>
}
vec![format!("{name}: {chain},")]
}
- Some(Repr::OwnedString | Repr::BorrowedString) => {
+ Some(Repr::OwnedString | Repr::OwnedStringKeepAlive |
Repr::BorrowedString) => {
let args = [format!("self.{name}"), format!("\"{name}\"")];
unsafe_call_field(name, "optional_string", &args)?
}
@@ -870,6 +972,106 @@ mod tests {
.collect()
}
+ /// The `pub struct name { ... }` block of the rendered C options.
+ fn c_struct<'a>(rendered: &'a str, name: &str) -> &'a str {
+ let start = rendered
+ .find(&format!("\npub struct {name} {{\n"))
+ .unwrap_or_else(|| panic!("`{name}` must be rendered"));
+ let body = &rendered[start + 1..];
+ &body[..body.find("\n}\n").unwrap()]
+ }
+
+ /// Split doc lines into paragraphs, each joined into one line of words.
+ fn paragraphs<'a>(lines: impl IntoIterator<Item = &'a str>) -> Vec<String>
{
+ let mut paragraphs = vec![Vec::new()];
+ for line in lines {
+ match line.trim() {
+ "" => paragraphs.push(Vec::new()),
+ text => paragraphs.last_mut().unwrap().push(text),
+ }
+ }
+ paragraphs
+ .into_iter()
+ .filter(|words| !words.is_empty())
+ .map(|words| words.join(" "))
+ .collect()
+ }
+
+ /// Core doc text as C or Go must read it, one entry per paragraph,
+ /// written from the rules that [`binding_doc`] documents rather than with
+ /// it.
+ ///
+ /// Rustdoc links to code keep their code span, and reference links to
+ /// crate items keep their text. C names a capability as its
+ /// `opendal_capability` member and an error kind as its `opendal_code`;
+ /// Go names a capability as its `Capability` method, an error kind as the
+ /// `*Error` whose `Code()` is the `ErrorCode`, and a released field as
+ /// its option function.
+ fn expected_paragraphs(core_doc: &[String], spec: &OptionsSpec, lang:
Lang) -> Vec<String> {
+ use regex::{Captures, Regex};
+
+ // The `opendal_code` and Go `ErrorCode` names of core error kinds, as
+ // `opendal.h` and `error.go` spell them.
+ const KINDS: &[(&str, &str, &str)] = &[
+ ("Unsupported", "OPENDAL_UNSUPPORTED", "CodeUnsupported"),
+ (
+ "ConfigInvalid",
+ "OPENDAL_CONFIG_INVALID",
+ "CodeConfigInvalid",
+ ),
+ ("NotFound", "OPENDAL_NOT_FOUND", "CodeNotFound"),
+ (
+ "PermissionDenied",
+ "OPENDAL_PERMISSION_DENIED",
+ "CodePermissioDenied",
+ ),
+ (
+ "ConditionNotMatch",
+ "OPENDAL_CONDITION_NOT_MATCH",
+ "CodeConditionNotMatch",
+ ),
+ ("Conflict", "OPENDAL_CONFLICT", "CodeConflict"),
+ ];
+ let text = core_doc.join("\n");
+ let text = Regex::new(r"\[(`[^`]*`)\](\([^)]*\))?")
+ .unwrap()
+ .replace_all(&text, "$1");
+ let text = Regex::new(r"\[([^\]]*)\]\[crate::[^\]]*\]")
+ .unwrap()
+ .replace_all(&text, "$1");
+ let text = Regex::new(r"`(?:crate::)?Capability::(\w+)`")
+ .unwrap()
+ .replace_all(&text, |c: &Captures| match lang {
+ Lang::C => format!("`opendal_capability.{}`", &c[1]),
+ Lang::Go => format!("`Capability.{}`",
heck::AsUpperCamelCase(&c[1])),
+ });
+ let text = Regex::new(r"`(?:crate::)?(?:ErrorKind::)?(\w+)`")
+ .unwrap()
+ .replace_all(&text, |c: &Captures| {
+ match KINDS.iter().find(|(kind, _, _)| *kind == &c[1]) {
+ Some((_, code, _)) if matches!(lang, Lang::C) =>
format!("`{code}`"),
+ Some((_, _, code)) => format!("an `*Error` whose `Code()`
is `{code}`"),
+ None => c[0].to_owned(),
+ }
+ });
+ let prefix = spec.core.strip_suffix("Options").unwrap();
+ let text = Regex::new(r"`(\w+)`")
+ .unwrap()
+ .replace_all(&text, |c: &Captures| {
+ let released = spec.fields.iter().any(|&(name, _, _)| name ==
&c[1]);
+ match lang {
+ Lang::Go if released => {
+ format!("`{prefix}With{}`",
heck::AsUpperCamelCase(&c[1]))
+ }
+ _ => c[0].to_owned(),
+ }
+ });
+ paragraphs(text.lines())
+ }
+
+ /// Every C member, C setter, and Go option documents its core field with
+ /// the field's full core doc, and the C struct and Go function type with
+ /// the struct's, before what the binding adds.
#[test]
fn test_docs_come_from_core() {
let parsed = core_options();
@@ -877,31 +1079,176 @@ mod tests {
for spec in RELEASED_OPTIONS {
let core = parsed.iter().find(|o| o.name == spec.core).unwrap();
let go_prefix = spec.core.strip_suffix("Options").unwrap();
+ let c_name = format!("opendal_{}_options",
heck::AsSnakeCase(go_prefix));
for &(name, _, _) in spec.fields {
let core_field = core.fields.iter().find(|f| f.name ==
name).unwrap();
+ let at = format!("{}.{name}", spec.core);
- let doc = binding_doc(&core_field.doc, spec, &names(),
Lang::C);
- let doc: Vec<&str> = doc.iter().map(String::as_str).collect();
- let member = doc_above(&c, " ///", &format!(" pub
{name}: "));
+ let expected = expected_paragraphs(&core_field.doc, spec,
Lang::C);
+ let members = format!("\n{}", c_struct(&c, &c_name));
+ let member =
+ paragraphs(doc_above(&members, " ///", &format!("
pub {name}: ")));
+ assert_eq!(member[..expected.len()], expected, "C member
`{at}`");
assert!(
- member.starts_with(&doc),
- "C member docs of `{}.{name}`: {member:?}",
- spec.core
+ member.len() <= expected.len() + 1,
+ "C member `{at}`: {member:?}"
+ );
+
+ let setter = format!(" pub unsafe extern \"C\" fn
{c_name}_set_{name}(");
+ let setter = paragraphs(doc_above(&c, " ///", &setter));
+ assert_eq!(
+ setter[0],
+ format!("\\brief Set `{name}`."),
+ "C setter `{at}`"
);
+ assert_eq!(setter[1..=expected.len()], expected, "C setter
`{at}`");
- let doc = binding_doc(&core_field.doc, spec, &names(),
Lang::Go);
- let doc: Vec<&str> = doc.iter().map(String::as_str).collect();
- let option = format!("func {go_prefix}With{}(",
super::super::to_pascal(name));
- let option_doc = doc_above(&go, "//", &option);
+ let expected = expected_paragraphs(&core_field.doc, spec,
Lang::Go);
+ let option = format!("{go_prefix}With{}",
super::super::to_pascal(name));
+ let option_doc = paragraphs(doc_above(&go, "//",
&format!("func {option}(")));
+ assert_eq!(option_doc[0], format!("{option} sets the {name}
option."));
+ assert_eq!(option_doc[1..=expected.len()], expected, "Go
option `{at}`");
assert!(
- option_doc.windows(doc.len()).any(|lines| lines == doc),
- "Go docs of `{}.{name}`: {option_doc:?}",
- spec.core
+ option_doc.len() <= expected.len() + 2,
+ "Go option `{at}`: {option_doc:?}"
);
}
+
+ // The binding note follows the summary paragraph.
+ let (c_note, go_note) = match binding_notes(spec.core) {
+ Some((c, go)) => (vec![c.to_owned()], vec![go.to_owned()]),
+ None => (vec![], vec![]),
+ };
+
+ let expected = expected_paragraphs(&core.doc, spec, Lang::C);
+ let struct_doc = paragraphs(doc_above(&c, "///", &format!("pub
struct {c_name} {{")));
+ let (summary, rest) = struct_doc.split_first().unwrap();
+ assert_eq!(*summary, format!("\\brief {}", expected[0]));
+ let (note, rest) = rest.split_at(c_note.len());
+ assert_eq!(note, c_note, "C `{c_name}` note");
+ assert_eq!(rest[..expected.len() - 1], expected[1..], "C
`{c_name}`");
+ assert_eq!(
+ rest[expected.len() - 1],
+ format!("Use `{c_name}_new()` to construct and
`{c_name}_free()` to free.")
+ );
+
+ let expected = expected_paragraphs(&core.doc, spec, Lang::Go);
+ let go_fn = format!("With{go_prefix}Fn");
+ let fn_doc = paragraphs(doc_above(&go, "//", &format!("type
{go_fn} ")));
+ let purpose = expected[0].strip_prefix("Options for ").unwrap();
+ let (summary, rest) = fn_doc.split_first().unwrap();
+ assert_eq!(
+ *summary,
+ format!("{go_fn} is a functional option for {purpose}")
+ );
+ let (note, rest) = rest.split_at(go_note.len());
+ assert_eq!(note, go_note, "Go `{go_fn}` note");
+ assert_eq!(rest, &expected[1..], "Go `{go_fn}`");
}
}
+ /// The binding notes that C and Go callers must read, one paragraph per
+ /// binding, as written for review.
+ fn binding_notes(core: &str) -> Option<(&'static str, &'static str)> {
+ match core {
+ "DeleteOptions" => Some((
+ "C exposes only `version` and `recursive`, and neither is a
condition, so \
+ the conditions below cannot be used from C yet. Selecting a
version with \
+ `version` fails with `OPENDAL_UNSUPPORTED` when \
+ `opendal_capability.delete_with_version` is false, even if
the path is \
+ missing.",
+ "Go exposes only `DeleteWithVersion` and
`DeleteWithRecursive`, and neither \
+ is a condition, so the conditions below cannot be used from
Go yet. \
+ Selecting a version with `DeleteWithVersion` fails with an
`*Error` whose \
+ `Code()` is `CodeUnsupported` when
`Capability.DeleteWithVersion` is \
+ false, even if the path is missing.",
+ )),
+ _ => None,
+ }
+ }
+
+ /// A binding note must name every field of its struct, so that adding a
+ /// field forces the note to be revisited.
+ #[test]
+ fn test_binding_note_names_every_field() {
+ let parsed = core_options();
+ let spec = OptionsSpec {
+ core: "DeleteOptions",
+ fields: spec("DeleteOptions").fields,
+ binding_note: Some("{binding} exposes only `version`."),
+ };
+ let core = parsed.iter().find(|o| o.name == "DeleteOptions").unwrap();
+ let err = options_model(core, &spec, &names()).err().unwrap();
+ assert_eq!(
+ err.to_string(),
+ "the binding note of `DeleteOptions` does not name its field
`recursive`"
+ );
+ }
+
+ /// The rules in [`expected_paragraphs`] at work on examples, so that a
+ /// rule that rewrites nothing in today's core docs still has to hold.
+ #[test]
+ fn test_expected_paragraphs_rules() {
+ let lines = [
+ "Requires [`crate::Capability::delete_with_version`] and
`recursive`.",
+ "",
+ "- Fails with [`crate::ErrorKind::ConditionNotMatch`]",
+ " or `Unsupported`; see the [spec][crate::docs::specs::x].",
+ ]
+ .map(String::from);
+ let spec = spec("DeleteOptions");
+ assert_eq!(
+ expected_paragraphs(&lines, spec, Lang::C),
+ [
+ "Requires `opendal_capability.delete_with_version` and
`recursive`.",
+ "- Fails with `OPENDAL_CONDITION_NOT_MATCH` or
`OPENDAL_UNSUPPORTED`; see the spec.",
+ ]
+ );
+ assert_eq!(
+ expected_paragraphs(&lines, spec, Lang::Go),
+ [
+ "Requires `Capability.DeleteWithVersion` and
`DeleteWithRecursive`.",
+ "- Fails with an `*Error` whose `Code()` is
`CodeConditionNotMatch` or an `*Error` whose `Code()` is `CodeUnsupported`; see
the spec.",
+ ]
+ );
+ }
+
+ #[test]
+ fn test_binding_doc_indents_list_items() {
+ let lines = [
+ "# Groups",
+ "- Traversal: `recursive`.",
+ "- Fails with",
+ "[`crate::ErrorKind::Conflict`].",
+ "",
+ "A paragraph stays.",
+ ]
+ .map(String::from);
+ let spec = spec("DeleteOptions");
+ assert_eq!(
+ binding_doc(&lines, spec, &names(), Lang::C),
+ [
+ "# Groups",
+ "- Traversal: `recursive`.",
+ "- Fails with",
+ " `OPENDAL_CONFLICT`.",
+ "",
+ "A paragraph stays.",
+ ]
+ );
+ assert_eq!(
+ binding_doc(&lines, spec, &names(), Lang::Go),
+ [
+ "# Groups",
+ " - Traversal: `DeleteWithRecursive`.",
+ " - Fails with",
+ " an `*Error` whose `Code()` is `CodeConflict`.",
+ "",
+ "A paragraph stays.",
+ ]
+ );
+ }
+
#[test]
fn test_binding_doc_strips_rustdoc_links() {
let lines = [
@@ -925,9 +1272,11 @@ mod tests {
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`.",
"Fails with [`crate::ErrorKind::NotFound`] or
`ErrorKind::PermissionDenied`.",
+ "Also returns `Unsupported`, not `Unsupported_` or `ErrorKind`.",
"Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`,
`start_after_key`, `glob`, and prose start_after stay.",
]
.map(String::from);
@@ -936,9 +1285,11 @@ mod tests {
binding_doc(&lines, spec, &names(), Lang::C),
[
"- Pagination: `limit`, `start_after`.",
+ "",
"Requires `opendal_capability.list_with_limit`.",
"Requires `opendal_capability.list_with_versions` and
`opendal_capability.list_with_deleted`.",
"Fails with `OPENDAL_NOT_FOUND` or
`OPENDAL_PERMISSION_DENIED`.",
+ "Also returns `OPENDAL_UNSUPPORTED`, not `Unsupported_` or
`ErrorKind`.",
"Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`,
`start_after_key`, `glob`, and prose start_after stay.",
]
);
@@ -946,10 +1297,12 @@ mod tests {
assert_eq!(
binding_doc(&lines, spec, &names(), Lang::Go),
[
- "- Pagination: `ListWithLimit`, `ListWithStartAfter`.",
+ " - Pagination: `ListWithLimit`, `ListWithStartAfter`.",
+ "",
"Requires `Capability.ListWithLimit`.",
"Requires `Capability.ListWithVersions` and
`Capability.ListWithDeleted`.",
"Fails with an `*Error` whose `Code()` is `CodeNotFound` or an
`*Error` whose `Code()` is `CodePermissioDenied`.",
+ "Also returns an `*Error` whose `Code()` is `CodeUnsupported`,
not `Unsupported_` or `ErrorKind`.",
"Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`,
`start_after_key`, `glob`, and prose start_after stay.",
]
);
@@ -985,16 +1338,20 @@ mod tests {
" /// Check `opendal_capability.stat_with_version` before using
this\n",
" /// `OPENDAL_CONDITION_NOT_MATCH`; a missing file returns\n",
"/// See the conditional operation specification\n",
+ " /// Check `opendal_capability.delete_with_version` before
using this\n",
+ "/// combination of conditions also returns
`OPENDAL_UNSUPPORTED`.\n",
] {
assert!(c.contains(expected), "C docs must contain {expected:?}");
}
for expected in [
- "// - Pagination: `ListWithLimit`, `ListWithStartAfter`.\n",
+ "// - Pagination: `ListWithLimit`, `ListWithStartAfter`.\n",
"// Setting this requires `Capability.ListWithStartAfter`.\n",
"// The operation fails with an `*Error` whose `Code()` is
`CodeUnsupported` when an option\n",
"// Check `Capability.StatWithVersion` before using this\n",
"// an `*Error` whose `Code()` is `CodeConditionNotMatch`; a
missing file returns\n",
"// See the conditional operation specification\n",
+ "// Check `Capability.DeleteWithVersion` before using this\n",
+ "// combination of conditions also returns an `*Error` whose
`Code()` is `CodeUnsupported`.\n",
] {
assert!(go.contains(expected), "Go docs must contain
{expected:?}");
}
@@ -1057,7 +1414,10 @@ mod tests {
|| error_go.contains(&format!("\n\t{code} ErrorCode")),
"{code}"
);
- } else if code.starts_with("ListWith") ||
code.starts_with("StatWith") {
+ } else if ["ListWith", "StatWith", "DeleteWith"]
+ .iter()
+ .any(|prefix| code.starts_with(prefix))
+ {
assert!(go.contains(&format!("\nfunc {code}(")), "{code}");
}
}
@@ -1069,7 +1429,8 @@ mod tests {
let doc =
|rendered: &str, prefix: &str, item: &str| doc_above(rendered,
prefix, item).join(" ");
- let member = doc(&c, " ///", " pub start_after: ");
+ let list = format!("\n{}", c_struct(&c, "opendal_list_options"));
+ let member = doc(&list, " ///", " pub start_after: ");
assert!(
member.contains("`opendal_list_options_set_start_after()` stores a
copy"),
"{member}"
@@ -1088,8 +1449,9 @@ mod tests {
"{setter}"
);
+ let stat = format!("\n{}", c_struct(&c, "opendal_stat_options"));
for name in ["version", "if_match", "override_content_disposition"] {
- let member = doc(&c, " ///", &format!(" pub {name}: "));
+ let member = doc(&stat, " ///", &format!(" pub {name}: "));
assert!(
member.contains(&format!(
"`opendal_stat_options_set_{name}()` stores this pointer
without copying"
@@ -1117,6 +1479,24 @@ mod tests {
);
}
+ // Delete `version` is copied as list `start_after` is.
+ let delete = format!("\n{}", c_struct(&c, "opendal_delete_options"));
+ let member = doc(&delete, " ///", " pub version: ");
+ assert!(
+ member.contains("`opendal_delete_options_set_version()` stores a
copy")
+ && member.contains("`opendal_delete_options_free()` frees it"),
+ "{member}"
+ );
+ let setter = doc(
+ &c,
+ " ///",
+ " pub unsafe extern \"C\" fn
opendal_delete_options_set_version(",
+ );
+ assert!(
+ setter.contains("@param version The string to copy; NULL unsets
it."),
+ "{setter}"
+ );
+
let setter = doc(
&c,
" ///",
@@ -1178,13 +1558,26 @@ mod tests {
assert!(rendered.contains(
"pub(crate) unsafe fn to_core(&self) ->
opendal::Result<options::StatOptions> {"
));
- // `glob`, the version conditions, and `checksum` are the core options
- // that C and Go do not expose (#9323).
+ assert!(
+ rendered.contains("pub(crate) unsafe fn to_core(&self) ->
options::DeleteOptions {")
+ );
+ // `glob`, the conditions, and `checksum` are the core options that C
+ // and Go do not expose (#9323).
assert_eq!(defaulted_fields(&rendered, "ListOptions"), ["glob"]);
assert_eq!(
defaulted_fields(&rendered, "StatOptions"),
["if_version_match", "if_version_not_match", "checksum"]
);
+ assert_eq!(
+ defaulted_fields(&rendered, "DeleteOptions"),
+ [
+ "if_match",
+ "if_none_match",
+ "if_version_match",
+ "if_version_not_match",
+ "if_not_changed"
+ ]
+ );
}
#[test]
@@ -1192,6 +1585,7 @@ mod tests {
for (core, name) in [
("ListOptions", "start_after"),
("StatOptions", "if_modified_since"),
+ ("DeleteOptions", "recursive"),
] {
let mut parsed = core_options();
let options = parsed.iter_mut().find(|o| o.name == core).unwrap();
@@ -1230,6 +1624,18 @@ mod tests {
OptionKind::OptionString,
"`if_unmodified_since` has kind OptionString",
),
+ (
+ "DeleteOptions",
+ "version",
+ OptionKind::OptionUsize,
+ "`version` has kind OptionUsize",
+ ),
+ (
+ "DeleteOptions",
+ "recursive",
+ OptionKind::OptionString,
+ "`recursive` has kind OptionString",
+ ),
] {
let mut parsed = core_options();
let options = parsed.iter_mut().find(|o| o.name == core).unwrap();
diff --git a/dev/src/generate/c/options_go.j2 b/dev/src/generate/c/options_go.j2
index b8b601d580..c8b9b11982 100644
--- a/dev/src/generate/c/options_go.j2
+++ b/dev/src/generate/c/options_go.j2
@@ -35,7 +35,7 @@ type With{{ o.go_prefix }}Fn func(*{{ o.go_private }})
{%- endfor %}
func {{ f.go_option }}({{ f.go_param }} {{ f.go_param_type }}) With{{
o.go_prefix }}Fn {
return func(o *{{ o.go_private }}) {
- o.{{ f.go_field }} = {{ "&" if f.repr in ["owned_string",
"flagged_millis"] else "" }}{{ f.go_param }}
+ o.{{ f.go_field }} = {{ "&" if f.repr in ["owned_string",
"owned_string_keep_alive", "flagged_millis"] else "" }}{{ f.go_param }}
}
}
{%- endfor %}
@@ -56,11 +56,17 @@ func parse{{ o.go_prefix }}Options(opts ...With{{
o.go_prefix }}Fn) *{{ o.go_pri
}
return o
}
-{% if o.go_borrows %}
+{% if o.go_keep_alive %}
// newOpendal{{ o.go_prefix }}Options builds the C options from o. On error it
frees
+{%- if o.go_borrows %}
// them; otherwise the caller frees them. The C options borrow the returned
// bytes, so the caller keeps them alive until the C call that uses the
// options returns.
+{%- else %}
+// them; otherwise the caller frees them. The C setters copy the strings, and
+// the caller keeps the returned bytes alive until the C call that uses the
+// options returns.
+{%- endif %}
func newOpendal{{ o.go_prefix }}Options(ctx context.Context, o *{{
o.go_private }}) (*opendal{{ o.go_prefix }}Options, [][]byte, error) {
cOpts := ffi{{ o.go_prefix }}OptionsNew.symbol(ctx)()
var keepAlive [][]byte
@@ -81,12 +87,17 @@ func newOpendal{{ o.go_prefix }}Options(ctx
context.Context, o *{{ o.go_private
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, {{ "nil, " if o.go_borrows else "" }}err
+ return nil, {{ "nil, " if o.go_keep_alive else "" }}err
}
}
-{%- elif f.repr == "borrowed_string" %}
+{%- elif f.repr in ["owned_string_keep_alive", "borrowed_string"] %}
+{%- if f.repr == "owned_string_keep_alive" %}
+ if o.{{ f.go_field }} != nil {
+ data, err := {{ f.go_ffi }}.symbol(ctx)(cOpts, *o.{{ f.go_field
}})
+{%- else %}
if o.{{ f.go_field }} != "" {
data, err := {{ f.go_ffi }}.symbol(ctx)(cOpts, o.{{ f.go_field
}})
+{%- endif %}
if err != nil {
ffi{{ o.go_prefix }}OptionsFree.symbol(ctx)(cOpts)
return nil, nil, err
@@ -99,7 +110,7 @@ func newOpendal{{ o.go_prefix }}Options(ctx context.Context,
o *{{ o.go_private
}
{%- endif %}
{%- endfor %}
- return cOpts, {{ "keepAlive, " if o.go_borrows else "" }}nil
+ return cOpts, {{ "keepAlive, " if o.go_keep_alive else "" }}nil
}
var ffi{{ o.go_prefix }}OptionsNew = newDirectFFI[func() *opendal{{
o.go_prefix }}Options]("{{ o.c_name }}_new")
@@ -119,9 +130,14 @@ var {{ f.go_ffi }} = newFFI(
}
},
)
-{%- elif f.repr == "borrowed_string" %}
+{%- elif f.repr in ["owned_string_keep_alive", "borrowed_string"] %}
+{%- if f.repr == "owned_string_keep_alive" %}
+// {{ f.go_ffi }} returns the nul-terminated bytes that it passes to the C
+// setter, which copies them.
+{%- else %}
// {{ f.go_ffi }} returns the nul-terminated bytes that the C options keep a
// pointer to.
+{%- endif %}
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) ([]byte, error) {
diff --git a/dev/src/generate/c/options_rs.j2 b/dev/src/generate/c/options_rs.j2
index 362547728c..7a8f1b9a1b 100644
--- a/dev/src/generate/c/options_rs.j2
+++ b/dev/src/generate/c/options_rs.j2
@@ -58,7 +58,7 @@ impl {{ o.c_name }} {
opts: *mut {{ o.c_name }},
{{ f.name }}: {{ f.c_param_type }},
) {
-{%- if f.repr == "owned_string" %}
+{%- if f.repr in ["owned_string", "owned_string_keep_alive"] %}
if opts.is_null() {
return;
}
@@ -92,7 +92,7 @@ impl {{ o.c_name }} {
if !opts.is_null() {
{%- if o.owns_strings %}
let o = &mut *opts;
-{%- for f in o.fields if f.repr == "owned_string" %}
+{%- for f in o.fields if f.repr in ["owned_string", "owned_string_keep_alive"]
%}
if !o.{{ f.name }}.is_null() {
drop(CString::from_raw(o.{{ f.name }}));
o.{{ f.name }} = std::ptr::null_mut();
@@ -128,7 +128,7 @@ impl {{ o.c_name }} {
///
/// # Safety
///
-{%- for f in o.fields if f.repr in ["owned_string", "borrowed_string"] %}
+{%- for f in o.fields if f.repr in ["owned_string", "owned_string_keep_alive",
"borrowed_string"] %}
/// * A non-null `{{ f.name }}` must point to a readable, nul-terminated C
string
/// for the duration of the copy.
{%- endfor %}