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 f8d039a690 feat(bindings/cpp): generate ReadOptions from core (#9378)
f8d039a690 is described below
commit f8d039a690bbaddb5d18d6bd637ea6c9e9703139
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 19:24:05 2026 +0530
feat(bindings/cpp): generate ReadOptions from core (#9378)
* feat(bindings/cpp): generate ReadOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/cpp): generate ReadOptions from core
Fail the C++ doc test when the header contains `Some(`, `None`, or
"performance guide", so a reworded core sentence cannot bypass the two
rules that match exact core text. Document that a `ReadRange::Range`
whose `end` is not after `start` reads nothing, as the conversion has
always done.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/cpp): generate ReadOptions from core
Split the `range` doc sentence so the failure past the end of the file
applies only to a nonempty `ReadRange::Range`. On memory and fs,
`Range(11, 11)` of a 10-byte file returns an empty string, while
`Range(2, 11)` fails. Test both.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/cpp/include/data_structure.hpp | 51 ---
bindings/cpp/include/options.hpp | 153 +++++++
bindings/cpp/src/lib.rs | 54 +--
bindings/cpp/src/operator.cpp | 25 +-
bindings/cpp/src/options.rs | 69 +++
bindings/cpp/src/options_test.rs | 158 ++++++-
bindings/cpp/src/utils/options_converter.cpp | 31 ++
bindings/cpp/src/utils/options_converter.hpp | 1 +
bindings/cpp/tests/options_test.cpp | 244 ++++++++++
dev/src/generate/cpp.rs | 624 +++++++++++++++++++++++---
dev/src/generate/cpp/options_converter_cpp.j2 | 13 +
dev/src/generate/cpp/options_hpp.j2 | 34 ++
dev/src/generate/cpp/options_rs.j2 | 25 ++
13 files changed, 1302 insertions(+), 180 deletions(-)
diff --git a/bindings/cpp/include/data_structure.hpp
b/bindings/cpp/include/data_structure.hpp
index 080c5030df..08a635ac4d 100644
--- a/bindings/cpp/include/data_structure.hpp
+++ b/bindings/cpp/include/data_structure.hpp
@@ -41,57 +41,6 @@ class Entry {
std::string path;
};
-/**
- * @struct ReadRange
- * @brief Byte range used by read operations.
- */
-struct ReadRange {
- enum class Type : std::uint8_t {
- FULL = 0,
- OFFSET = 1,
- RANGE = 2,
- SUFFIX = 3,
- };
-
- Type type{Type::FULL};
- std::uint64_t start{0};
- std::uint64_t end{0};
-
- static ReadRange Full() { return {}; }
-
- static ReadRange Offset(std::uint64_t offset) {
- return {Type::OFFSET, offset, 0};
- }
-
- static ReadRange Range(std::uint64_t start, std::uint64_t end) {
- return {Type::RANGE, start, end};
- }
-
- static ReadRange Suffix(std::uint64_t size) {
- return {Type::SUFFIX, 0, size};
- }
-};
-
-/**
- * @struct ReadOptions
- * @brief Options for read operations.
- */
-struct ReadOptions {
- ReadRange range;
- std::optional<std::string> version;
- std::optional<std::string> if_match;
- std::optional<std::string> if_none_match;
- std::optional<std::chrono::system_clock::time_point> if_modified_since;
- std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
- std::optional<std::uint64_t> content_length_hint;
- std::size_t concurrent{0};
- std::optional<std::size_t> chunk;
- std::optional<std::size_t> gap;
- std::optional<std::string> override_content_type;
- std::optional<std::string> override_cache_control;
- std::optional<std::string> override_content_disposition;
-};
-
/**
* @struct ReaderOptions
* @brief Options for creating readers.
diff --git a/bindings/cpp/include/options.hpp b/bindings/cpp/include/options.hpp
index 1a37065865..7a1610fbcf 100644
--- a/bindings/cpp/include/options.hpp
+++ b/bindings/cpp/include/options.hpp
@@ -24,11 +24,43 @@
#include <chrono>
#include <cstddef>
+#include <cstdint>
#include <optional>
#include <string>
namespace opendal {
+/**
+ * @struct ReadRange
+ * @brief Byte range used by read operations.
+ */
+struct ReadRange {
+ enum class Type : std::uint8_t {
+ FULL = 0,
+ OFFSET = 1,
+ RANGE = 2,
+ SUFFIX = 3,
+ };
+
+ Type type{Type::FULL};
+ std::uint64_t start{0};
+ std::uint64_t end{0};
+
+ static ReadRange Full() { return {}; }
+
+ static ReadRange Offset(std::uint64_t offset) {
+ return {Type::OFFSET, offset, 0};
+ }
+
+ static ReadRange Range(std::uint64_t start, std::uint64_t end) {
+ return {Type::RANGE, start, end};
+ }
+
+ static ReadRange Suffix(std::uint64_t size) {
+ return {Type::SUFFIX, 0, size};
+ }
+};
+
/**
* @struct ListOptions
* @brief Options for list and lister operations.
@@ -192,4 +224,125 @@ struct DeleteOptions {
bool recursive{false};
};
+/**
+ * @struct ReadOptions
+ * @brief Options for read operations.
+ */
+/// Each condition checks the file being read, and every condition must hold
for
+/// the read to proceed. Once the option and capability checks pass, a read
that
+/// reaches storage fails with `NotFound` for a missing file, no matter which
+/// conditions are set. An existing file that fails a condition returns
+/// `ConditionNotMatch`, and a condition the service does not advertise through
+/// its capability returns `Unsupported`; OpenDAL never silently drops a
+/// condition. A read with an empty range, such as `ReadRange::Range(0, 0)`,
+/// validates the read options and capabilities, then returns an empty buffer
+/// without accessing storage or evaluating conditions against the file.
+///
+/// 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
+/// `NotFound`, it throws a `std::exception` whose `what()` starts with that
+/// kind.
+struct ReadOptions {
+ /// Read only this byte range of the file. For a file of `n` bytes:
+ ///
+ /// - `ReadRange::Full()`, the default, reads bytes `[0, n)`.
+ /// - `ReadRange::Offset(1024)` reads bytes `[1024, n)`.
+ /// - `ReadRange::Range(0, 1024)` reads bytes `[0, 1024)`.
+ /// - `ReadRange::Suffix(1024)` reads the last `min(1024, n)` bytes.
+ ///
+ /// A `ReadRange::Range` whose `end` is not after `start` reads nothing.
+ /// Otherwise, a `ReadRange::Range` whose `end` is past the end of the file
+ /// fails the read.
+ ReadRange range;
+ /// Read the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the read returns; it is not a condition
+ /// on the file. A version that does not exist returns `NotFound`.
+ ///
+ /// Check `opendal::Capability::read_with_version` before using this option.
+ std::optional<std::string> version;
+ /// Read only when the file has this exact ETag.
+ ///
+ /// The condition succeeds when the file exists and its ETag equals this
+ /// value. A file with a different ETag returns `ConditionNotMatch`; a
missing
+ /// file returns `NotFound`. 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::read_with_if_match`.
+ std::optional<std::string> if_match;
+ /// Read only when the file does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file exists
+ /// with a different ETag. A file whose ETag equals this value returns
+ /// `ConditionNotMatch`; a missing file returns `NotFound`. 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::read_with_if_none_match`.
+ std::optional<std::string> if_none_match;
+ /// Read only when the file was modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was modified after this
+ /// time. A file not modified since this time returns `ConditionNotMatch`; a
+ /// missing file returns `NotFound`.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_modified_since`.
+ std::optional<std::chrono::system_clock::time_point> if_modified_since;
+ /// Read only when the file was not modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was not modified after
+ /// this time. A file modified after this time returns `ConditionNotMatch`; a
+ /// missing file returns `NotFound`.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_unmodified_since`.
+ std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
+ /// Known content length of the object.
+ ///
+ /// This is an execution hint that allows OpenDAL to avoid extra metadata
+ /// requests while planning reads. It must not be used as an object identity
+ /// or consistency condition.
+ std::optional<std::uint64_t> content_length_hint;
+ /// Set `concurrent` for the operation.
+ ///
+ /// OpenDAL reads a file without concurrency by default. This is not
efficient
+ /// for cases when users read large chunks of data. By setting `concurrent`
+ /// together with `chunk`, opendal will read files concurrently on supported
+ /// storage services.
+ ///
+ /// By setting `concurrent`, opendal will fetch chunks concurrently with the
+ /// given chunk size. Without `chunk`, OpenDAL does not read concurrently.
+ std::size_t concurrent{0};
+ /// Set `chunk` for the operation.
+ ///
+ /// By default, OpenDAL reads the range with a single request instead of in
+ /// chunks. Users can set chunk based on their own needs. `0` has the same
+ /// behavior as `std::nullopt`.
+ ///
+ /// A read with a positive `chunk` and an open-ended or nonempty suffix range
+ /// first stats the file to learn its length, unless `content_length_hint` is
+ /// set. That stat carries the read's version and conditions, so each of them
+ /// also needs its stat capability, such as
+ /// `opendal::Capability::stat_with_if_modified_since` for
+ /// `if_modified_since`; otherwise the read returns `Unsupported`.
+ std::optional<std::size_t> chunk;
+ /// Each call to `opendal::Operator::Read` reads a single byte range, so
`gap`
+ /// has no effect.
+ std::optional<std::size_t> gap;
+ /// Request a `content-type` response header override from services that
+ /// support it.
+ std::optional<std::string> override_content_type;
+ /// Request a `cache-control` response header override from services that
+ /// support it.
+ std::optional<std::string> override_cache_control;
+ /// Request a `content-disposition` response header override from services
+ /// that support it.
+ std::optional<std::string> override_content_disposition;
+};
+
} // namespace opendal
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index d509e65ea7..1df98bcd06 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -74,28 +74,6 @@ mod ffi {
nanoseconds: u32,
}
- struct FfiBytesRange {
- kind: u8,
- start: u64,
- end: u64,
- }
-
- struct FfiReadOptions {
- range: FfiBytesRange,
- version: OptionalString,
- if_match: OptionalString,
- if_none_match: OptionalString,
- if_modified_since: OptionalTimestamp,
- if_unmodified_since: OptionalTimestamp,
- content_length_hint: OptionalU64,
- concurrent: usize,
- chunk: OptionalUsize,
- gap: OptionalUsize,
- override_content_type: OptionalString,
- override_cache_control: OptionalString,
- override_content_disposition: OptionalString,
- }
-
struct FfiReaderOptions {
version: OptionalString,
if_match: OptionalString,
@@ -180,6 +158,8 @@ mod ffi {
type FfiStatOptions = crate::options::ffi::FfiStatOptions;
#[namespace = "opendal::ffi::options"]
type FfiDeleteOptions = crate::options::ffi::FfiDeleteOptions;
+ #[namespace = "opendal::ffi::options"]
+ type FfiReadOptions = crate::options::ffi::FfiReadOptions;
}
extern "Rust" {
@@ -385,15 +365,6 @@ fn optional_timestamp(v: ffi::OptionalTimestamp) ->
Result<Option<Timestamp>> {
}
}
-fn bytes_range(v: ffi::FfiBytesRange) -> od::BytesRange {
- match v.kind {
- 1 => od::BytesRange::new(v.start, None),
- 2 => od::BytesRange::new(v.start, Some(v.end.saturating_sub(v.start))),
- 3 => od::BytesRange::suffix(v.end),
- _ => od::BytesRange::default(),
- }
-}
-
fn user_metadata(
has_value: bool,
values: Vec<ffi::HashMapValue>,
@@ -406,25 +377,6 @@ fn user_metadata(
})
}
-fn read_options(opts: ffi::FfiReadOptions) -> Result<od::options::ReadOptions>
{
- Ok(od::options::ReadOptions {
- range: bytes_range(opts.range),
- version: optional_string(opts.version),
- if_match: optional_string(opts.if_match),
- if_none_match: optional_string(opts.if_none_match),
- if_modified_since: optional_timestamp(opts.if_modified_since)?,
- if_unmodified_since: optional_timestamp(opts.if_unmodified_since)?,
- content_length_hint: optional_u64(opts.content_length_hint),
- concurrent: opts.concurrent,
- chunk: optional_usize(opts.chunk),
- gap: optional_usize(opts.gap),
- override_content_type: optional_string(opts.override_content_type),
- override_cache_control: optional_string(opts.override_cache_control),
- override_content_disposition:
optional_string(opts.override_content_disposition),
- ..Default::default()
- })
-}
-
fn reader_options(opts: ffi::FfiReaderOptions) ->
Result<od::options::ReaderOptions> {
Ok(od::options::ReaderOptions {
version: optional_string(opts.version),
@@ -482,7 +434,7 @@ impl Operator {
}
fn read_options(&self, path: &str, opts: ffi::FfiReadOptions) ->
Result<Vec<u8>> {
- Ok(self.0.read_options(path, read_options(opts)?)?.to_vec())
+ Ok(self.0.read_options(path, opts.try_into()?)?.to_vec())
}
fn write(&self, path: &str, bs: &[u8]) -> Result<()> {
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index df36a5e3e1..6bb95c7d49 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -77,11 +77,6 @@ ffi::OptionalTimestamp ToFfiOptionalTimestamp(
static_cast<std::uint32_t>(nanoseconds)};
}
-ffi::FfiBytesRange ToFfiBytesRange(const ReadRange &range) {
- return ffi::FfiBytesRange{static_cast<std::uint8_t>(range.type), range.start,
- range.end};
-}
-
rust::Vec<ffi::HashMapValue> ToFfiHashMap(
const std::unordered_map<std::string, std::string> &map) {
rust::Vec<ffi::HashMapValue> values;
@@ -92,24 +87,6 @@ rust::Vec<ffi::HashMapValue> ToFfiHashMap(
return values;
}
-ffi::FfiReadOptions ToFfiOptions(const ReadOptions &options) {
- return ffi::FfiReadOptions{
- ToFfiBytesRange(options.range),
- ToFfiOptionalString(options.version),
- ToFfiOptionalString(options.if_match),
- ToFfiOptionalString(options.if_none_match),
- ToFfiOptionalTimestamp(options.if_modified_since),
- ToFfiOptionalTimestamp(options.if_unmodified_since),
- ToFfiOptionalU64(options.content_length_hint),
- options.concurrent,
- ToFfiOptionalUsize(options.chunk),
- ToFfiOptionalUsize(options.gap),
- ToFfiOptionalString(options.override_content_type),
- ToFfiOptionalString(options.override_cache_control),
- ToFfiOptionalString(options.override_content_disposition),
- };
-}
-
ffi::FfiReaderOptions ToFfiOptions(const ReaderOptions &options) {
return ffi::FfiReaderOptions{
ToFfiOptionalString(options.version),
@@ -229,7 +206,7 @@ std::string Operator::Read(std::string_view path) {
std::string Operator::Read(std::string_view path, const ReadOptions &options) {
auto rust_vec = CheckedOperator(operator_).read_options(
- utils::rust_str(path), ToFfiOptions(options));
+ utils::rust_str(path), utils::ToFfiOptions(options));
return {rust_vec.begin(), rust_vec.end()};
}
diff --git a/bindings/cpp/src/options.rs b/bindings/cpp/src/options.rs
index 37202db974..e7b2734816 100644
--- a/bindings/cpp/src/options.rs
+++ b/bindings/cpp/src/options.rs
@@ -34,12 +34,24 @@ pub mod ffi {
value: usize,
}
+ struct OptionalU64 {
+ has_value: bool,
+ value: u64,
+ }
+
struct OptionalTimestamp {
has_value: bool,
seconds: i64,
nanoseconds: u32,
}
+ /// A C++ `ReadRange`, whose `kind` is its `ReadRange::Type`.
+ struct FfiBytesRange {
+ kind: u8,
+ start: u64,
+ end: u64,
+ }
+
struct FfiListOptions {
limit: OptionalUsize,
start_after: OptionalString,
@@ -63,6 +75,22 @@ pub mod ffi {
version: OptionalString,
recursive: bool,
}
+
+ struct FfiReadOptions {
+ range: FfiBytesRange,
+ version: OptionalString,
+ if_match: OptionalString,
+ if_none_match: OptionalString,
+ if_modified_since: OptionalTimestamp,
+ if_unmodified_since: OptionalTimestamp,
+ content_length_hint: OptionalU64,
+ concurrent: usize,
+ chunk: OptionalUsize,
+ gap: OptionalUsize,
+ override_content_type: OptionalString,
+ override_cache_control: OptionalString,
+ override_content_disposition: OptionalString,
+ }
}
fn optional_string(v: ffi::OptionalString) -> Option<String> {
@@ -73,6 +101,10 @@ fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
v.has_value.then_some(v.value)
}
+fn optional_u64(v: ffi::OptionalU64) -> Option<u64> {
+ v.has_value.then_some(v.value)
+}
+
fn optional_timestamp(
v: ffi::OptionalTimestamp,
) -> opendal::Result<Option<opendal::raw::Timestamp>> {
@@ -86,6 +118,15 @@ fn optional_timestamp(
}
}
+fn bytes_range(v: ffi::FfiBytesRange) -> opendal::BytesRange {
+ match v.kind {
+ 1 => opendal::BytesRange::new(v.start, None),
+ 2 => opendal::BytesRange::new(v.start,
Some(v.end.saturating_sub(v.start))),
+ 3 => opendal::BytesRange::suffix(v.end),
+ _ => opendal::BytesRange::default(),
+ }
+}
+
impl From<ffi::FfiListOptions> for opendal::options::ListOptions {
fn from(opts: ffi::FfiListOptions) -> Self {
Self {
@@ -138,3 +179,31 @@ impl From<ffi::FfiDeleteOptions> for
opendal::options::DeleteOptions {
}
}
}
+
+impl TryFrom<ffi::FfiReadOptions> for opendal::options::ReadOptions {
+ type Error = opendal::Error;
+
+ fn try_from(opts: ffi::FfiReadOptions) -> Result<Self, Self::Error> {
+ Ok(Self {
+ range: bytes_range(opts.range),
+ version: optional_string(opts.version),
+ if_match: optional_string(opts.if_match),
+ if_none_match: optional_string(opts.if_none_match),
+ if_modified_since: optional_timestamp(opts.if_modified_since)?,
+ if_unmodified_since: optional_timestamp(opts.if_unmodified_since)?,
+ content_length_hint: optional_u64(opts.content_length_hint),
+ concurrent: opts.concurrent,
+ chunk: optional_usize(opts.chunk),
+ gap: optional_usize(opts.gap),
+ override_content_type: optional_string(opts.override_content_type),
+ override_cache_control:
optional_string(opts.override_cache_control),
+ override_content_disposition:
optional_string(opts.override_content_disposition),
+ // Not exposed in C++ yet:
+ // - `limit`
+ // - `if_version_match`
+ // - `if_version_not_match`
+ // - `checksum`
+ ..Default::default()
+ })
+ }
+}
diff --git a/bindings/cpp/src/options_test.rs b/bindings/cpp/src/options_test.rs
index 114c0ca61c..bf02cfb7ed 100644
--- a/bindings/cpp/src/options_test.rs
+++ b/bindings/cpp/src/options_test.rs
@@ -15,12 +15,14 @@
// specific language governing permissions and limitations
// under the License.
-//! The generated `ListOptions`, `StatOptions`, and `DeleteOptions`
-//! conversions in `options.rs` carry every bridge field to the core field of
-//! the same name, and absent values stay absent.
+//! The generated `ListOptions`, `StatOptions`, `DeleteOptions`, and
+//! `ReadOptions` conversions in `options.rs` carry every bridge field to the
+//! core field of the same name, and absent values stay absent.
+use opendal::BytesRange;
use opendal::options::DeleteOptions;
use opendal::options::ListOptions;
+use opendal::options::ReadOptions;
use opendal::options::StatOptions;
use opendal::raw::Timestamp;
@@ -191,3 +193,153 @@ fn test_delete_options_keep_absent_values_absent() {
assert_eq!(DeleteOptions::from(opts), DeleteOptions::default());
}
+
+fn bridge_usize(value: Option<usize>) -> ffi::OptionalUsize {
+ ffi::OptionalUsize {
+ has_value: value.is_some(),
+ value: value.unwrap_or(7),
+ }
+}
+
+fn bridge_u64(value: Option<u64>) -> ffi::OptionalU64 {
+ ffi::OptionalU64 {
+ has_value: value.is_some(),
+ value: value.unwrap_or(7),
+ }
+}
+
+/// A C++ `ReadRange` with `ReadRange::Type` `kind`.
+fn bridge_range(kind: u8, start: u64, end: u64) -> ffi::FfiBytesRange {
+ ffi::FfiBytesRange { kind, start, end }
+}
+
+fn absent_read_options() -> ffi::FfiReadOptions {
+ ffi::FfiReadOptions {
+ // `ReadRange::Full()` sends its zero `start` and `end`.
+ range: bridge_range(0, 0, 0),
+ version: bridge_string(None),
+ if_match: bridge_string(None),
+ if_none_match: bridge_string(None),
+ if_modified_since: bridge_timestamp(None),
+ if_unmodified_since: bridge_timestamp(None),
+ content_length_hint: bridge_u64(None),
+ concurrent: 0,
+ chunk: bridge_usize(None),
+ gap: bridge_usize(None),
+ override_content_type: bridge_string(None),
+ override_cache_control: bridge_string(None),
+ override_content_disposition: bridge_string(None),
+ }
+}
+
+#[test]
+fn test_read_options_carry_every_field() {
+ let opts = ffi::FfiReadOptions {
+ range: bridge_range(2, 3, 10),
+ version: bridge_string(Some("version")),
+ if_match: bridge_string(Some("if_match")),
+ if_none_match: bridge_string(Some("if_none_match")),
+ if_modified_since: bridge_timestamp(Some((1_700_000_000, 250_000))),
+ if_unmodified_since: bridge_timestamp(Some((-1, 999_999_000))),
+ content_length_hint: bridge_u64(Some(u64::MAX)),
+ concurrent: 4,
+ chunk: bridge_usize(Some(16)),
+ gap: bridge_usize(Some(32)),
+ override_content_type: bridge_string(Some("override_content_type")),
+ override_cache_control: bridge_string(Some("override_cache_control")),
+ override_content_disposition:
bridge_string(Some("override_content_disposition")),
+ };
+
+ // The options that C++ does not expose keep their core defaults, as on
+ // `main`.
+ let expected = ReadOptions {
+ range: BytesRange::new(3, Some(7)),
+ version: Some("version".to_string()),
+ if_match: Some("if_match".to_string()),
+ if_none_match: Some("if_none_match".to_string()),
+ if_modified_since: Some(Timestamp::new(1_700_000_000,
250_000).unwrap()),
+ if_unmodified_since: Some(Timestamp::new(-1, 999_999_000).unwrap()),
+ content_length_hint: Some(u64::MAX),
+ concurrent: 4,
+ chunk: Some(16),
+ gap: Some(32),
+ override_content_type: Some("override_content_type".to_string()),
+ override_cache_control: Some("override_cache_control".to_string()),
+ override_content_disposition:
Some("override_content_disposition".to_string()),
+ ..Default::default()
+ };
+ assert_eq!(ReadOptions::try_from(opts).unwrap(), expected);
+}
+
+#[test]
+fn test_read_options_convert_each_range_type() {
+ // `(ReadRange::Type, start, end)` and the core range that `main` sent.
+ for (kind, start, end, expected) in [
+ (0, 3, 10, BytesRange::default()),
+ (1, 3, 10, BytesRange::new(3, None)),
+ (2, 3, 10, BytesRange::new(3, Some(7))),
+ // An `end` before `start` reads nothing.
+ (2, 10, 3, BytesRange::new(10, Some(0))),
+ (3, 3, 10, BytesRange::suffix(10)),
+ // A type that C++ does not declare reads the whole file.
+ (4, 3, 10, BytesRange::default()),
+ (u8::MAX, 3, 10, BytesRange::default()),
+ ] {
+ let opts = ffi::FfiReadOptions {
+ range: bridge_range(kind, start, end),
+ ..absent_read_options()
+ };
+ assert_eq!(
+ ReadOptions::try_from(opts).unwrap().range,
+ expected,
+ "kind {kind}"
+ );
+ }
+}
+
+#[test]
+fn test_read_options_keep_explicit_zeros() {
+ let opts = ffi::FfiReadOptions {
+ content_length_hint: bridge_u64(Some(0)),
+ chunk: bridge_usize(Some(0)),
+ gap: bridge_usize(Some(0)),
+ ..absent_read_options()
+ };
+
+ let options = ReadOptions::try_from(opts).unwrap();
+ assert_eq!(options.content_length_hint, Some(0));
+ assert_eq!(options.chunk, Some(0));
+ assert_eq!(options.gap, Some(0));
+}
+
+#[test]
+fn test_read_options_keep_absent_values_absent() {
+ // C++ sends a value behind `has_value == false`; it must not reach core.
+ assert_eq!(
+ ReadOptions::try_from(absent_read_options()).unwrap(),
+ ReadOptions::default()
+ );
+}
+
+#[test]
+fn test_read_options_reject_out_of_range_timestamps() {
+ // The read fails before reaching the service, as it did on `main`.
+ for opts in [
+ ffi::FfiReadOptions {
+ if_modified_since: bridge_timestamp(Some((i64::MAX, 0))),
+ ..absent_read_options()
+ },
+ ffi::FfiReadOptions {
+ if_unmodified_since: bridge_timestamp(Some((i64::MAX, 0))),
+ ..absent_read_options()
+ },
+ ] {
+ let err = ReadOptions::try_from(opts).unwrap_err();
+ assert_eq!(err.kind(), opendal::ErrorKind::Unexpected);
+ assert!(
+ err.to_string()
+ .contains("create timestamp from '9223372036854775807'
seconds"),
+ "{err}"
+ );
+ }
+}
diff --git a/bindings/cpp/src/utils/options_converter.cpp
b/bindings/cpp/src/utils/options_converter.cpp
index ea186d02fa..b83f2172da 100644
--- a/bindings/cpp/src/utils/options_converter.cpp
+++ b/bindings/cpp/src/utils/options_converter.cpp
@@ -50,6 +50,14 @@ ffi::options::OptionalUsize ToFfiOptionalUsize(
return ffi::options::OptionalUsize{false, 0};
}
+ffi::options::OptionalU64 ToFfiOptionalU64(
+ const std::optional<std::uint64_t> &value) {
+ if (value.has_value()) {
+ return ffi::options::OptionalU64{true, *value};
+ }
+ return ffi::options::OptionalU64{false, 0};
+}
+
ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
const std::optional<std::chrono::system_clock::time_point> &value) {
if (!value.has_value()) {
@@ -73,6 +81,11 @@ ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
static_cast<std::uint32_t>(nanoseconds)};
}
+ffi::options::FfiBytesRange ToFfiBytesRange(const ReadRange &range) {
+ return ffi::options::FfiBytesRange{static_cast<std::uint8_t>(range.type),
+ range.start, range.end};
+}
+
} // namespace
ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options) {
@@ -105,4 +118,22 @@ ffi::options::FfiDeleteOptions ToFfiOptions(const
DeleteOptions &options) {
};
}
+ffi::options::FfiReadOptions ToFfiOptions(const ReadOptions &options) {
+ return ffi::options::FfiReadOptions{
+ ToFfiBytesRange(options.range),
+ ToFfiOptionalString(options.version),
+ ToFfiOptionalString(options.if_match),
+ ToFfiOptionalString(options.if_none_match),
+ ToFfiOptionalTimestamp(options.if_modified_since),
+ ToFfiOptionalTimestamp(options.if_unmodified_since),
+ ToFfiOptionalU64(options.content_length_hint),
+ options.concurrent,
+ ToFfiOptionalUsize(options.chunk),
+ ToFfiOptionalUsize(options.gap),
+ ToFfiOptionalString(options.override_content_type),
+ ToFfiOptionalString(options.override_cache_control),
+ ToFfiOptionalString(options.override_content_disposition),
+ };
+}
+
} // namespace opendal::utils
diff --git a/bindings/cpp/src/utils/options_converter.hpp
b/bindings/cpp/src/utils/options_converter.hpp
index 884fe62153..89b7c79591 100644
--- a/bindings/cpp/src/utils/options_converter.hpp
+++ b/bindings/cpp/src/utils/options_converter.hpp
@@ -30,5 +30,6 @@ namespace opendal::utils {
ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options);
ffi::options::FfiStatOptions ToFfiOptions(const StatOptions &options);
ffi::options::FfiDeleteOptions ToFfiOptions(const DeleteOptions &options);
+ffi::options::FfiReadOptions ToFfiOptions(const ReadOptions &options);
} // namespace opendal::utils
diff --git a/bindings/cpp/tests/options_test.cpp
b/bindings/cpp/tests/options_test.cpp
index ff2eebb578..8270123459 100644
--- a/bindings/cpp/tests/options_test.cpp
+++ b/bindings/cpp/tests/options_test.cpp
@@ -320,3 +320,247 @@ TEST(OptionsTest, DeleteOptionsErrorsStartWithErrorKind) {
}
EXPECT_TRUE(op.Exists("delete_errors"));
}
+
+TEST(OptionsTest, ReadOptionsPositionalInitializerReachesBridge) {
+ const std::chrono::system_clock::time_point modified{
+ std::chrono::seconds{1700000000} + std::chrono::microseconds{250}};
+ const std::chrono::system_clock::time_point unmodified{
+ std::chrono::microseconds{-1}};
+ // Every member in the order `data_structure.hpp` declared them before
+ // `ReadOptions` was generated.
+ const opendal::ReadOptions options{
+ /*range=*/opendal::ReadRange::Range(3, 10),
+ /*version=*/"version",
+ /*if_match=*/"if_match",
+ /*if_none_match=*/"if_none_match",
+ /*if_modified_since=*/modified,
+ /*if_unmodified_since=*/unmodified,
+ /*content_length_hint=*/std::uint64_t{42},
+ /*concurrent=*/4,
+ /*chunk=*/16,
+ /*gap=*/32,
+ /*override_content_type=*/"override_content_type",
+ /*override_cache_control=*/"override_cache_control",
+ /*override_content_disposition=*/"override_content_disposition",
+ };
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_EQ(ffi.range.kind, std::uint8_t{2});
+ EXPECT_EQ(ffi.range.start, std::uint64_t{3});
+ EXPECT_EQ(ffi.range.end, std::uint64_t{10});
+ EXPECT_TRUE(ffi.version.has_value);
+ EXPECT_EQ(std::string(ffi.version.value), "version");
+ 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_modified_since.has_value);
+ EXPECT_EQ(ffi.if_modified_since.seconds, std::int64_t{1700000000});
+ EXPECT_EQ(ffi.if_modified_since.nanoseconds, std::uint32_t{250000});
+ // A time before the epoch keeps a non-negative nanosecond part.
+ EXPECT_TRUE(ffi.if_unmodified_since.has_value);
+ EXPECT_EQ(ffi.if_unmodified_since.seconds, std::int64_t{-1});
+ EXPECT_EQ(ffi.if_unmodified_since.nanoseconds, std::uint32_t{999999000});
+ EXPECT_TRUE(ffi.content_length_hint.has_value);
+ EXPECT_EQ(ffi.content_length_hint.value, std::uint64_t{42});
+ EXPECT_EQ(ffi.concurrent, std::size_t{4});
+ EXPECT_TRUE(ffi.chunk.has_value);
+ EXPECT_EQ(ffi.chunk.value, std::size_t{16});
+ EXPECT_TRUE(ffi.gap.has_value);
+ EXPECT_EQ(ffi.gap.value, std::size_t{32});
+ EXPECT_TRUE(ffi.override_content_type.has_value);
+ EXPECT_EQ(std::string(ffi.override_content_type.value),
+ "override_content_type");
+ EXPECT_TRUE(ffi.override_cache_control.has_value);
+ EXPECT_EQ(std::string(ffi.override_cache_control.value),
+ "override_cache_control");
+ EXPECT_TRUE(ffi.override_content_disposition.has_value);
+ EXPECT_EQ(std::string(ffi.override_content_disposition.value),
+ "override_content_disposition");
+}
+
+TEST(OptionsTest, ReadOptionsStructuredBindingsKeepMemberOrder) {
+ opendal::ReadOptions options;
+ auto &[range, version, if_match, if_none_match, if_modified_since,
+ if_unmodified_since, content_length_hint, concurrent, chunk, gap,
+ override_content_type, override_cache_control,
+ override_content_disposition] = options;
+
+ EXPECT_EQ(&range, &options.range);
+ EXPECT_EQ(&version, &options.version);
+ EXPECT_EQ(&if_match, &options.if_match);
+ EXPECT_EQ(&if_none_match, &options.if_none_match);
+ EXPECT_EQ(&if_modified_since, &options.if_modified_since);
+ EXPECT_EQ(&if_unmodified_since, &options.if_unmodified_since);
+ EXPECT_EQ(&content_length_hint, &options.content_length_hint);
+ EXPECT_EQ(&concurrent, &options.concurrent);
+ EXPECT_EQ(&chunk, &options.chunk);
+ EXPECT_EQ(&gap, &options.gap);
+ EXPECT_EQ(&override_content_type, &options.override_content_type);
+ EXPECT_EQ(&override_cache_control, &options.override_cache_control);
+ EXPECT_EQ(&override_content_disposition,
+ &options.override_content_disposition);
+}
+
+TEST(OptionsTest, DefaultReadOptionsReachBridgeAbsent) {
+ const opendal::ReadOptions options;
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_EQ(ffi.range.kind, std::uint8_t{0});
+ EXPECT_EQ(ffi.range.start, std::uint64_t{0});
+ EXPECT_EQ(ffi.range.end, std::uint64_t{0});
+ EXPECT_FALSE(ffi.version.has_value);
+ EXPECT_FALSE(ffi.if_match.has_value);
+ EXPECT_FALSE(ffi.if_none_match.has_value);
+ EXPECT_FALSE(ffi.if_modified_since.has_value);
+ EXPECT_FALSE(ffi.if_unmodified_since.has_value);
+ EXPECT_FALSE(ffi.content_length_hint.has_value);
+ EXPECT_EQ(ffi.concurrent, std::size_t{0});
+ EXPECT_FALSE(ffi.chunk.has_value);
+ EXPECT_FALSE(ffi.gap.has_value);
+ EXPECT_FALSE(ffi.override_content_type.has_value);
+ EXPECT_FALSE(ffi.override_cache_control.has_value);
+ EXPECT_FALSE(ffi.override_content_disposition.has_value);
+}
+
+TEST(OptionsTest, ReadOptionsRangesReadOnMemory) {
+ opendal::Operator op("memory");
+ op.Write("read_ranges", "0123456789");
+
+ const std::pair<opendal::ReadRange, std::string> cases[] = {
+ {opendal::ReadRange::Full(), "0123456789"},
+ {opendal::ReadRange::Offset(7), "789"},
+ {opendal::ReadRange::Range(2, 5), "234"},
+ {opendal::ReadRange::Suffix(2), "89"},
+ // A suffix reads at most the whole file.
+ {opendal::ReadRange::Suffix(1024), "0123456789"},
+ // An `end` that is not after `start` reads nothing, as on `main`, even
+ // past the end of the file.
+ {opendal::ReadRange::Range(5, 5), ""},
+ {opendal::ReadRange::Range(5, 3), ""},
+ {opendal::ReadRange::Range(11, 11), ""},
+ {opendal::ReadRange::Range(12, 11), ""},
+ };
+ for (const auto &item : cases) {
+ opendal::ReadOptions options;
+ options.range = item.first;
+ EXPECT_EQ(op.Read("read_ranges", options), item.second)
+ << static_cast<int>(item.first.type) << " " << item.first.start << " "
+ << item.first.end;
+ }
+
+ // Otherwise, a range that ends past the end of the file fails.
+ opendal::ReadOptions past_end;
+ past_end.range = opendal::ReadRange::Range(0, 10);
+ EXPECT_EQ(op.Read("read_ranges", past_end), "0123456789");
+ for (const auto &range :
+ {opendal::ReadRange::Range(0, 11), opendal::ReadRange::Range(2, 11),
+ opendal::ReadRange::Range(10, 11)}) {
+ past_end.range = range;
+ EXPECT_THROW(op.Read("read_ranges", past_end), std::exception)
+ << range.start << " " << range.end;
+ }
+}
+
+TEST(OptionsTest, ReadOptionsSucceedOnMemory) {
+ opendal::Operator op("memory");
+ op.Write("read_succeed", "0123456789");
+
+ opendal::ReadOptions content_length_hint;
+ content_length_hint.content_length_hint = 10;
+ opendal::ReadOptions concurrent;
+ concurrent.chunk = 3;
+ concurrent.concurrent = 2;
+ opendal::ReadOptions gap;
+ gap.gap = 0;
+ opendal::ReadOptions overrides;
+ overrides.override_content_type = "text/plain";
+ overrides.override_cache_control = "no-cache";
+ overrides.override_content_disposition = "attachment";
+ for (const auto &options :
+ {content_length_hint, concurrent, gap, overrides}) {
+ EXPECT_EQ(op.Read("read_succeed", options), "0123456789");
+ }
+
+ // `chunk` reaches core: on `memory`, only a chunked read rejects an offset
+ // past the end, and `0` reads as `std::nullopt` does.
+ opendal::ReadOptions past_end;
+ past_end.range = opendal::ReadRange::Offset(100);
+ EXPECT_EQ(op.Read("read_succeed", past_end), "");
+ past_end.chunk = 0;
+ EXPECT_EQ(op.Read("read_succeed", past_end), "");
+ past_end.chunk = 4;
+ EXPECT_THAT([&] { op.Read("read_succeed", past_end); },
+ ::testing::ThrowsMessage<std::exception>(
+ ::testing::StartsWith("RangeNotSatisfied")));
+}
+
+TEST(OptionsTest, ReadOptionsErrorsStartWithErrorKind) {
+ using ::testing::AllOf;
+ using ::testing::HasSubstr;
+ using ::testing::StartsWith;
+ using ::testing::ThrowsMessage;
+
+ opendal::Operator op("memory");
+ op.Write("read_errors", "hello");
+
+ // With valid, supported options, a missing file fails with `NotFound`. The
+ // memory service ignores the `override_*` members.
+ opendal::ReadOptions overrides;
+ overrides.override_content_type = "text/plain";
+ overrides.override_cache_control = "no-cache";
+ overrides.override_content_disposition = "attachment";
+ for (const auto &options : {opendal::ReadOptions{}, overrides}) {
+ EXPECT_THAT([&] { op.Read("read_errors_missing", options); },
+ ThrowsMessage<std::exception>(StartsWith("NotFound")));
+ }
+
+ // An empty range returns an empty buffer without looking for the file.
+ opendal::ReadOptions empty;
+ empty.range = opendal::ReadRange::Range(0, 0);
+ EXPECT_EQ(op.Read("read_errors_missing", empty), "");
+
+ // The memory service advertises none of these conditions, so core rejects
+ // each one once it arrives, before looking for the file, even for an empty
+ // range.
+ const auto info = op.Info();
+ ASSERT_FALSE(info.read_with_version);
+ ASSERT_FALSE(info.read_with_if_match);
+ ASSERT_FALSE(info.read_with_if_none_match);
+ ASSERT_FALSE(info.read_with_if_modified_since);
+ ASSERT_FALSE(info.read_with_if_unmodified_since);
+ opendal::ReadOptions version;
+ version.version = "version";
+ opendal::ReadOptions if_match;
+ if_match.if_match = "etag";
+ opendal::ReadOptions if_none_match;
+ if_none_match.if_none_match = "etag";
+ opendal::ReadOptions if_modified_since;
+ if_modified_since.if_modified_since = std::chrono::system_clock::now();
+ opendal::ReadOptions if_unmodified_since;
+ if_unmodified_since.if_unmodified_since = std::chrono::system_clock::now();
+ const std::pair<std::string, opendal::ReadOptions> cases[] = {
+ {"version", version},
+ {"if_match", if_match},
+ {"if_none_match", if_none_match},
+ {"if_modified_since", if_modified_since},
+ {"if_unmodified_since", if_unmodified_since},
+ };
+ for (const auto &item : cases) {
+ for (const auto &range :
+ {opendal::ReadRange::Full(), opendal::ReadRange::Range(0, 0)}) {
+ for (const char *path : {"read_errors", "read_errors_missing"}) {
+ auto options = item.second;
+ options.range = range;
+ EXPECT_THAT([&] { op.Read(path, options); },
+ ThrowsMessage<std::exception>(AllOf(
+ StartsWith("Unsupported"),
+ HasSubstr("with the arguments " + item.first + "."))))
+ << item.first << " on " << path << " with range type "
+ << static_cast<int>(range.type);
+ }
+ }
+ }
+}
diff --git a/dev/src/generate/cpp.rs b/dev/src/generate/cpp.rs
index c42032791d..5fc219745d 100644
--- a/dev/src/generate/cpp.rs
+++ b/dev/src/generate/cpp.rs
@@ -552,6 +552,17 @@ struct OptionsSpec {
/// doc describes options that C++ does not expose, and name every member
/// in `fields`.
cpp_doc: &'static [&'static str],
+ /// C++ docs, in core's doc syntax, that replace core's doc of a member
+ /// where core's doc does not hold for C++, as `(member, doc lines)`. A
+ /// `BytesRange` member needs one, because core documents it in Rust range
+ /// syntax.
+ cpp_member_docs: &'static [(&'static str, &'static [&'static str])],
+ /// C++ wording for core doc text that does not hold for C++, as `(core
+ /// text, C++ text)` in core's doc syntax. Each applies within the
+ /// paragraphs of the struct doc and the member docs that come from core.
+ /// Generation fails when one matches nothing, so a reworded core doc gets
+ /// reviewed again.
+ cpp_rewrites: &'static [(&'static str, &'static str)],
}
/// Options structs generated into `include/options.hpp`. The other options
@@ -571,6 +582,8 @@ const OPTIONS: &[OptionsSpec] = {
("deleted", Bool),
],
cpp_doc: &[],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[],
},
OptionsSpec {
name: "StatOptions",
@@ -586,6 +599,8 @@ const OPTIONS: &[OptionsSpec] = {
("override_content_disposition", OptionString),
],
cpp_doc: &[],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[],
},
OptionsSpec {
name: "DeleteOptions",
@@ -600,6 +615,61 @@ const OPTIONS: &[OptionsSpec] = {
"[`ErrorKind::Unsupported`] when the operator's",
"[`Capability::delete_with_version`] is false, even if the
path is missing.",
],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[],
+ },
+ OptionsSpec {
+ name: "ReadOptions",
+ brief: "Options for read operations.",
+ fields: &[
+ ("range", BytesRange),
+ ("version", OptionString),
+ ("if_match", OptionString),
+ ("if_none_match", OptionString),
+ ("if_modified_since", OptionTimestamp),
+ ("if_unmodified_since", OptionTimestamp),
+ ("content_length_hint", OptionU64),
+ ("concurrent", Usize),
+ ("chunk", OptionUsize),
+ ("gap", OptionUsize),
+ ("override_content_type", OptionString),
+ ("override_cache_control", OptionString),
+ ("override_content_disposition", OptionString),
+ ],
+ cpp_doc: &[],
+ // Core documents `range` in Rust range syntax, and `gap` for
+ // `Reader::fetch`, which C++ does not expose.
+ cpp_member_docs: &[
+ (
+ "range",
+ &[
+ "Read only this byte range of the file. For a file of
`n` bytes:",
+ "",
+ "- `ReadRange::Full()`, the default, reads bytes `[0,
n)`.",
+ "- `ReadRange::Offset(1024)` reads bytes `[1024, n)`.",
+ "- `ReadRange::Range(0, 1024)` reads bytes `[0,
1024)`.",
+ "- `ReadRange::Suffix(1024)` reads the last `min(1024,
n)` bytes.",
+ "",
+ "A `ReadRange::Range` whose `end` is not after `start`
reads nothing. Otherwise, a",
+ "`ReadRange::Range` whose `end` is past the end of the
file fails the read.",
+ ],
+ ),
+ (
+ "gap",
+ &[
+ "Each call to `opendal::Operator::Read` reads a single
byte range, so `gap`",
+ "has no effect.",
+ ],
+ ),
+ ],
+ // C++ does not expose `limit` yet, and has no presign API.
+ cpp_rewrites: &[
+ (
+ "A read with a zero limit or an empty range validates",
+ "A read with an empty range, such as `ReadRange::Range(0,
0)`, validates",
+ ),
+ (", including for presigned read requests.", "."),
+ ],
},
]
};
@@ -686,23 +756,40 @@ impl CppNames {
}
/// Map one core option field to its public C++ member, bridge field, and
-/// conversions.
+/// conversions, documented by `doc` in core's doc syntax.
///
/// Fails for a kind the bridge cannot carry yet, so such a field cannot be
/// listed in `OPTIONS` by mistake.
fn option_member(
options: &str,
- field: &core_options::OptionField,
+ name: &str,
kind: OptionKind,
+ doc: &[String],
names: &CppNames,
) -> Result<OptionMember> {
- let name = field.name.as_str();
let member = format!("options.{name}");
let bridge_field = format!("opts.{name}");
// (public type, member initializer, bridge type, C++ conversion, Rust
// conversion)
let (cpp_type, cpp_init, bridge_type, cpp_value, rust_value) = match kind {
OptionKind::Bool => ("bool", "{false}", "bool", member, bridge_field),
+ OptionKind::Usize => ("std::size_t", "{0}", "usize", member,
bridge_field),
+ OptionKind::OptionU64 => (
+ "std::optional<std::uint64_t>",
+ "",
+ "OptionalU64",
+ format!("ToFfiOptionalU64({member})"),
+ format!("optional_u64({bridge_field})"),
+ ),
+ // `ReadRange`, declared in the options header, is the C++ form of a
+ // core `BytesRange`.
+ OptionKind::BytesRange => (
+ "ReadRange",
+ "",
+ "FfiBytesRange",
+ format!("ToFfiBytesRange({member})"),
+ format!("bytes_range({bridge_field})"),
+ ),
OptionKind::OptionUsize => (
"std::optional<std::size_t>",
"",
@@ -729,7 +816,7 @@ fn option_member(
};
Ok(OptionMember {
name: name.to_string(),
- hpp_doc_lines: option_doc_lines(&field.doc, HPP_DOC_PREFIX, names),
+ hpp_doc_lines: option_doc_lines(doc, HPP_DOC_PREFIX, names),
hpp_member: format!("{cpp_type} {name}{cpp_init};"),
bridge_type,
fallible: rust_value.ends_with('?'),
@@ -756,8 +843,46 @@ fn option_member(
/// - A paragraph that ends with a backslash gets an empty HTML comment,
/// which Doxygen drops, so the comment line does not end with a backslash
/// and continue onto the next source line.
+/// - C++ has no `Option`, so "`Some(0)` has the same behavior as `None`"
+/// reads "`0` has the same behavior as `std::nullopt`".
+/// - Core's paragraph that points to the performance guide is dropped,
+/// because that guide covers the Rust API only. Only the exact paragraph
+/// is dropped, so a reworded one shows up in review instead of
+/// disappearing.
fn option_doc_lines(doc: &[String], prefix: &str, names: &CppNames) ->
Vec<String> {
- // Markdown blocks, each with whether a blank line precedes it in core.
+ let mut lines = Vec::new();
+ for (after_blank, text) in doc_blocks(doc) {
+ if text == PERFORMANCE_GUIDE {
+ continue;
+ }
+ if after_blank && !lines.is_empty() {
+ lines.push(String::new());
+ }
+ let text = text.replace(
+ "`Some(0)` has the same behavior as `None`",
+ "`0` has the same behavior as `std::nullopt`",
+ );
+ let text = rewrite_code_spans(&strip_crate_reference_links(&text),
|code| {
+ cpp_code_span(code, names)
+ });
+ let mut text = doxygen_text(&text);
+ if text.ends_with('\\') {
+ text.push_str("<!---->");
+ }
+ lines.extend(wrap_doc(&text, prefix, HPP_COLUMN_LIMIT));
+ }
+ lines
+}
+
+/// Core's paragraph that points to the Rust performance guide.
+const PERFORMANCE_GUIDE: &str = "Refer to the \
+ [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)
\
+ for more details.";
+
+/// 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.
+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;
@@ -779,19 +904,30 @@ fn option_doc_lines(doc: &[String], prefix: &str, names:
&CppNames) -> Vec<Strin
after_blank = false;
continues = !heading;
}
+ blocks
+}
+
+/// `doc` with `rewrites` applied within each of its Markdown blocks, marking
+/// in `matched` each rewrite that matched.
+///
+/// With rewrites, the result has one line per block, which
+/// `option_doc_lines` groups into the same blocks.
+fn rewrite_doc(doc: &[String], rewrites: &[(&str, &str)], matched: &mut
[bool]) -> Vec<String> {
+ if rewrites.is_empty() {
+ return doc.to_vec();
+ }
let mut lines = Vec::new();
- for (after_blank, text) in blocks {
+ for (after_blank, mut text) in doc_blocks(doc) {
+ for (&(from, to), matched) in rewrites.iter().zip(matched.iter_mut()) {
+ if text.contains(from) {
+ *matched = true;
+ text = text.replace(from, to);
+ }
+ }
if after_blank {
lines.push(String::new());
}
- let text = rewrite_code_spans(&strip_crate_reference_links(&text),
|code| {
- cpp_code_span(code, names)
- });
- let mut text = doxygen_text(&text);
- if text.ends_with('\\') {
- text.push_str("<!---->");
- }
- lines.extend(wrap_doc(&text, prefix, HPP_COLUMN_LIMIT));
+ lines.push(text);
}
lines
}
@@ -799,10 +935,11 @@ fn option_doc_lines(doc: &[String], prefix: &str, names:
&CppNames) -> Vec<Strin
/// The doc of a public options struct after its `@brief` block.
///
/// The released `@brief` replaces core's summary paragraph, so the doc is
-/// `cpp_doc` followed by the rest of core's struct doc, both rendered by
-/// `option_doc_lines`. When that doc or a member doc names an error kind, a
-/// last paragraph tells C++ callers how such an error reaches them, with the
-/// first kind named as its example.
+/// `cpp_doc` followed by the rest of core's struct doc `core_doc`, both
+/// rendered by `option_doc_lines`. `core_doc` and `member_docs` come with
+/// their C++ rewrites and C++ member docs applied. When that doc or a member
+/// doc names an error kind, a last paragraph tells C++ callers how such an
+/// error reaches them, with the first kind named as its example.
fn struct_doc_lines(
cpp_doc: &[&str],
core_doc: &[String],
@@ -934,7 +1071,9 @@ fn doxygen_text(text: &str) -> String {
/// would silently break source compatibility, if a field is listed twice, if
/// a field's kind in core differs from its listed kind, because that would
/// change the public C++ member type, or if a spec's `cpp_doc` does not name
-/// one of its fields, because the doc would then list stale members.
+/// one of its fields, because the doc would then list stale members. It also
+/// fails if a C++ member doc documents no listed field, if a `BytesRange`
+/// field has no C++ doc, or if a C++ rewrite matches no core doc text.
fn options_models(
parsed: &[core_options::OptionsStruct],
specs: &[OptionsSpec],
@@ -946,6 +1085,17 @@ fn options_models(
.iter()
.find(|s| s.name == spec.name)
.with_context(|| format!("OPTIONS struct `{}` is missing from
core", spec.name))?;
+ if let Some((name, _)) = spec
+ .cpp_member_docs
+ .iter()
+ .find(|(name, _)| !spec.fields.iter().any(|(listed, _)| listed ==
name))
+ {
+ bail!(
+ "the C++ doc of `{}::{name}` documents no listed member",
+ spec.name
+ );
+ }
+ let mut rewritten = vec![false; spec.cpp_rewrites.len()];
let mut members = Vec::with_capacity(spec.fields.len());
let mut member_docs = Vec::with_capacity(spec.fields.len());
for (i, &(name, kind)) in spec.fields.iter().enumerate() {
@@ -969,9 +1119,30 @@ fn options_models(
field.kind
);
}
- members.push(option_member(spec.name, field, kind, names)?);
- member_docs.push(field.doc.as_slice());
+ let doc = match spec
+ .cpp_member_docs
+ .iter()
+ .find(|(member, _)| *member == name)
+ {
+ Some((_, doc)) => doc.iter().map(|line|
line.to_string()).collect(),
+ None if kind == OptionKind::BytesRange => bail!(
+ "`{}::{name}` needs a C++ doc, because core documents it
in Rust range syntax",
+ spec.name
+ ),
+ None => rewrite_doc(&field.doc, spec.cpp_rewrites, &mut
rewritten),
+ };
+ members.push(option_member(spec.name, name, kind, &doc, names)?);
+ member_docs.push(doc);
+ }
+ let core_doc = rewrite_doc(&core.doc, spec.cpp_rewrites, &mut
rewritten);
+ if let Some(i) = rewritten.iter().position(|matched| !matched) {
+ bail!(
+ "core `{}` docs no longer contain `{}`; review its C++
rewrite",
+ spec.name,
+ spec.cpp_rewrites[i].0
+ );
}
+ let member_docs: Vec<&[String]> =
member_docs.iter().map(Vec::as_slice).collect();
if !spec.cpp_doc.is_empty() {
let cpp_doc = spec.cpp_doc.join(" ");
if let Some((name, _)) = spec
@@ -997,7 +1168,7 @@ fn options_models(
brief: spec.brief,
fills_defaults: !unexposed.is_empty() ||
core.has_unmirrored_fields,
fallible: members.iter().any(|m| m.fallible),
- hpp_doc_lines: struct_doc_lines(spec.cpp_doc, &core.doc,
&member_docs, names),
+ hpp_doc_lines: struct_doc_lines(spec.cpp_doc, &core_doc,
&member_docs, names),
members,
unexposed,
});
@@ -1185,9 +1356,9 @@ mod tests {
assert!(err.contains("`cache_control` is missing from core"));
}
- /// `ListOptions`, `StatOptions`, and `DeleteOptions` as
- /// `bindings/cpp/include/data_structure.hpp` declared them on `main`
before
- /// they were generated, copied verbatim.
+ /// `ListOptions`, `StatOptions`, `DeleteOptions`, `ReadRange`, and
+ /// `ReadOptions` 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,
/// and position. The generated header adds doc comments, which these texts
/// omit.
@@ -1227,6 +1398,57 @@ struct DeleteOptions {
bool recursive{false};
};"#;
+ const MAIN_READ_RANGE: &str = r#"/**
+ * @struct ReadRange
+ * @brief Byte range used by read operations.
+ */
+struct ReadRange {
+ enum class Type : std::uint8_t {
+ FULL = 0,
+ OFFSET = 1,
+ RANGE = 2,
+ SUFFIX = 3,
+ };
+
+ Type type{Type::FULL};
+ std::uint64_t start{0};
+ std::uint64_t end{0};
+
+ static ReadRange Full() { return {}; }
+
+ static ReadRange Offset(std::uint64_t offset) {
+ return {Type::OFFSET, offset, 0};
+ }
+
+ static ReadRange Range(std::uint64_t start, std::uint64_t end) {
+ return {Type::RANGE, start, end};
+ }
+
+ static ReadRange Suffix(std::uint64_t size) {
+ return {Type::SUFFIX, 0, size};
+ }
+};"#;
+
+ const MAIN_READ_OPTIONS: &str = r#"/**
+ * @struct ReadOptions
+ * @brief Options for read operations.
+ */
+struct ReadOptions {
+ ReadRange range;
+ std::optional<std::string> version;
+ std::optional<std::string> if_match;
+ std::optional<std::string> if_none_match;
+ std::optional<std::chrono::system_clock::time_point> if_modified_since;
+ std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
+ std::optional<std::uint64_t> content_length_hint;
+ std::size_t concurrent{0};
+ std::optional<std::size_t> chunk;
+ std::optional<std::size_t> gap;
+ std::optional<std::string> override_content_type;
+ std::optional<std::string> override_cache_control;
+ std::optional<std::string> override_content_disposition;
+};"#;
+
fn core_names() -> CppNames {
CppNames::parse(&workspace_dir()).expect("parse core names")
}
@@ -1262,7 +1484,13 @@ struct DeleteOptions {
fn test_rendered_options_header_keeps_main_declarations() {
let header = rendered_options("bindings/cpp/include/options.hpp");
let code = code_lines(&header);
- for main in [MAIN_LIST_OPTIONS, MAIN_STAT_OPTIONS,
MAIN_DELETE_OPTIONS] {
+ for main in [
+ MAIN_LIST_OPTIONS,
+ MAIN_STAT_OPTIONS,
+ MAIN_DELETE_OPTIONS,
+ MAIN_READ_RANGE,
+ MAIN_READ_OPTIONS,
+ ] {
assert!(
code.contains(&code_lines(main)),
"header no longer declares:\n{main}\n\nheader:\n{header}"
@@ -1271,8 +1499,13 @@ struct DeleteOptions {
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(), 3);
- assert!(header.contains("\n#include <chrono>\n"));
+ assert_eq!(header.matches("\nstruct ").count(), 5);
+ // `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>"] {
+ assert!(header.contains(&format!("\n#include {include}\n")));
+ }
}
/// Split doc text into paragraphs, each joined into one line of words.
@@ -1291,14 +1524,20 @@ struct DeleteOptions {
.collect()
}
- /// Core doc text as the C++ header must read it, one entry per paragraph.
+ /// Core doc text as the C++ header must read it, one entry per paragraph,
+ /// after applying `rewrites` within each paragraph.
///
/// Rustdoc links to code keep their code span, and reference-style links
/// to crate items keep their text. C++ callers read capabilities from the
/// `opendal::Capability` that `Operator::Info()` returns, and see an error
- /// kind as the name that starts `what()`.
- fn expected_paragraphs(core_doc: &[String]) -> Vec<String> {
- let text = core_doc.join("\n");
+ /// kind as the name that starts `what()`. C++ has no `Option`, and the
+ /// performance guide covers the Rust API only, so its paragraph is gone.
+ fn expected_paragraphs(core_doc: &[String], rewrites: &[(&str, &str)]) ->
Vec<String> {
+ let text = paragraphs(core_doc.iter().map(String::as_str))
+ .into_iter()
+ .map(|p| rewrites.iter().fold(p, |p, (from, to)| p.replace(from,
to)))
+ .collect::<Vec<_>>()
+ .join("\n\n");
let text = Regex::new(r"\[(`[^`]*`)\](\([^)]*\))?")
.unwrap()
.replace_all(&text, "$1");
@@ -1309,8 +1548,17 @@ struct DeleteOptions {
.replace("`crate::Capability::", "`Capability::")
.replace("`Capability::", "`opendal::Capability::")
.replace("`crate::ErrorKind::", "`")
- .replace("`ErrorKind::", "`");
+ .replace("`ErrorKind::", "`")
+ .replace(
+ "`Some(0)` has the same behavior as `None`",
+ "`0` has the same behavior as `std::nullopt`",
+ );
paragraphs(text.lines())
+ .into_iter()
+ .filter(|p| {
+ p != "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)
for more details."
+ })
+ .collect()
}
/// A rendered comment line as core wrote it: outside code spans, Doxygen
@@ -1342,9 +1590,9 @@ struct DeleteOptions {
let decl = lines
.iter()
.position(|line| {
- !line.starts_with(" ///")
- && (line.ends_with(&format!(" {name};"))
- || line.ends_with(&format!(" {name}{{false}};")))
+ let decl = line.strip_suffix(';').unwrap_or(line);
+ let decl = decl.split_once('{').map_or(decl, |(decl, _)| decl);
+ !line.starts_with(" ///") && decl.ends_with(&format!("
{name}"))
})
.unwrap_or_else(|| panic!("`{struct_name}` lacks `{name}`"));
let mut comment: Vec<String> = lines[..decl]
@@ -1381,6 +1629,45 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
[`Capability::delete_with_version`] is false, even if the path is missing.",
)];
+ /// C++ docs, in core's doc syntax, that must replace core's doc of each
+ /// listed `(struct, member)`.
+ const CPP_MEMBER_DOCS: &[(&str, &str, &str)] = &[
+ (
+ "ReadOptions",
+ "range",
+ "Read only this byte range of the file. For a file of `n` bytes:
+
+- `ReadRange::Full()`, the default, reads bytes `[0, n)`.
+- `ReadRange::Offset(1024)` reads bytes `[1024, n)`.
+- `ReadRange::Range(0, 1024)` reads bytes `[0, 1024)`.
+- `ReadRange::Suffix(1024)` reads the last `min(1024, n)` bytes.
+
+A `ReadRange::Range` whose `end` is not after `start` reads nothing.
Otherwise, a
+`ReadRange::Range` whose `end` is past the end of the file fails the read.",
+ ),
+ (
+ "ReadOptions",
+ "gap",
+ "Each call to `opendal::Operator::Read` reads a single byte range,
so `gap`
+has no effect.",
+ ),
+ ];
+
+ /// C++ wording, as `(struct, core text, C++ text)`, that must replace core
+ /// doc text in the docs of each listed struct.
+ const CPP_REWRITES: &[(&str, &str, &str)] = &[
+ (
+ "ReadOptions",
+ "A read with a zero limit or an empty range validates",
+ "A read with an empty range, such as `ReadRange::Range(0, 0)`,
validates",
+ ),
+ (
+ "ReadOptions",
+ ", including for presigned read requests.",
+ ".",
+ ),
+ ];
+
#[test]
fn test_rendered_options_header_documents_members_with_core_docs() {
let header = rendered_options("bindings/cpp/include/options.hpp");
@@ -1388,15 +1675,33 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
let kind = Regex::new(r"ErrorKind::(\w+)").unwrap();
for spec in OPTIONS {
let core = parsed.iter().find(|s| s.name == spec.name).unwrap();
+ let rewrites: Vec<(&str, &str)> = CPP_REWRITES
+ .iter()
+ .filter(|(name, ..)| *name == spec.name)
+ .map(|&(_, from, to)| (from, to))
+ .collect();
let mut docs = Vec::new();
for (name, _) in spec.fields {
- let core_doc = &core.fields.iter().find(|f| f.name ==
*name).unwrap().doc;
- let expected = expected_paragraphs(core_doc);
- assert!(
- !expected.is_empty(),
- "core `{}::{name}` has no doc",
- spec.name
- );
+ let cpp_doc = CPP_MEMBER_DOCS
+ .iter()
+ .find(|(options, member, _)| *options == spec.name &&
member == name);
+ let doc: Vec<String> = match cpp_doc {
+ Some((_, _, doc)) =>
doc.lines().map(String::from).collect(),
+ None => core
+ .fields
+ .iter()
+ .find(|f| f.name == *name)
+ .unwrap()
+ .doc
+ .clone(),
+ };
+ let applied = if cpp_doc.is_some() {
+ &[][..]
+ } else {
+ &rewrites[..]
+ };
+ let expected = expected_paragraphs(&doc, applied);
+ assert!(!expected.is_empty(), "`{}::{name}` has no doc",
spec.name);
let comment = member_comment(&header, spec.name, name);
assert_eq!(
paragraphs(comment.iter().map(String::as_str)),
@@ -1404,7 +1709,7 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
"doc of `{}::{name}`",
spec.name
);
- docs.push(core_doc.join(" "));
+ docs.push(doc.join(" "));
}
// The C++ note, then core's struct doc after its summary, which
@@ -1421,8 +1726,8 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
.skip_while(|line| !line.trim().is_empty())
.cloned()
.collect();
- let mut expected = expected_paragraphs(¬e);
- expected.extend(expected_paragraphs(&details));
+ let mut expected = expected_paragraphs(¬e, &[]);
+ expected.extend(expected_paragraphs(&details, &rewrites));
docs.insert(0, details.join(" "));
docs.insert(0, note.join(" "));
if let Some(first) = kind.captures(&docs.join(" ")) {
@@ -1459,7 +1764,22 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
`Unsupported`, it throws a `std::exception` whose `what()`
starts with that kind."
)
);
- for rust in ["[`", "](", "crate::", "ErrorKind::", "`Capability::"] {
+ // C++ has no presign API, so the `ReadOptions` docs do not mention it.
+ let read = &header[header.find(" * @struct ReadOptions\n").unwrap()..];
+ let read = &read[..read.find("\n};\n").unwrap()];
+ assert!(!read.to_lowercase().contains("presign"), "{read}");
+ // The rules for `Some(0)` and the performance guide match exact core
+ // text, so a reworded one must not slip through.
+ for rust in [
+ "[`",
+ "](",
+ "crate::",
+ "ErrorKind::",
+ "`Capability::",
+ "Some(",
+ "`None`",
+ "performance guide",
+ ] {
assert!(!header.contains(rust), "header contains `{rust}`");
}
@@ -1472,6 +1792,25 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
"capability.hpp lacks `{member}`"
);
}
+ // Each referenced `ReadRange` factory is declared, and
+ // `Operator::Read` takes the `ReadOptions`.
+ for reference in header.split("`ReadRange::").skip(1) {
+ let end = reference
+ .find(|c: char| !c.is_alphanumeric() && c != '_')
+ .unwrap();
+ let factory = &reference[..end];
+ assert!(
+ header.contains(&format!(" static ReadRange {factory}(")),
+ "`ReadRange` lacks `{factory}`"
+ );
+ }
+ let operator =
fs::read_to_string(workspace_dir().join("bindings/cpp/include/opendal.hpp"))
+ .expect("read opendal.hpp");
+ assert!(
+ operator.contains(
+ " std::string Read(std::string_view path, const ReadOptions
&options);\n"
+ )
+ );
}
#[test]
@@ -1559,6 +1898,86 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
assert!(lines.iter().all(|line| !line.ends_with('\\')));
}
+ #[test]
+ fn test_option_doc_lines_replace_rust_only_text() {
+ let doc = [
+ "Set `chunk`. `Some(0)` has the same behavior as `None`.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for more details.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for tuning details.",
+ ]
+ .map(String::from);
+ // Only the exact performance guide paragraph is dropped.
+ assert_eq!(
+ option_doc_lines(&doc, HPP_DOC_PREFIX, &core_names()),
+ [
+ "Set `chunk`. `0` has the same behavior as `std::nullopt`.",
+ "",
+ "Refer to the [performance",
+
"guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for tuning details.",
+ ]
+ );
+ // Dropping a leading paragraph leaves no leading blank line.
+ assert_eq!(
+ option_doc_lines(&doc[2..5], HPP_DOC_PREFIX, &core_names()),
+ Vec::<String>::new()
+ );
+ assert_eq!(
+ option_doc_lines(&doc[2..], HPP_DOC_PREFIX, &core_names())[0],
+ "Refer to the [performance"
+ );
+ }
+
+ #[test]
+ fn test_rewrite_doc_applies_within_blocks() {
+ let doc = [
+ "Summary.",
+ "",
+ "A read with a zero",
+ "limit returns.",
+ "- an item with a zero",
+ " limit",
+ "# Heading",
+ "Text.",
+ ]
+ .map(String::from);
+ let mut matched = [false, false];
+ let rewritten = rewrite_doc(
+ &doc,
+ &[("a zero limit", "an empty range"), ("no such text", "")],
+ &mut matched,
+ );
+ assert_eq!(
+ rewritten,
+ [
+ "Summary.",
+ "",
+ "A read with an empty range returns.",
+ "- an item with an empty range",
+ "# Heading",
+ "Text.",
+ ]
+ );
+ assert_eq!(matched, [true, false]);
+ // The rewritten doc renders into the same blocks.
+ let names = core_names();
+ let mut unchanged = [false];
+ assert_eq!(
+ option_doc_lines(
+ &rewrite_doc(&doc, &[("x", "x")], &mut unchanged),
+ HPP_DOC_PREFIX,
+ &names
+ ),
+ option_doc_lines(&doc, HPP_DOC_PREFIX, &names)
+ );
+ // Without rewrites, the doc stays as written.
+ assert_eq!(rewrite_doc(&doc, &[], &mut []), doc);
+ }
+
#[test]
fn test_struct_doc_lines_render_core_details() {
let names = core_names();
@@ -1671,7 +2090,7 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
}
#[test]
- fn test_only_stat_options_convert_with_try_from() {
+ fn test_only_options_with_timestamps_convert_with_try_from() {
let models = options_models(&parsed_options(), OPTIONS,
&core_names()).unwrap();
let fallible: Vec<(&str, bool)> = models.iter().map(|m| (m.name,
m.fallible)).collect();
assert_eq!(
@@ -1679,7 +2098,8 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
[
("ListOptions", false),
("StatOptions", true),
- ("DeleteOptions", false)
+ ("DeleteOptions", false),
+ ("ReadOptions", true),
]
);
@@ -1696,6 +2116,9 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
assert!(rust.contains(
" if_modified_since:
optional_timestamp(opts.if_modified_since)?,\n"
));
+ assert!(rust.contains(
+ "impl TryFrom<ffi::FfiReadOptions> for
opendal::options::ReadOptions {\n type Error = opendal::Error;\n"
+ ));
}
#[test]
@@ -1709,6 +2132,8 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
brief: "",
fields,
cpp_doc: &[],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[],
};
options_models(&parsed, &[spec], &core_names())
.unwrap_err()
@@ -1761,6 +2186,30 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
Bool,
"core `DeleteOptions::version` has kind Bool, but OPTIONS
lists OptionString",
),
+ (
+ "ReadOptions",
+ "range",
+ OptionU64,
+ "core `ReadOptions::range` has kind OptionU64, but OPTIONS
lists BytesRange",
+ ),
+ (
+ "ReadOptions",
+ "content_length_hint",
+ OptionUsize,
+ "core `ReadOptions::content_length_hint` has kind OptionUsize,
but OPTIONS lists OptionU64",
+ ),
+ (
+ "ReadOptions",
+ "concurrent",
+ OptionUsize,
+ "core `ReadOptions::concurrent` has kind OptionUsize, but
OPTIONS lists Usize",
+ ),
+ (
+ "ReadOptions",
+ "chunk",
+ OptionU64,
+ "core `ReadOptions::chunk` has kind OptionU64, but OPTIONS
lists OptionUsize",
+ ),
] {
let mut changed = parsed.clone();
changed
@@ -1792,9 +2241,22 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
.to_string(),
"OPTIONS member `DeleteOptions::recursive` is missing from core"
);
+ let mut without_range = parsed.clone();
+ without_range
+ .iter_mut()
+ .find(|s| s.name == "ReadOptions")
+ .unwrap()
+ .fields
+ .retain(|f| f.name != "range");
assert_eq!(
- error("ReadOptions", &[("range", BytesRange)]),
- "the C++ bridge cannot carry `ReadOptions::range` of kind
BytesRange yet"
+ options_models(&without_range, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ "OPTIONS member `ReadOptions::range` is missing from core"
+ );
+ assert_eq!(
+ error("WriteOptions", &[("expires", OptionDuration)]),
+ "the C++ bridge cannot carry `WriteOptions::expires` of kind
OptionDuration yet"
);
// A C++ note that no longer names every exposed member is stale.
let stale = OptionsSpec {
@@ -1802,6 +2264,8 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
brief: "",
fields: &[("version", OptionString), ("recursive", Bool)],
cpp_doc: &["C++ exposes only `version`; `recursively` is not a
member."],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[],
};
assert_eq!(
options_models(&parsed, &[stale], &core_names())
@@ -1809,6 +2273,64 @@ conditions below cannot be set from C++ yet. Setting
`version` fails with
.to_string(),
"the C++ doc of `DeleteOptions` does not name its member
`recursive`"
);
+ // Core documents a `BytesRange` in Rust range syntax.
+ assert_eq!(
+ error("ReadOptions", &[("range", BytesRange)]),
+ "`ReadOptions::range` needs a C++ doc, because core documents it
in Rust range syntax"
+ );
+ // A C++ member doc for a member that is not listed is stale.
+ let stale = OptionsSpec {
+ name: "ReadOptions",
+ brief: "",
+ fields: &[("version", OptionString)],
+ cpp_doc: &[],
+ cpp_member_docs: &[("gap", &["Has no effect."])],
+ cpp_rewrites: &[],
+ };
+ assert_eq!(
+ options_models(&parsed, &[stale], &core_names())
+ .unwrap_err()
+ .to_string(),
+ "the C++ doc of `ReadOptions::gap` documents no listed member"
+ );
+ }
+
+ #[test]
+ fn test_options_models_reject_stale_rewrites() {
+ let read = OPTIONS.iter().find(|s| s.name == "ReadOptions").unwrap();
+ let (from, _) = read.cpp_rewrites[0];
+ let mut reworded = parsed_options();
+ for line in &mut reworded
+ .iter_mut()
+ .find(|s| s.name == "ReadOptions")
+ .unwrap()
+ .doc
+ {
+ *line = line.replace("zero limit", "limit of zero");
+ }
+ assert_eq!(
+ options_models(&reworded, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ format!("core `ReadOptions` 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",
+ brief: "",
+ fields: &[("version", OptionKind::OptionString)],
+ cpp_doc: &[],
+ cpp_member_docs: &[],
+ cpp_rewrites: &[("stored version", "stored C++ version")],
+ };
+ let models = options_models(&parsed_options(), &[spec],
&core_names()).unwrap();
+ assert!(
+ models[0].members[0]
+ .hpp_doc_lines
+ .join(" ")
+ .contains("which stored C++ version the read returns")
+ );
}
#[test]
diff --git a/dev/src/generate/cpp/options_converter_cpp.j2
b/dev/src/generate/cpp/options_converter_cpp.j2
index 9b5227ae12..5ae2e1b98f 100644
--- a/dev/src/generate/cpp/options_converter_cpp.j2
+++ b/dev/src/generate/cpp/options_converter_cpp.j2
@@ -50,6 +50,14 @@ ffi::options::OptionalUsize ToFfiOptionalUsize(
return ffi::options::OptionalUsize{false, 0};
}
+ffi::options::OptionalU64 ToFfiOptionalU64(
+ const std::optional<std::uint64_t> &value) {
+ if (value.has_value()) {
+ return ffi::options::OptionalU64{true, *value};
+ }
+ return ffi::options::OptionalU64{false, 0};
+}
+
ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
const std::optional<std::chrono::system_clock::time_point> &value) {
if (!value.has_value()) {
@@ -73,6 +81,11 @@ ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
static_cast<std::uint32_t>(nanoseconds)};
}
+ffi::options::FfiBytesRange ToFfiBytesRange(const ReadRange &range) {
+ return ffi::options::FfiBytesRange{static_cast<std::uint8_t>(range.type),
+ range.start, range.end};
+}
+
} // namespace
{%- for s in options %}
diff --git a/dev/src/generate/cpp/options_hpp.j2
b/dev/src/generate/cpp/options_hpp.j2
index eed6755028..2d0a63c5b3 100644
--- a/dev/src/generate/cpp/options_hpp.j2
+++ b/dev/src/generate/cpp/options_hpp.j2
@@ -24,10 +24,44 @@
#include <chrono>
#include <cstddef>
+#include <cstdint>
#include <optional>
#include <string>
namespace opendal {
+
+{#- `ReadRange` is the C++ form of a core `BytesRange` member. #}
+
+/**
+ * @struct ReadRange
+ * @brief Byte range used by read operations.
+ */
+struct ReadRange {
+ enum class Type : std::uint8_t {
+ FULL = 0,
+ OFFSET = 1,
+ RANGE = 2,
+ SUFFIX = 3,
+ };
+
+ Type type{Type::FULL};
+ std::uint64_t start{0};
+ std::uint64_t end{0};
+
+ static ReadRange Full() { return {}; }
+
+ static ReadRange Offset(std::uint64_t offset) {
+ return {Type::OFFSET, offset, 0};
+ }
+
+ static ReadRange Range(std::uint64_t start, std::uint64_t end) {
+ return {Type::RANGE, start, end};
+ }
+
+ static ReadRange Suffix(std::uint64_t size) {
+ return {Type::SUFFIX, 0, size};
+ }
+};
{%- for s in options %}
/**
diff --git a/dev/src/generate/cpp/options_rs.j2
b/dev/src/generate/cpp/options_rs.j2
index e5a492a74b..5efd6a5d78 100644
--- a/dev/src/generate/cpp/options_rs.j2
+++ b/dev/src/generate/cpp/options_rs.j2
@@ -34,11 +34,23 @@ pub mod ffi {
value: usize,
}
+ struct OptionalU64 {
+ has_value: bool,
+ value: u64,
+ }
+
struct OptionalTimestamp {
has_value: bool,
seconds: i64,
nanoseconds: u32,
}
+
+ /// A C++ `ReadRange`, whose `kind` is its `ReadRange::Type`.
+ struct FfiBytesRange {
+ kind: u8,
+ start: u64,
+ end: u64,
+ }
{%- for s in options %}
struct {{ s.bridge_name }} {
@@ -57,6 +69,10 @@ fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
v.has_value.then_some(v.value)
}
+fn optional_u64(v: ffi::OptionalU64) -> Option<u64> {
+ v.has_value.then_some(v.value)
+}
+
fn optional_timestamp(
v: ffi::OptionalTimestamp,
) -> opendal::Result<Option<opendal::raw::Timestamp>> {
@@ -69,6 +85,15 @@ fn optional_timestamp(
Ok(None)
}
}
+
+fn bytes_range(v: ffi::FfiBytesRange) -> opendal::BytesRange {
+ match v.kind {
+ 1 => opendal::BytesRange::new(v.start, None),
+ 2 => opendal::BytesRange::new(v.start,
Some(v.end.saturating_sub(v.start))),
+ 3 => opendal::BytesRange::suffix(v.end),
+ _ => opendal::BytesRange::default(),
+ }
+}
{%- for s in options %}
{% if s.fallible %}
impl TryFrom<ffi::{{ s.bridge_name }}> for opendal::options::{{ s.name }} {