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 9f07b06225 feat(bindings/cpp): generate WriteOptions from core (#9387)
9f07b06225 is described below
commit 9f07b06225094c59e8846362f2440555f878dc0d
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 23:54:20 2026 +0530
feat(bindings/cpp): generate WriteOptions from core (#9387)
* feat(bindings/cpp): generate WriteOptions from core
Generate the existing C++ `WriteOptions` from core's `WriteOptions`, as
#9331, #9361, #9366, #9378, and #9382 do for the other options structs.
The members keep their order, types, and default initializers.
`content_language`, `expires`, `if_version_match`,
`if_version_not_match`, `if_not_changed`, and `checksum` stay unexposed.
`user_metadata` crosses the bridge as one `OptionalStringMap`, so an
empty map stays a set value. The docs are core's full docs, with C++
names for `GetWriter`, `Writer::Write`, `Writer::Close`,
`Operator::Stat`, and `Operator::Write`. Nested list items keep their
indentation.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/cpp): generate WriteOptions from core
List `checksum` with the other core fields that C++ does not expose yet.
The core options parser skips it, so the generated `WriteOptions` conversion
comment left it out.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/cpp/include/data_structure.hpp | 18 --
bindings/cpp/include/options.hpp | 259 ++++++++++++++++++++++
bindings/cpp/src/lib.rs | 52 +----
bindings/cpp/src/operator.cpp | 36 +--
bindings/cpp/src/options.rs | 61 ++++++
bindings/cpp/src/options_test.rs | 100 ++++++++-
bindings/cpp/src/utils/options_converter.cpp | 30 +++
bindings/cpp/src/utils/options_converter.hpp | 1 +
bindings/cpp/tests/options_test.cpp | 266 +++++++++++++++++++++++
dev/src/generate/core_options.rs | 2 +-
dev/src/generate/cpp.rs | 302 ++++++++++++++++++++++++--
dev/src/generate/cpp/options_converter_cpp.j2 | 14 ++
dev/src/generate/cpp/options_hpp.j2 | 1 +
dev/src/generate/cpp/options_rs.j2 | 21 ++
14 files changed, 1045 insertions(+), 118 deletions(-)
diff --git a/bindings/cpp/include/data_structure.hpp
b/bindings/cpp/include/data_structure.hpp
index d3de91e4a5..8623fc908a 100644
--- a/bindings/cpp/include/data_structure.hpp
+++ b/bindings/cpp/include/data_structure.hpp
@@ -41,24 +41,6 @@ class Entry {
std::string path;
};
-/**
- * @struct WriteOptions
- * @brief Options for write and writer operations.
- */
-struct WriteOptions {
- bool append{false};
- std::optional<std::string> cache_control;
- std::optional<std::string> content_type;
- std::optional<std::string> content_disposition;
- std::optional<std::string> content_encoding;
- std::optional<std::unordered_map<std::string, std::string>> user_metadata;
- std::optional<std::string> if_match;
- std::optional<std::string> if_none_match;
- bool if_not_exists{false};
- std::size_t concurrent{0};
- std::optional<std::size_t> chunk;
-};
-
/**
* @struct CopyOptions
* @brief Options for copy operations.
diff --git a/bindings/cpp/include/options.hpp b/bindings/cpp/include/options.hpp
index f8cde743d3..896f0900c5 100644
--- a/bindings/cpp/include/options.hpp
+++ b/bindings/cpp/include/options.hpp
@@ -27,6 +27,7 @@
#include <cstdint>
#include <optional>
#include <string>
+#include <unordered_map>
namespace opendal {
@@ -475,4 +476,262 @@ struct ReaderOptions {
std::size_t prefetch{0};
};
+/**
+ * @struct WriteOptions
+ * @brief Options for write and writer operations.
+ */
+/// Each condition checks the file currently stored at the write path, and the
+/// service evaluates it atomically with the write's visible commit:
+///
+/// - A false condition fails the write with `ConditionNotMatch` and leaves the
+/// previously visible file unchanged. `opendal::Operator::GetWriter` does not
+/// access storage, so depending on the service, a check against the stored
file
+/// fails the returned writer's `opendal::Writer::Write` or
+/// `opendal::Writer::Close`.
+/// - A condition the service does not advertise through its capability fails
+/// the write with `Unsupported`; OpenDAL never silently drops a condition. A
+/// service that cannot preserve a combination of conditions also returns
+/// `Unsupported`.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// `Conflict`.
+///
+/// See the conditional operation specification for the complete
cross-operation
+/// contract.
+///
+/// When the operation fails with an error kind that these docs name, such as
+/// `ConditionNotMatch`, it throws a `std::exception` whose `what()` starts
with
+/// that kind.
+struct WriteOptions {
+ /// Sets append mode for this operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_can_append` before using this option.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, write operations overwrite existing files
+ /// - When append is set to true:
+ /// - New data will be appended to the end of existing file
+ /// - If file doesn't exist, it will be created
+ /// - If not supported, will return an error
+ ///
+ /// This operation allows adding data to existing files instead of
overwriting
+ /// them.
+ bool append{false};
+ /// Sets Cache-Control header for this write operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_with_cache_control` before using this
+ /// feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Cache-Control as system metadata on the target file
+ /// - The value should follow HTTP Cache-Control header format
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling caching behavior for the written
+ /// content.
+ ///
+ /// ### Use Cases
+ ///
+ /// - Setting browser cache duration
+ /// - Configuring CDN behavior
+ /// - Optimizing content delivery
+ /// - Managing cache invalidation
+ ///
+ /// ### References
+ ///
+ /// - [MDN
+ ///
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
+ /// - [RFC 7234 Section 5.2](https://tools.ietf.org/html/rfc7234#section-5.2)
+ std::optional<std::string> cache_control;
+ /// Sets `Content-Type` header for this write operation.
+ ///
+ /// ## Capability
+ ///
+ /// Check `opendal::Capability::write_with_content_type` before using this
+ /// feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Type as system metadata on the target file
+ /// - The value should follow MIME type format (e.g. "text/plain",
+ /// "image/jpeg")
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the media type of the content being
+ /// written.
+ std::optional<std::string> content_type;
+ /// Sets Content-Disposition header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_with_content_disposition` before using
+ /// this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Disposition as system metadata on the target
+ /// file
+ /// - The value should follow HTTP Content-Disposition header format
+ /// - Common values include:
+ /// - `inline` - Content displayed within browser
+ /// - `attachment` - Content downloaded as file
+ /// - `attachment; filename="example.jpg"` - Downloaded with specified
+ /// filename
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling how the content should be displayed or
+ /// downloaded.
+ std::optional<std::string> content_disposition;
+ /// Sets Content-Encoding header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_with_content_encoding` before using
this
+ /// feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Encoding as system metadata on the target
+ /// file
+ /// - The value should follow HTTP Content-Encoding header format
+ /// - Common values include:
+ /// - `gzip` - Content encoded using gzip compression
+ /// - `deflate` - Content encoded using deflate compression
+ /// - `br` - Content encoded using Brotli compression
+ /// - `identity` - No encoding applied (default value)
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the encoding applied to the content
being
+ /// written.
+ std::optional<std::string> content_encoding;
+ /// Sets user metadata for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_with_user_metadata` before using this
+ /// feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, the user metadata will be attached to the object during
+ /// write
+ /// - Accepts key-value pairs where both key and value are strings
+ /// - Some services, such as `s3`, return keys in lowercase
+ /// - Services may have limitations for user metadata, for example:
+ /// - Key length is typically limited (e.g., 1024 bytes)
+ /// - Value length is typically limited (e.g., 4096 bytes)
+ /// - Total metadata size might be limited
+ /// - Some characters might be forbidden in keys
+ /// - If not supported, the metadata will be ignored
+ ///
+ /// User metadata provides a way to attach custom metadata to objects during
+ /// write operations. A later `opendal::Operator::Stat` returns this metadata
+ /// when the service exposes user metadata.
+ std::optional<std::unordered_map<std::string, std::string>> user_metadata;
+ /// Write only when the file at the write path has this exact ETag.
+ ///
+ /// The condition succeeds when the file exists and its ETag equals this
+ /// value. A file with a different ETag, or a missing file, fails the write
+ /// with `ConditionNotMatch`. Only concrete ETag values are portable; a
+ /// wildcard such as `"*"` has no portable meaning here.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::write_with_if_match`.
+ std::optional<std::string> if_match;
+ /// Write only when the file at the write path does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file has a
+ /// different ETag or does not exist; the write then replaces or creates the
+ /// file. A file whose ETag equals this value fails the write with
+ /// `ConditionNotMatch`. Only concrete ETag values are portable; a wildcard
+ /// such as `"*"` has no portable meaning here.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::write_with_if_none_match`. Some services, such as
+ /// `s3`, support `if_not_exists` but not `if_none_match`; use
+ /// `WriteOptions::if_not_exists` when you only need to guard against an
+ /// existing file.
+ std::optional<std::string> if_none_match;
+ /// Write only when no file exists at the write path.
+ ///
+ /// The condition succeeds when the path is empty, so the write creates the
+ /// file. An existing file fails the write with `ConditionNotMatch`.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::write_with_if_not_exists`.
+ bool if_not_exists{false};
+ /// Sets concurrent write operations for this writer.
+ ///
+ /// ## Behavior
+ ///
+ /// - By default, OpenDAL writes files sequentially
+ /// - When concurrent is set:
+ /// - Multiple write operations can execute in parallel
+ /// - Write operations return immediately without waiting if tasks space
are
+ /// available
+ /// - Close operation ensures all writes complete in order
+ /// - Memory usage increases with concurrency level
+ /// - If not supported, falls back to sequential writes
+ ///
+ /// `opendal::Operator::Write` without `chunk` passes the whole buffer to the
+ /// service writer as one write. A service that splits the buffer internally,
+ /// such as `fs` with `direct_io` on Linux, can write the parts concurrently.
+ ///
+ /// This feature significantly improves performance when:
+ /// - Writing large files
+ /// - Network latency is high
+ /// - Storage service supports concurrent uploads like multipart uploads
+ ///
+ /// ## Performance Impact
+ ///
+ /// Setting appropriate concurrency can:
+ /// - Increase write throughput
+ /// - Reduce total write time
+ /// - Better utilize available bandwidth
+ /// - Trade memory for performance
+ std::size_t concurrent{0};
+ /// Sets chunk size for buffered writes.
+ ///
+ /// ### Capability
+ ///
+ /// Check `opendal::Capability::write_multi_min_size` and
+ /// `opendal::Capability::write_multi_max_size` for size limits.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, OpenDAL buffers data until it reaches the service's
+ /// `opendal::Capability::write_multi_min_size` and then writes everything
+ /// buffered at once; a service without that minimum receives each write as
it
+ /// arrives
+ /// - `0` has the same behavior as `std::nullopt`
+ /// - When chunk size is set:
+ /// - Data will be buffered until reaching chunk size
+ /// - Each chunk reaches the service writer as one write; a service may add
+ /// requests, such as the ones that start and complete an S3 multipart
+ /// upload
+ /// - Last chunk may be smaller than chunk size
+ /// - Important considerations:
+ /// - Some services require minimum chunk sizes, so OpenDAL raises a chunk
+ /// size below `opendal::Capability::write_multi_min_size` to that minimum
+ /// and lowers one above `opendal::Capability::write_multi_max_size` to
that
+ /// maximum
+ /// - Smaller chunks increase API calls and costs
+ /// - Larger chunks increase memory usage, but improve performance and
+ /// reduce costs
+ ///
+ /// ### Performance Impact
+ ///
+ /// Setting appropriate chunk size can:
+ /// - Reduce number of API calls
+ /// - Improve overall throughput
+ /// - Lower operation costs
+ /// - Better utilize network bandwidth
+ std::optional<std::size_t> chunk;
+};
+
} // namespace opendal
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index 73080c039f..4f21be3df5 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -67,21 +67,6 @@ mod ffi {
value: usize,
}
- struct FfiWriteOptions {
- append: bool,
- cache_control: OptionalString,
- content_type: OptionalString,
- content_disposition: OptionalString,
- content_encoding: OptionalString,
- has_user_metadata: bool,
- user_metadata: Vec<HashMapValue>,
- if_match: OptionalString,
- if_none_match: OptionalString,
- if_not_exists: bool,
- concurrent: usize,
- chunk: OptionalUsize,
- }
-
struct FfiCopyOptions {
if_not_exists: bool,
if_match: OptionalString,
@@ -142,6 +127,8 @@ mod ffi {
type FfiReadOptions = crate::options::ffi::FfiReadOptions;
#[namespace = "opendal::ffi::options"]
type FfiReaderOptions = crate::options::ffi::FfiReaderOptions;
+ #[namespace = "opendal::ffi::options"]
+ type FfiWriteOptions = crate::options::ffi::FfiWriteOptions;
}
extern "Rust" {
@@ -339,35 +326,6 @@ fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
v.has_value.then_some(v.value)
}
-fn user_metadata(
- has_value: bool,
- values: Vec<ffi::HashMapValue>,
-) -> Option<HashMap<String, String>> {
- has_value.then(|| {
- values
- .into_iter()
- .map(|value| (value.key, value.value))
- .collect()
- })
-}
-
-fn write_options(opts: ffi::FfiWriteOptions) -> od::options::WriteOptions {
- od::options::WriteOptions {
- append: opts.append,
- cache_control: optional_string(opts.cache_control),
- content_type: optional_string(opts.content_type),
- content_disposition: optional_string(opts.content_disposition),
- content_encoding: optional_string(opts.content_encoding),
- user_metadata: user_metadata(opts.has_user_metadata,
opts.user_metadata),
- if_match: optional_string(opts.if_match),
- if_none_match: optional_string(opts.if_none_match),
- if_not_exists: opts.if_not_exists,
- concurrent: opts.concurrent,
- chunk: optional_usize(opts.chunk),
- ..Default::default()
- }
-}
-
fn copy_options(opts: ffi::FfiCopyOptions) -> od::options::CopyOptions {
od::options::CopyOptions {
if_not_exists: opts.if_not_exists,
@@ -402,7 +360,7 @@ impl Operator {
fn write_options(&self, path: &str, bs: &[u8], opts: ffi::FfiWriteOptions)
-> Result<()> {
Ok(self
.0
- .write_options(path, bs.to_vec(), write_options(opts))
+ .write_options(path, bs.to_vec(), opts.into())
.map(|_| ())?)
}
@@ -514,9 +472,7 @@ impl Operator {
}
fn writer_options(&self, path: &str, opts: ffi::FfiWriteOptions) ->
Result<*mut Writer> {
- let writer = Box::into_raw(Box::new(Writer(
- self.0.writer_options(path, write_options(opts))?,
- )));
+ let writer = Box::into_raw(Box::new(Writer(self.0.writer_options(path,
opts.into())?)));
Ok(writer)
}
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index c89b619736..af41dd7fc7 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -54,36 +54,6 @@ ffi::OptionalUsize ToFfiOptionalUsize(const
std::optional<std::size_t> &value) {
return ffi::OptionalUsize{false, 0};
}
-rust::Vec<ffi::HashMapValue> ToFfiHashMap(
- const std::unordered_map<std::string, std::string> &map) {
- rust::Vec<ffi::HashMapValue> values;
- values.reserve(map.size());
- for (const auto &[key, value] : map) {
- values.push_back({utils::rust_string(key), utils::rust_string(value)});
- }
- return values;
-}
-
-ffi::FfiWriteOptions ToFfiOptions(const WriteOptions &options) {
- auto metadata = options.user_metadata.has_value()
- ? ToFfiHashMap(*options.user_metadata)
- : rust::Vec<ffi::HashMapValue>();
- return ffi::FfiWriteOptions{
- options.append,
- ToFfiOptionalString(options.cache_control),
- ToFfiOptionalString(options.content_type),
- ToFfiOptionalString(options.content_disposition),
- ToFfiOptionalString(options.content_encoding),
- options.user_metadata.has_value(),
- std::move(metadata),
- ToFfiOptionalString(options.if_match),
- ToFfiOptionalString(options.if_none_match),
- options.if_not_exists,
- options.concurrent,
- ToFfiOptionalUsize(options.chunk),
- };
-}
-
ffi::FfiCopyOptions ToFfiOptions(const CopyOptions &options) {
return ffi::FfiCopyOptions{
options.if_not_exists,
@@ -181,7 +151,7 @@ void Operator::Write(std::string_view path,
std::string_view data,
const WriteOptions &options) {
CheckedOperator(operator_).write_options(
utils::rust_str(path), utils::rust_slice<const uint8_t>(data),
- ToFfiOptions(options));
+ utils::ToFfiOptions(options));
}
bool Operator::Exists(std::string_view path) {
@@ -293,8 +263,8 @@ Writer Operator::GetWriter(std::string_view path) {
}
Writer Operator::GetWriter(std::string_view path, const WriteOptions &options)
{
- return CheckedOperator(operator_).writer_options(utils::rust_str(path),
- ToFfiOptions(options));
+ return CheckedOperator(operator_).writer_options(
+ utils::rust_str(path), utils::ToFfiOptions(options));
}
Capability Operator::Info() {
diff --git a/bindings/cpp/src/options.rs b/bindings/cpp/src/options.rs
index aedd5b0cc4..43574108e9 100644
--- a/bindings/cpp/src/options.rs
+++ b/bindings/cpp/src/options.rs
@@ -45,6 +45,16 @@ pub mod ffi {
nanoseconds: u32,
}
+ struct HashMapValue {
+ key: String,
+ value: String,
+ }
+
+ struct OptionalStringMap {
+ has_value: bool,
+ value: Vec<HashMapValue>,
+ }
+
/// A C++ `ReadRange`, whose `kind` is its `ReadRange::Type`.
struct FfiBytesRange {
kind: u8,
@@ -104,6 +114,20 @@ pub mod ffi {
gap: OptionalUsize,
prefetch: usize,
}
+
+ struct FfiWriteOptions {
+ append: bool,
+ cache_control: OptionalString,
+ content_type: OptionalString,
+ content_disposition: OptionalString,
+ content_encoding: OptionalString,
+ user_metadata: OptionalStringMap,
+ if_match: OptionalString,
+ if_none_match: OptionalString,
+ if_not_exists: bool,
+ concurrent: usize,
+ chunk: OptionalUsize,
+ }
}
fn optional_string(v: ffi::OptionalString) -> Option<String> {
@@ -131,6 +155,17 @@ fn optional_timestamp(
}
}
+fn optional_string_map(
+ v: ffi::OptionalStringMap,
+) -> Option<std::collections::HashMap<String, String>> {
+ v.has_value.then(|| {
+ v.value
+ .into_iter()
+ .map(|entry| (entry.key, entry.value))
+ .collect()
+ })
+}
+
fn bytes_range(v: ffi::FfiBytesRange) -> opendal::BytesRange {
match v.kind {
1 => opendal::BytesRange::new(v.start, None),
@@ -244,3 +279,29 @@ impl TryFrom<ffi::FfiReaderOptions> for
opendal::options::ReaderOptions {
})
}
}
+
+impl From<ffi::FfiWriteOptions> for opendal::options::WriteOptions {
+ fn from(opts: ffi::FfiWriteOptions) -> Self {
+ Self {
+ append: opts.append,
+ cache_control: optional_string(opts.cache_control),
+ content_type: optional_string(opts.content_type),
+ content_disposition: optional_string(opts.content_disposition),
+ content_encoding: optional_string(opts.content_encoding),
+ user_metadata: optional_string_map(opts.user_metadata),
+ if_match: optional_string(opts.if_match),
+ if_none_match: optional_string(opts.if_none_match),
+ if_not_exists: opts.if_not_exists,
+ concurrent: opts.concurrent,
+ chunk: optional_usize(opts.chunk),
+ // Not exposed in C++ yet:
+ // - `content_language`
+ // - `expires`
+ // - `if_version_match`
+ // - `if_version_not_match`
+ // - `if_not_changed`
+ // - `checksum`
+ ..Default::default()
+ }
+ }
+}
diff --git a/bindings/cpp/src/options_test.rs b/bindings/cpp/src/options_test.rs
index 2be040b8c5..b8067850d5 100644
--- a/bindings/cpp/src/options_test.rs
+++ b/bindings/cpp/src/options_test.rs
@@ -16,9 +16,11 @@
// under the License.
//! The generated `ListOptions`, `StatOptions`, `DeleteOptions`,
-//! `ReadOptions`, and `ReaderOptions` conversions in `options.rs` carry every
-//! bridge field to the core field of the same name, and absent values stay
-//! absent.
+//! `ReadOptions`, `ReaderOptions`, and `WriteOptions` conversions in
+//! `options.rs` carry every bridge field to the core field of the same name,
+//! and absent values stay absent.
+
+use std::collections::HashMap;
use opendal::BytesRange;
use opendal::options::DeleteOptions;
@@ -26,6 +28,7 @@ use opendal::options::ListOptions;
use opendal::options::ReadOptions;
use opendal::options::ReaderOptions;
use opendal::options::StatOptions;
+use opendal::options::WriteOptions;
use opendal::raw::Timestamp;
use crate::options::ffi;
@@ -440,3 +443,94 @@ fn test_reader_options_reject_out_of_range_timestamps() {
);
}
}
+
+fn bridge_string_map(entries: Option<&[(&str, &str)]>) ->
ffi::OptionalStringMap {
+ ffi::OptionalStringMap {
+ has_value: entries.is_some(),
+ value: entries
+ .unwrap_or(&[("ignored", "ignored")])
+ .iter()
+ .map(|&(key, value)| ffi::HashMapValue {
+ key: key.to_string(),
+ value: value.to_string(),
+ })
+ .collect(),
+ }
+}
+
+fn absent_write_options() -> ffi::FfiWriteOptions {
+ ffi::FfiWriteOptions {
+ append: false,
+ cache_control: bridge_string(None),
+ content_type: bridge_string(None),
+ content_disposition: bridge_string(None),
+ content_encoding: bridge_string(None),
+ user_metadata: bridge_string_map(None),
+ if_match: bridge_string(None),
+ if_none_match: bridge_string(None),
+ if_not_exists: false,
+ concurrent: 0,
+ chunk: bridge_usize(None),
+ }
+}
+
+#[test]
+fn test_write_options_carry_every_field() {
+ let opts = ffi::FfiWriteOptions {
+ append: true,
+ cache_control: bridge_string(Some("cache_control")),
+ content_type: bridge_string(Some("content_type")),
+ content_disposition: bridge_string(Some("content_disposition")),
+ content_encoding: bridge_string(Some("content_encoding")),
+ user_metadata: bridge_string_map(Some(&[("owner", "cpp"), ("Key",
"Value")])),
+ if_match: bridge_string(Some("if_match")),
+ if_none_match: bridge_string(Some("if_none_match")),
+ if_not_exists: true,
+ concurrent: 4,
+ chunk: bridge_usize(Some(16)),
+ };
+
+ // The options that C++ does not expose keep their core defaults, as on
+ // `main`.
+ let expected = WriteOptions {
+ append: true,
+ cache_control: Some("cache_control".to_string()),
+ content_type: Some("content_type".to_string()),
+ content_disposition: Some("content_disposition".to_string()),
+ content_encoding: Some("content_encoding".to_string()),
+ user_metadata: Some(HashMap::from([
+ ("owner".to_string(), "cpp".to_string()),
+ ("Key".to_string(), "Value".to_string()),
+ ])),
+ if_match: Some("if_match".to_string()),
+ if_none_match: Some("if_none_match".to_string()),
+ if_not_exists: true,
+ concurrent: 4,
+ chunk: Some(16),
+ ..Default::default()
+ };
+ assert_eq!(WriteOptions::from(opts), expected);
+}
+
+#[test]
+fn test_write_options_keep_explicit_empty_values() {
+ // An empty map and a zero chunk are set values, as on `main`.
+ let opts = ffi::FfiWriteOptions {
+ user_metadata: bridge_string_map(Some(&[])),
+ chunk: bridge_usize(Some(0)),
+ ..absent_write_options()
+ };
+
+ let options = WriteOptions::from(opts);
+ assert_eq!(options.user_metadata, Some(HashMap::new()));
+ assert_eq!(options.chunk, Some(0));
+}
+
+#[test]
+fn test_write_options_keep_absent_values_absent() {
+ // C++ sends a value behind `has_value == false`; it must not reach core.
+ assert_eq!(
+ WriteOptions::from(absent_write_options()),
+ WriteOptions::default()
+ );
+}
diff --git a/bindings/cpp/src/utils/options_converter.cpp
b/bindings/cpp/src/utils/options_converter.cpp
index 75054b11cb..5fb31bd7fe 100644
--- a/bindings/cpp/src/utils/options_converter.cpp
+++ b/bindings/cpp/src/utils/options_converter.cpp
@@ -27,6 +27,8 @@
#include <cstdint>
#include <optional>
#include <string>
+#include <unordered_map>
+#include <utility>
#include "utils/rust_converter.hpp"
@@ -81,6 +83,18 @@ ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
static_cast<std::uint32_t>(nanoseconds)};
}
+ffi::options::OptionalStringMap ToFfiOptionalStringMap(
+ const std::optional<std::unordered_map<std::string, std::string>> &value) {
+ rust::Vec<ffi::options::HashMapValue> values;
+ if (value.has_value()) {
+ values.reserve(value->size());
+ for (const auto &[key, item] : *value) {
+ values.push_back({rust_string(key), rust_string(item)});
+ }
+ }
+ return ffi::options::OptionalStringMap{value.has_value(), std::move(values)};
+}
+
ffi::options::FfiBytesRange ToFfiBytesRange(const ReadRange &range) {
return ffi::options::FfiBytesRange{static_cast<std::uint8_t>(range.type),
range.start, range.end};
@@ -151,4 +165,20 @@ ffi::options::FfiReaderOptions ToFfiOptions(const
ReaderOptions &options) {
};
}
+ffi::options::FfiWriteOptions ToFfiOptions(const WriteOptions &options) {
+ return ffi::options::FfiWriteOptions{
+ options.append,
+ ToFfiOptionalString(options.cache_control),
+ ToFfiOptionalString(options.content_type),
+ ToFfiOptionalString(options.content_disposition),
+ ToFfiOptionalString(options.content_encoding),
+ ToFfiOptionalStringMap(options.user_metadata),
+ ToFfiOptionalString(options.if_match),
+ ToFfiOptionalString(options.if_none_match),
+ options.if_not_exists,
+ options.concurrent,
+ ToFfiOptionalUsize(options.chunk),
+ };
+}
+
} // namespace opendal::utils
diff --git a/bindings/cpp/src/utils/options_converter.hpp
b/bindings/cpp/src/utils/options_converter.hpp
index bab5c53d3f..2046399a21 100644
--- a/bindings/cpp/src/utils/options_converter.hpp
+++ b/bindings/cpp/src/utils/options_converter.hpp
@@ -32,5 +32,6 @@ ffi::options::FfiStatOptions ToFfiOptions(const StatOptions
&options);
ffi::options::FfiDeleteOptions ToFfiOptions(const DeleteOptions &options);
ffi::options::FfiReadOptions ToFfiOptions(const ReadOptions &options);
ffi::options::FfiReaderOptions ToFfiOptions(const ReaderOptions &options);
+ffi::options::FfiWriteOptions ToFfiOptions(const WriteOptions &options);
} // namespace opendal::utils
diff --git a/bindings/cpp/tests/options_test.cpp
b/bindings/cpp/tests/options_test.cpp
index 3f6730633b..bbd3684877 100644
--- a/bindings/cpp/tests/options_test.cpp
+++ b/bindings/cpp/tests/options_test.cpp
@@ -24,9 +24,11 @@
#include <exception>
#include <filesystem>
#include <ios>
+#include <map>
#include <optional>
#include <string>
#include <system_error>
+#include <unordered_map>
#include <utility>
#include "gmock/gmock.h"
@@ -889,3 +891,267 @@ TEST(OptionsTest,
ReaderOptionsStatNeedsStatCapabilityOnFs) {
EXPECT_THAT([&] { ReadToEnd(unmodified); },
ThrowsMessage<std::exception>(StartsWith("ConditionNotMatch")));
}
+
+TEST(OptionsTest, WriteOptionsPositionalInitializerReachesBridge) {
+ // Every member in the order `data_structure.hpp` declared them before
+ // `WriteOptions` was generated.
+ const opendal::WriteOptions options{
+ /*append=*/true,
+ /*cache_control=*/"cache_control",
+ /*content_type=*/"content_type",
+ /*content_disposition=*/"content_disposition",
+ /*content_encoding=*/"content_encoding",
+ /*user_metadata=*/
+ std::unordered_map<std::string, std::string>{{"owner", "cpp"},
+ {"Key", "Value"}},
+ /*if_match=*/"if_match",
+ /*if_none_match=*/"if_none_match",
+ /*if_not_exists=*/true,
+ /*concurrent=*/4,
+ /*chunk=*/16,
+ };
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_TRUE(ffi.append);
+ EXPECT_TRUE(ffi.cache_control.has_value);
+ EXPECT_EQ(std::string(ffi.cache_control.value), "cache_control");
+ EXPECT_TRUE(ffi.content_type.has_value);
+ EXPECT_EQ(std::string(ffi.content_type.value), "content_type");
+ EXPECT_TRUE(ffi.content_disposition.has_value);
+ EXPECT_EQ(std::string(ffi.content_disposition.value), "content_disposition");
+ EXPECT_TRUE(ffi.content_encoding.has_value);
+ EXPECT_EQ(std::string(ffi.content_encoding.value), "content_encoding");
+ EXPECT_TRUE(ffi.user_metadata.has_value);
+ std::map<std::string, std::string> user_metadata;
+ for (const auto &entry : ffi.user_metadata.value) {
+ user_metadata.emplace(std::string(entry.key), std::string(entry.value));
+ }
+ const std::map<std::string, std::string> expected{{"owner", "cpp"},
+ {"Key", "Value"}};
+ EXPECT_EQ(user_metadata, expected);
+ EXPECT_EQ(ffi.user_metadata.value.size(), expected.size());
+ EXPECT_TRUE(ffi.if_match.has_value);
+ EXPECT_EQ(std::string(ffi.if_match.value), "if_match");
+ EXPECT_TRUE(ffi.if_none_match.has_value);
+ EXPECT_EQ(std::string(ffi.if_none_match.value), "if_none_match");
+ EXPECT_TRUE(ffi.if_not_exists);
+ EXPECT_EQ(ffi.concurrent, std::size_t{4});
+ EXPECT_TRUE(ffi.chunk.has_value);
+ EXPECT_EQ(ffi.chunk.value, std::size_t{16});
+}
+
+TEST(OptionsTest, WriteOptionsStructuredBindingsKeepMemberOrder) {
+ opendal::WriteOptions options;
+ auto &[append, cache_control, content_type, content_disposition,
+ content_encoding, user_metadata, if_match, if_none_match,
+ if_not_exists, concurrent, chunk] = options;
+
+ EXPECT_EQ(&append, &options.append);
+ EXPECT_EQ(&cache_control, &options.cache_control);
+ EXPECT_EQ(&content_type, &options.content_type);
+ EXPECT_EQ(&content_disposition, &options.content_disposition);
+ EXPECT_EQ(&content_encoding, &options.content_encoding);
+ EXPECT_EQ(&user_metadata, &options.user_metadata);
+ EXPECT_EQ(&if_match, &options.if_match);
+ EXPECT_EQ(&if_none_match, &options.if_none_match);
+ EXPECT_EQ(&if_not_exists, &options.if_not_exists);
+ EXPECT_EQ(&concurrent, &options.concurrent);
+ EXPECT_EQ(&chunk, &options.chunk);
+}
+
+TEST(OptionsTest, DefaultWriteOptionsReachBridgeAbsent) {
+ const opendal::WriteOptions options;
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_FALSE(ffi.append);
+ EXPECT_FALSE(ffi.cache_control.has_value);
+ EXPECT_FALSE(ffi.content_type.has_value);
+ EXPECT_FALSE(ffi.content_disposition.has_value);
+ EXPECT_FALSE(ffi.content_encoding.has_value);
+ EXPECT_FALSE(ffi.user_metadata.has_value);
+ EXPECT_TRUE(ffi.user_metadata.value.empty());
+ EXPECT_FALSE(ffi.if_match.has_value);
+ EXPECT_FALSE(ffi.if_none_match.has_value);
+ EXPECT_FALSE(ffi.if_not_exists);
+ EXPECT_EQ(ffi.concurrent, std::size_t{0});
+ EXPECT_FALSE(ffi.chunk.has_value);
+}
+
+TEST(OptionsTest, WriteOptionsSucceedOnMemory) {
+ opendal::Operator op("memory");
+
+ opendal::WriteOptions headers;
+ headers.cache_control = "max-age=60";
+ headers.content_type = "text/plain";
+ headers.content_disposition = "inline";
+ headers.content_encoding = "identity";
+ headers.user_metadata =
+ std::unordered_map<std::string, std::string>{{"owner", "cpp"}};
+ opendal::WriteOptions if_not_exists;
+ if_not_exists.if_not_exists = true;
+ opendal::WriteOptions chunked;
+ chunked.concurrent = 2;
+ chunked.chunk = 3;
+ opendal::WriteOptions no_chunk;
+ no_chunk.concurrent = 2;
+ no_chunk.chunk = 0;
+ const std::pair<std::string, opendal::WriteOptions> cases[] = {
+ {"default", opendal::WriteOptions{}},
+ {"headers", headers},
+ {"if_not_exists", if_not_exists},
+ {"chunked", chunked},
+ {"no_chunk", no_chunk},
+ };
+ for (const auto &item : cases) {
+ op.Write("write_" + item.first, "0123456789", item.second);
+ auto writer = op.GetWriter("writer_" + item.first, item.second);
+ writer.Write("01234");
+ writer.Write("56789");
+ writer.Close();
+ for (const auto &path : {"write_" + item.first, "writer_" + item.first}) {
+ EXPECT_EQ(op.Read(path), "0123456789") << path;
+ }
+ }
+
+ for (const auto &path : {"write_headers", "writer_headers"}) {
+ const auto metadata = op.Stat(path);
+ EXPECT_EQ(metadata.cache_control, "max-age=60") << path;
+ EXPECT_EQ(metadata.content_type, "text/plain") << path;
+ EXPECT_EQ(metadata.content_disposition, "inline") << path;
+ EXPECT_EQ(metadata.content_encoding, "identity") << path;
+ const std::unordered_map<std::string, std::string> expected{
+ {"owner", "cpp"}};
+ EXPECT_EQ(metadata.user_metadata, expected) << path;
+ }
+
+ // On `memory`, an empty map stays a set value, while `std::nullopt` sets
+ // no user metadata.
+ opendal::WriteOptions empty;
+ empty.user_metadata = std::unordered_map<std::string, std::string>{};
+ op.Write("write_empty_metadata", "data", empty);
+ const auto empty_metadata = op.Stat("write_empty_metadata").user_metadata;
+ ASSERT_TRUE(empty_metadata.has_value());
+ EXPECT_TRUE(empty_metadata->empty());
+ EXPECT_EQ(op.Stat("write_default").user_metadata, std::nullopt);
+}
+
+TEST(OptionsTest, WriteOptionsErrorsStartWithErrorKind) {
+ using ::testing::AllOf;
+ using ::testing::HasSubstr;
+ using ::testing::StartsWith;
+ using ::testing::ThrowsMessage;
+
+ opendal::Operator op("memory");
+ op.Write("write_errors", "hello");
+
+ // `memory` supports none of these, so each one fails before the write
+ // reaches storage.
+ const auto info = op.Info();
+ ASSERT_FALSE(info.write_can_append);
+ ASSERT_FALSE(info.write_with_if_match);
+ ASSERT_FALSE(info.write_with_if_none_match);
+ opendal::WriteOptions append;
+ append.append = true;
+ opendal::WriteOptions if_match;
+ if_match.if_match = "\"etag\"";
+ opendal::WriteOptions if_none_match;
+ if_none_match.if_none_match = "\"etag\"";
+ const std::pair<std::string, opendal::WriteOptions> cases[] = {
+ {"append", append},
+ {"if_match", if_match},
+ {"if_none_match", if_none_match},
+ };
+ for (const auto &item : cases) {
+ for (const char *path : {"write_errors", "write_errors_missing"}) {
+ const auto unsupported = ThrowsMessage<std::exception>(
+ AllOf(StartsWith("Unsupported"),
+ HasSubstr("with the arguments " + item.first + ".")));
+ EXPECT_THAT([&] { op.Write(path, "data", item.second); }, unsupported)
+ << item.first << " on " << path;
+ EXPECT_THAT([&] { op.GetWriter(path, item.second); }, unsupported)
+ << item.first << " on " << path;
+ }
+ }
+ EXPECT_EQ(op.Read("write_errors"), "hello");
+ EXPECT_FALSE(op.Exists("write_errors_missing"));
+
+ // A false condition fails the write and leaves the file unchanged. On
+ // `memory`, a writer reports it when it closes.
+ ASSERT_TRUE(info.write_with_if_not_exists);
+ opendal::WriteOptions if_not_exists;
+ if_not_exists.if_not_exists = true;
+ const auto condition_not_match =
+ ThrowsMessage<std::exception>(StartsWith("ConditionNotMatch"));
+ EXPECT_THAT([&] { op.Write("write_errors", "data", if_not_exists); },
+ condition_not_match);
+ auto writer = op.GetWriter("write_errors", if_not_exists);
+ writer.Write("data");
+ EXPECT_THAT([&] { writer.Close(); }, condition_not_match);
+ EXPECT_EQ(op.Read("write_errors"), "hello");
+}
+
+TEST(OptionsTest, WriteOptionsWithoutCapabilityAreIgnored) {
+ // `dashmap` cannot store user metadata, and `fs` stores none of these
+ // headers, so each write succeeds without them.
+ ReaderOptionsTempDir dir;
+ opendal::Operator dashmap("dashmap");
+ opendal::Operator fs("fs", {{"root", dir.path()}});
+ ASSERT_FALSE(dashmap.Info().write_with_user_metadata);
+ const auto info = fs.Info();
+ ASSERT_FALSE(info.write_with_cache_control || info.write_with_content_type ||
+ info.write_with_content_disposition ||
+ info.write_with_content_encoding);
+
+ opendal::WriteOptions user_metadata;
+ user_metadata.user_metadata =
+ std::unordered_map<std::string, std::string>{{"owner", "cpp"}};
+ dashmap.Write("ignored", "data", user_metadata);
+ EXPECT_EQ(dashmap.Read("ignored"), "data");
+ EXPECT_EQ(dashmap.Stat("ignored").user_metadata, std::nullopt);
+
+ opendal::WriteOptions headers;
+ headers.cache_control = "max-age=60";
+ headers.content_type = "text/plain";
+ headers.content_disposition = "inline";
+ headers.content_encoding = "identity";
+ fs.Write("ignored", "data", headers);
+ EXPECT_EQ(fs.Read("ignored"), "data");
+ const auto metadata = fs.Stat("ignored");
+ EXPECT_EQ(metadata.cache_control, std::nullopt);
+ EXPECT_EQ(metadata.content_type, std::nullopt);
+ EXPECT_EQ(metadata.content_disposition, std::nullopt);
+ EXPECT_EQ(metadata.content_encoding, std::nullopt);
+}
+
+TEST(OptionsTest, WriteOptionsAppendAndConditionOnFs) {
+ using ::testing::StartsWith;
+ using ::testing::ThrowsMessage;
+
+ ReaderOptionsTempDir dir;
+ opendal::Operator op("fs", {{"root", dir.path()}});
+ ASSERT_TRUE(op.Info().write_can_append);
+
+ // Appending to a missing file creates it.
+ opendal::WriteOptions append;
+ append.append = true;
+ op.Write("append", "hello", append);
+ auto writer = op.GetWriter("append", append);
+ writer.Write(" world");
+ writer.Close();
+ EXPECT_EQ(op.Read("append"), "hello world");
+
+ // Creating a writer does not check the condition; writing or closing it
+ // does.
+ opendal::WriteOptions if_not_exists;
+ if_not_exists.if_not_exists = true;
+ auto existing = op.GetWriter("append", if_not_exists);
+ EXPECT_THAT(
+ [&] {
+ existing.Write("data");
+ existing.Close();
+ },
+ ThrowsMessage<std::exception>(StartsWith("ConditionNotMatch")));
+ EXPECT_EQ(op.Read("append"), "hello world");
+}
diff --git a/dev/src/generate/core_options.rs b/dev/src/generate/core_options.rs
index 4604056799..a6a59afb8f 100644
--- a/dev/src/generate/core_options.rs
+++ b/dev/src/generate/core_options.rs
@@ -104,7 +104,7 @@ pub fn parse(path: &Path) -> Result<Vec<OptionsStruct>> {
}
/// Option fields whose types bindings do not mirror yet, as `(struct, field)`.
-const NOT_MIRRORED: &[(&str, &str)] = &[("WriteOptions", "checksum")];
+pub const NOT_MIRRORED: &[(&str, &str)] = &[("WriteOptions", "checksum")];
fn parse_struct(struct_: &ItemStruct) -> Result<OptionsStruct> {
let name = struct_.ident.to_string();
diff --git a/dev/src/generate/cpp.rs b/dev/src/generate/cpp.rs
index 7e0a3685bd..b77cdebdd8 100644
--- a/dev/src/generate/cpp.rs
+++ b/dev/src/generate/cpp.rs
@@ -565,8 +565,8 @@ struct OptionsSpec {
cpp_rewrites: &'static [(&'static str, &'static str)],
}
-/// Options structs generated into `include/options.hpp`. The other options
-/// structs are still hand-written in `include/data_structure.hpp`.
+/// Options structs generated into `include/options.hpp`. `CopyOptions` and
+/// `RenameOptions` are still hand-written in `include/data_structure.hpp`.
const OPTIONS: &[OptionsSpec] = {
use OptionKind::*;
@@ -777,6 +777,51 @@ const OPTIONS: &[OptionsSpec] = {
),
],
},
+ OptionsSpec {
+ name: "WriteOptions",
+ brief: "Options for write and writer operations.",
+ fields: &[
+ ("append", Bool),
+ ("cache_control", OptionString),
+ ("content_type", OptionString),
+ ("content_disposition", OptionString),
+ ("content_encoding", OptionString),
+ ("user_metadata", OptionStringMap),
+ ("if_match", OptionString),
+ ("if_none_match", OptionString),
+ ("if_not_exists", Bool),
+ ("concurrent", Usize),
+ ("chunk", OptionUsize),
+ ],
+ cpp_doc: &[],
+ cpp_member_docs: &[],
+ // C++ has no `if_not_changed`, `if_version_match`, or reader
+ // metadata, and `Operator::Write` is its one-shot write.
+ cpp_rewrites: &[
+ (
+ "Creating a writer does not access storage, so depending
on the service, \
+ a check against the stored file fails while writing or
when closing the \
+ writer. Combining `if_not_changed` with a conflicting
`if_match` or \
+ `if_version_match` fails before the writer exists,
without accessing \
+ storage.",
+ "`opendal::Operator::GetWriter` does not access storage,
so depending on \
+ the service, a check against the stored file fails the
returned \
+ writer's `opendal::Writer::Write` or
`opendal::Writer::Close`.",
+ ),
+ (
+ "A later stat returns this metadata when the service
exposes user metadata. \
+ [`crate::Reader::metadata`] may omit it, for example on
`fs`.",
+ "A later `opendal::Operator::Stat` returns this metadata
when the service \
+ exposes user metadata.",
+ ),
+ (
+ "[`crate::Operator::write_with`] and
[`crate::Operator::write_options`] \
+ without `chunk` pass the whole buffer to the service
writer as one write.",
+ "`opendal::Operator::Write` without `chunk` passes the
whole buffer to the \
+ service writer as one write.",
+ ),
+ ],
+ },
]
};
@@ -918,6 +963,14 @@ fn option_member(
format!("ToFfiOptionalTimestamp({member})"),
format!("optional_timestamp({bridge_field})?"),
),
+ // An empty map stays a set value, distinct from `std::nullopt`.
+ OptionKind::OptionStringMap => (
+ "std::optional<std::unordered_map<std::string, std::string>>",
+ "",
+ "OptionalStringMap",
+ format!("ToFfiOptionalStringMap({member})"),
+ format!("optional_string_map({bridge_field})"),
+ ),
_ => bail!("the C++ bridge cannot carry `{options}::{name}` of kind
{kind:?} yet"),
};
Ok(OptionMember {
@@ -935,7 +988,8 @@ fn option_member(
/// `prefix` in the C++ header.
///
/// - Each paragraph, heading, and list item is wrapped to fit the comment
-/// lines. An empty line separates paragraphs, as in core.
+/// lines. An empty line separates paragraphs, as in core. A nested list
+/// item keeps its indentation on each of its lines.
/// - Rustdoc links become plain code spans, and reference-style links to
/// crate items keep their text, because Doxygen cannot resolve Rust paths:
/// ``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
@@ -975,7 +1029,14 @@ fn option_doc_lines(doc: &[String], prefix: &str, names:
&CppNames) -> Vec<Strin
if text.ends_with('\\') {
text.push_str("<!---->");
}
- lines.extend(wrap_doc(&text, prefix, HPP_COLUMN_LIMIT));
+ // A nested list item and its wrapped lines keep the item's
+ // indentation, which Doxygen reads as nesting.
+ let indent = &text[..text.len() - text.trim_start().len()];
+ lines.extend(
+ wrap_doc(&text, &format!("{prefix}{indent}"), HPP_COLUMN_LIMIT)
+ .into_iter()
+ .map(|line| format!("{indent}{line}")),
+ );
}
lines
}
@@ -988,23 +1049,31 @@ const PERFORMANCE_GUIDE: &str = "Refer to the \
/// The Markdown blocks of a core doc comment: each paragraph, heading, and
/// list item with its lines joined, and whether a blank line precedes it in
/// core.
+///
+/// A list item keeps the indentation that core's doc lines give it, so a
+/// nested item stays nested.
fn doc_blocks(doc: &[String]) -> Vec<(bool, String)> {
let mut blocks: Vec<(bool, String)> = Vec::new();
let mut after_blank = false;
let mut continues = false;
- for line in doc {
- let line = line.trim();
+ for raw in doc {
+ let line = raw.trim();
if line.is_empty() {
after_blank = !blocks.is_empty();
continues = false;
continue;
}
let heading = line.starts_with('#');
+ let item = line.starts_with("- ");
match blocks.last_mut() {
- Some((_, text)) if continues && !heading && !line.starts_with("-
") => {
+ Some((_, text)) if continues && !heading && !item => {
text.push(' ');
text.push_str(line);
}
+ _ if item => {
+ let indent = raw.len() - raw.trim_start().len();
+ blocks.push((after_blank, format!("{}{line}",
&raw[..indent])));
+ }
_ => blocks.push((after_blank, line.to_string())),
}
after_blank = false;
@@ -1267,6 +1336,12 @@ fn options_models(
.iter()
.filter(|f| !spec.fields.iter().any(|(listed, _)| *listed ==
f.name))
.map(|f| f.name.clone())
+ .chain(
+ core_options::NOT_MIRRORED
+ .iter()
+ .filter(|(options, _)| *options == spec.name)
+ .map(|(_, name)| name.to_string()),
+ )
.collect();
models.push(OptionsModel {
name: spec.name,
@@ -1463,7 +1538,7 @@ mod tests {
}
/// `ListOptions`, `StatOptions`, `DeleteOptions`, `ReadRange`,
- /// `ReadOptions`, and `ReaderOptions` as
+ /// `ReadOptions`, `ReaderOptions`, and `WriteOptions` as
/// `bindings/cpp/include/data_structure.hpp` declared them on `main`
/// before they were generated, copied verbatim.
/// Callers depend on each member's name, type, default member initializer,
@@ -1573,6 +1648,24 @@ struct ReaderOptions {
std::size_t prefetch{0};
};"#;
+ const MAIN_WRITE_OPTIONS: &str = r#"/**
+ * @struct WriteOptions
+ * @brief Options for write and writer operations.
+ */
+struct WriteOptions {
+ bool append{false};
+ std::optional<std::string> cache_control;
+ std::optional<std::string> content_type;
+ std::optional<std::string> content_disposition;
+ std::optional<std::string> content_encoding;
+ std::optional<std::unordered_map<std::string, std::string>> user_metadata;
+ std::optional<std::string> if_match;
+ std::optional<std::string> if_none_match;
+ bool if_not_exists{false};
+ std::size_t concurrent{0};
+ std::optional<std::size_t> chunk;
+};"#;
+
fn core_names() -> CppNames {
CppNames::parse(&workspace_dir()).expect("parse core names")
}
@@ -1615,6 +1708,7 @@ struct ReaderOptions {
MAIN_READ_RANGE,
MAIN_READ_OPTIONS,
MAIN_READER_OPTIONS,
+ MAIN_WRITE_OPTIONS,
] {
assert!(
code.contains(&code_lines(main)),
@@ -1624,11 +1718,12 @@ struct ReaderOptions {
let head: String = main.lines().take(3).map(|l|
format!("{l}\n")).collect();
assert!(header.contains(&head), "header lacks:\n{head}");
}
- assert_eq!(header.matches("\nstruct ").count(), 6);
+ assert_eq!(header.matches("\nstruct ").count(), 7);
// `ReadOptions` needs `ReadRange` declared before it.
let position = |name: &str| header.find(&format!("\nstruct {name}
{{\n")).unwrap();
assert!(position("ReadRange") < position("ReadOptions"));
- for include in ["<chrono>", "<cstdint>"] {
+ // `data_structure.hpp` included `<unordered_map>` for `WriteOptions`.
+ for include in ["<chrono>", "<cstdint>", "<unordered_map>"] {
assert!(header.contains(&format!("\n#include {include}\n")));
}
}
@@ -1842,6 +1937,21 @@ single byte range, so `gap` has no effect.",
"A read with a positive `chunk` and an open-ended or suffix range
first stats the file to learn its length, unless `content_length_hint` is set
or an earlier read from this reader observed the length. Unlike with
[`ReadOptions::chunk`], an empty suffix range also stats the file. That stat
carries the reader's version and conditions, so each of them also needs its
stat capability, such as [`crate::Capability::stat_with_if_modified_since`] for
`if_modified_since`; otherwise the [...]
"`opendal::Reader::Read` and `opendal::Reader::ReadAt` read a
range with an end, so a positive `chunk` does not make them stat the file.",
),
+ (
+ "WriteOptions",
+ "Creating a writer does not access storage, so depending on the
service, a check against the stored file fails while writing or when closing
the writer. Combining `if_not_changed` with a conflicting `if_match` or
`if_version_match` fails before the writer exists, without accessing storage.",
+ "`opendal::Operator::GetWriter` does not access storage, so
depending on the service, a check against the stored file fails the returned
writer's `opendal::Writer::Write` or `opendal::Writer::Close`.",
+ ),
+ (
+ "WriteOptions",
+ "A later stat returns this metadata when the service exposes user
metadata. [`crate::Reader::metadata`] may omit it, for example on `fs`.",
+ "A later `opendal::Operator::Stat` returns this metadata when the
service exposes user metadata.",
+ ),
+ (
+ "WriteOptions",
+ "[`crate::Operator::write_with`] and
[`crate::Operator::write_options`] without `chunk` pass the whole buffer to the
service writer as one write.",
+ "`opendal::Operator::Write` without `chunk` passes the whole
buffer to the service writer as one write.",
+ ),
];
#[test]
@@ -1953,7 +2063,6 @@ single byte range, so `gap` has no effect.",
// text, so a reworded one must not slip through.
for rust in [
"[`",
- "](",
"crate::",
"ErrorKind::",
"`Capability::",
@@ -1963,13 +2072,19 @@ single byte range, so `gap` has no effect.",
] {
assert!(!header.contains(rust), "header contains `{rust}`");
}
+ // Links that stay point to web pages, such as
`WriteOptions::cache_control`'s
+ // references.
+ for target in header.split("](").skip(1) {
+ assert!(target.starts_with("https://"), "header links to
`{target}`");
+ }
// Each referenced capability is a member of the generated C++ class.
let capability_header =
rendered("bindings/cpp/include/capability.hpp");
for reference in header.split("`opendal::Capability::").skip(1) {
let member = &reference[..reference.find('`').unwrap()];
assert!(
- capability_header.contains(&format!(" bool
{member}{{false}};\n")),
+ capability_header.contains(&format!(" bool
{member}{{false}};\n"))
+ || capability_header.contains(&format!(" size_t
{member}{{0}};\n")),
"capability.hpp lacks `{member}`"
);
}
@@ -1990,14 +2105,16 @@ single byte range, so `gap` has no effect.",
for declaration in [
" std::string Read(std::string_view path, const ReadOptions
&options);\n",
" Reader GetReader(std::string_view path, const ReaderOptions
&options);\n",
+ " void Write(std::string_view path, std::string_view data,\n
const WriteOptions &options);\n",
+ " Writer GetWriter(std::string_view path, const WriteOptions
&options);\n",
] {
assert!(
operator.contains(declaration),
"opendal.hpp lacks {declaration}"
);
}
- // Each `Operator` and `Reader` method that the docs name is declared
- // in its class.
+ // Each `Operator`, `Reader`, and `Writer` method that the docs name is
+ // declared in its class.
let class = |name: &str| {
let body = &operator[operator.find(&format!("\nclass {name}
{{\n")).unwrap()..];
body[..body.find("\n};\n").unwrap()]
@@ -2011,7 +2128,7 @@ single byte range, so `gap` has no effect.",
.collect::<Vec<_>>()
.join("\n")
};
- let methods =
Regex::new(r"`opendal::(Operator|Reader)::(\w+)`").unwrap();
+ let methods =
Regex::new(r"`opendal::(Operator|Reader|Writer)::(\w+)`").unwrap();
let named: Vec<_> = methods.captures_iter(&header).collect();
assert!(!named.is_empty());
for method in named {
@@ -2143,6 +2260,45 @@ single byte range, so `gap` has no effect.",
);
}
+ #[test]
+ fn test_option_doc_lines_keep_nested_list_items() {
+ // Doc lines as core's parser gives them: a nested item keeps its
+ // indentation, and other lines are trimmed.
+ let doc = [
+ "- When chunk size is set:",
+ " - Each chunk reaches the service writer as one write; a service
may",
+ "add requests, such as the ones for an S3 multipart upload",
+ " - Fails with [`crate::ErrorKind::Unsupported`]",
+ "- Last item",
+ ]
+ .map(String::from);
+ let names = core_names();
+ let expected = [
+ "- When chunk size is set:",
+ " - Each chunk reaches the service writer as one write; a service
may add",
+ " requests, such as the ones for an S3 multipart upload",
+ " - Fails with `Unsupported`",
+ "- Last item",
+ ];
+ assert_eq!(option_doc_lines(&doc, HPP_DOC_PREFIX, &names), expected);
+ assert!(
+ expected
+ .iter()
+ .all(|line| HPP_DOC_PREFIX.len() + line.len() <=
HPP_COLUMN_LIMIT)
+ );
+ // A rewrite keeps the nesting.
+ let mut matched = [false];
+ assert_eq!(
+ option_doc_lines(
+ &rewrite_doc(&doc, &[("one write", "one write")], &mut
matched),
+ HPP_DOC_PREFIX,
+ &names
+ ),
+ expected
+ );
+ assert_eq!(matched, [true]);
+ }
+
#[test]
fn test_rewrite_doc_applies_within_blocks() {
let doc = [
@@ -2300,6 +2456,23 @@ single byte range, so `gap` has no effect.",
assert!(after[0].fills_defaults);
}
+ #[test]
+ fn test_unexposed_lists_unmirrored_fields() {
+ let models = options_models(&parsed_options(), OPTIONS,
&core_names()).unwrap();
+ let write = models.iter().find(|m| m.name == "WriteOptions").unwrap();
+ assert_eq!(
+ write.unexposed,
+ [
+ "content_language",
+ "expires",
+ "if_version_match",
+ "if_version_not_match",
+ "if_not_changed",
+ "checksum",
+ ]
+ );
+ }
+
#[test]
fn test_only_options_with_timestamps_convert_with_try_from() {
let models = options_models(&parsed_options(), OPTIONS,
&core_names()).unwrap();
@@ -2312,6 +2485,7 @@ single byte range, so `gap` has no effect.",
("DeleteOptions", false),
("ReadOptions", true),
("ReaderOptions", true),
+ ("WriteOptions", false),
]
);
@@ -2334,6 +2508,9 @@ single byte range, so `gap` has no effect.",
assert!(rust.contains(
"impl TryFrom<ffi::FfiReaderOptions> for
opendal::options::ReaderOptions {\n type Error = opendal::Error;\n"
));
+ assert!(
+ rust.contains("impl From<ffi::FfiWriteOptions> for
opendal::options::WriteOptions {")
+ );
}
#[test]
@@ -2449,6 +2626,42 @@ single byte range, so `gap` has no effect.",
OptionUsize,
"core `ReaderOptions::prefetch` has kind OptionUsize, but
OPTIONS lists Usize",
),
+ (
+ "WriteOptions",
+ "append",
+ OptionString,
+ "core `WriteOptions::append` has kind OptionString, but
OPTIONS lists Bool",
+ ),
+ (
+ "WriteOptions",
+ "cache_control",
+ Bool,
+ "core `WriteOptions::cache_control` has kind Bool, but OPTIONS
lists OptionString",
+ ),
+ (
+ "WriteOptions",
+ "user_metadata",
+ OptionString,
+ "core `WriteOptions::user_metadata` has kind OptionString, but
OPTIONS lists OptionStringMap",
+ ),
+ (
+ "WriteOptions",
+ "if_not_exists",
+ OptionString,
+ "core `WriteOptions::if_not_exists` has kind OptionString, but
OPTIONS lists Bool",
+ ),
+ (
+ "WriteOptions",
+ "concurrent",
+ OptionUsize,
+ "core `WriteOptions::concurrent` has kind OptionUsize, but
OPTIONS lists Usize",
+ ),
+ (
+ "WriteOptions",
+ "chunk",
+ OptionU64,
+ "core `WriteOptions::chunk` has kind OptionU64, but OPTIONS
lists OptionUsize",
+ ),
] {
let mut changed = parsed.clone();
changed
@@ -2506,6 +2719,19 @@ single byte range, so `gap` has no effect.",
.to_string(),
"OPTIONS member `ReaderOptions::prefetch` is missing from core"
);
+ let mut without_user_metadata = parsed.clone();
+ without_user_metadata
+ .iter_mut()
+ .find(|s| s.name == "WriteOptions")
+ .unwrap()
+ .fields
+ .retain(|f| f.name != "user_metadata");
+ assert_eq!(
+ options_models(&without_user_metadata, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ "OPTIONS member `WriteOptions::user_metadata` is missing from core"
+ );
assert_eq!(
error("WriteOptions", &[("expires", OptionDuration)]),
"the C++ bridge cannot carry `WriteOptions::expires` of kind
OptionDuration yet"
@@ -2645,6 +2871,52 @@ single byte range, so `gap` has no effect.",
);
}
+ let write = OPTIONS.iter().find(|s| s.name == "WriteOptions").unwrap();
+ let rewordings = [
+ (None, "without accessing", "without contacting"),
+ (Some("user_metadata"), "may omit it", "can omit it"),
+ (
+ Some("concurrent"),
+ "pass the whole buffer",
+ "send the whole buffer",
+ ),
+ ];
+ assert_eq!(rewordings.len(), write.cpp_rewrites.len());
+ for (i, (field, core_text, reworded_text)) in
rewordings.into_iter().enumerate() {
+ let (from, _) = write.cpp_rewrites[i];
+ let mut reworded = parsed_options();
+ let core = reworded
+ .iter_mut()
+ .find(|s| s.name == "WriteOptions")
+ .unwrap();
+ let doc = match field {
+ None => &mut core.doc,
+ Some(field) => {
+ &mut core
+ .fields
+ .iter_mut()
+ .find(|f| f.name == field)
+ .unwrap()
+ .doc
+ }
+ };
+ assert!(
+ doc.iter().any(|line| line.contains(core_text)),
+ "{core_text}"
+ );
+ for line in doc.iter_mut() {
+ *line = line.replace(core_text, reworded_text);
+ }
+ assert_eq!(
+ options_models(&reworded, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ format!(
+ "core `WriteOptions` docs no longer contain `{from}`;
review its C++ rewrite"
+ )
+ );
+ }
+
// A rewrite also applies to member docs, and a match there counts.
let spec = OptionsSpec {
name: "ReadOptions",
diff --git a/dev/src/generate/cpp/options_converter_cpp.j2
b/dev/src/generate/cpp/options_converter_cpp.j2
index 5ae2e1b98f..06735df106 100644
--- a/dev/src/generate/cpp/options_converter_cpp.j2
+++ b/dev/src/generate/cpp/options_converter_cpp.j2
@@ -27,6 +27,8 @@
#include <cstdint>
#include <optional>
#include <string>
+#include <unordered_map>
+#include <utility>
#include "utils/rust_converter.hpp"
@@ -81,6 +83,18 @@ ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
static_cast<std::uint32_t>(nanoseconds)};
}
+ffi::options::OptionalStringMap ToFfiOptionalStringMap(
+ const std::optional<std::unordered_map<std::string, std::string>> &value) {
+ rust::Vec<ffi::options::HashMapValue> values;
+ if (value.has_value()) {
+ values.reserve(value->size());
+ for (const auto &[key, item] : *value) {
+ values.push_back({rust_string(key), rust_string(item)});
+ }
+ }
+ return ffi::options::OptionalStringMap{value.has_value(), std::move(values)};
+}
+
ffi::options::FfiBytesRange ToFfiBytesRange(const ReadRange &range) {
return ffi::options::FfiBytesRange{static_cast<std::uint8_t>(range.type),
range.start, range.end};
diff --git a/dev/src/generate/cpp/options_hpp.j2
b/dev/src/generate/cpp/options_hpp.j2
index 2d0a63c5b3..5adfa39ffa 100644
--- a/dev/src/generate/cpp/options_hpp.j2
+++ b/dev/src/generate/cpp/options_hpp.j2
@@ -27,6 +27,7 @@
#include <cstdint>
#include <optional>
#include <string>
+#include <unordered_map>
namespace opendal {
diff --git a/dev/src/generate/cpp/options_rs.j2
b/dev/src/generate/cpp/options_rs.j2
index 5efd6a5d78..46208e583e 100644
--- a/dev/src/generate/cpp/options_rs.j2
+++ b/dev/src/generate/cpp/options_rs.j2
@@ -45,6 +45,16 @@ pub mod ffi {
nanoseconds: u32,
}
+ struct HashMapValue {
+ key: String,
+ value: String,
+ }
+
+ struct OptionalStringMap {
+ has_value: bool,
+ value: Vec<HashMapValue>,
+ }
+
/// A C++ `ReadRange`, whose `kind` is its `ReadRange::Type`.
struct FfiBytesRange {
kind: u8,
@@ -86,6 +96,17 @@ fn optional_timestamp(
}
}
+fn optional_string_map(
+ v: ffi::OptionalStringMap,
+) -> Option<std::collections::HashMap<String, String>> {
+ v.has_value.then(|| {
+ v.value
+ .into_iter()
+ .map(|entry| (entry.key, entry.value))
+ .collect()
+ })
+}
+
fn bytes_range(v: ffi::FfiBytesRange) -> opendal::BytesRange {
match v.kind {
1 => opendal::BytesRange::new(v.start, None),