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 735d03e882 feat(bindings/cpp): generate StatOptions from core (#9361)
735d03e882 is described below

commit 735d03e88200c8c25d90c214f6cc21f75782c7a7
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 14:24:10 2026 +0530

    feat(bindings/cpp): generate StatOptions from core (#9361)
    
    * feat(bindings/cpp): generate StatOptions from core
    
    Generate opendal::StatOptions and the three layers behind it from
    core/core/src/types/options.rs, as ListOptions already is: the public
    struct in include/options.hpp, the cxx bridge struct in src/options.rs,
    the C++ ToFfiOptions conversion in src/utils/options_converter.cpp, and
    the Rust conversion into core. StatOptions keeps its member names,
    types, and order, so its layout and its positional, designated, and
    structured-binding use stay the same. Core's if_version_match,
    if_version_not_match, and checksum stay unexposed.
    
    The bridge now carries Option<Timestamp>. A struct with a timestamp
    member converts into core with TryFrom, so an out-of-range time still
    fails the stat as it did before.
    
    Member docs render core's ErrorKind references as the kind name that
    starts the what() of the thrown exception, and the struct doc says so.
    Doc text is escaped for Doxygen, and no generated comment line ends
    with a backslash, which would continue the comment onto the member
    declaration.
    
    The Bindings Cpp CI also runs on changes to
    core/core/src/types/error.rs, which the generator now reads.
    
    Part of #9324.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/cpp): generate StatOptions from core
    
    Render each options struct's core doc after the released `@brief`
    block, as `///` lines, so StatOptions carries core's "With valid,
    supported options, stat returns NotFound for a missing file" (#9348)
    and ListOptions carries its groups and its Unsupported sentence. The
    error-kind note now follows those paragraphs and names the first kind
    that the struct or member docs name. Reference-style links to crate
    items keep their text, and headings and list items stay on their own
    lines.
    
    Test on memory that each unsupported stat option fails with
    Unsupported for a missing file too, and that default and override_*
    options fail with NotFound there.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/cpp): generate StatOptions from core
    
    Compare each generated member doc, and each struct doc, with core's full
    doc paragraph by paragraph again, as #9331 did. The test derives the
    expected prose from core: links keep their code span or text,
    capabilities read as `opendal::Capability::` members, and error kinds
    read as the name that starts `what()`. It looks up each declaration
    inside its own `struct ... { ... };` block. This replaces the
    MEMBER_REFERENCES and STRUCT_REFERENCES inventories.
    
    The name-rewrite unit test also covers `[`crate::ErrorKind::NotFound`]`
    reading `NotFound`.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 .github/workflows/ci_bindings_cpp.yml         |   1 +
 bindings/cpp/include/data_structure.hpp       |  15 -
 bindings/cpp/include/options.hpp              |  87 +++
 bindings/cpp/src/lib.rs                       |  29 +-
 bindings/cpp/src/operator.cpp                 |  15 +-
 bindings/cpp/src/options.rs                   |  52 ++
 bindings/cpp/src/options_test.rs              |  95 +++-
 bindings/cpp/src/utils/options_converter.cpp  |  38 ++
 bindings/cpp/src/utils/options_converter.hpp  |   1 +
 bindings/cpp/tests/options_test.cpp           | 143 +++++
 dev/src/generate/cpp.rs                       | 764 +++++++++++++++++++++-----
 dev/src/generate/cpp/options_converter_cpp.j2 |  25 +
 dev/src/generate/cpp/options_hpp.j2           |   4 +
 dev/src/generate/cpp/options_rs.j2            |  30 +
 14 files changed, 1093 insertions(+), 206 deletions(-)

diff --git a/.github/workflows/ci_bindings_cpp.yml 
b/.github/workflows/ci_bindings_cpp.yml
index 21cbd5ae3e..669cb66bc6 100644
--- a/.github/workflows/ci_bindings_cpp.yml
+++ b/.github/workflows/ci_bindings_cpp.yml
@@ -26,6 +26,7 @@ on:
       - main
     paths:
       - "core/core/src/types/capability.rs"
+      - "core/core/src/types/error.rs"
       - "core/core/src/types/metadata.rs"
       - "core/core/src/types/options.rs"
       - "dev/src/generate/**"
diff --git a/bindings/cpp/include/data_structure.hpp 
b/bindings/cpp/include/data_structure.hpp
index 2c4de58c23..8c4a419731 100644
--- a/bindings/cpp/include/data_structure.hpp
+++ b/bindings/cpp/include/data_structure.hpp
@@ -72,21 +72,6 @@ struct ReadRange {
   }
 };
 
-/**
- * @struct StatOptions
- * @brief Options for stat operations.
- */
-struct StatOptions {
-  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::string> override_content_type;
-  std::optional<std::string> override_cache_control;
-  std::optional<std::string> override_content_disposition;
-};
-
 /**
  * @struct ReadOptions
  * @brief Options for read operations.
diff --git a/bindings/cpp/include/options.hpp b/bindings/cpp/include/options.hpp
index 2806081ab6..2a92152f14 100644
--- a/bindings/cpp/include/options.hpp
+++ b/bindings/cpp/include/options.hpp
@@ -22,6 +22,7 @@
 
 #pragma once
 
+#include <chrono>
 #include <cstddef>
 #include <optional>
 #include <string>
@@ -32,6 +33,17 @@ namespace opendal {
  * @struct ListOptions
  * @brief Options for list and lister operations.
  */
+/// # Groups
+/// - Traversal: `recursive`.
+/// - Pagination: `limit`, `start_after`.
+/// - Versioning: `versions`, `deleted`.
+///
+/// The operation fails with `Unsupported` when an option requires a capability
+/// that the operator lacks.
+///
+/// When the operation fails with an error kind that these docs name, such as
+/// `Unsupported`, it throws a `std::exception` whose `what()` starts with that
+/// kind.
 struct ListOptions {
   /// Maximum results per request (backend hint) to control memory and
   /// throttling.
@@ -55,4 +67,79 @@ struct ListOptions {
   bool deleted{false};
 };
 
+/**
+ * @struct StatOptions
+ * @brief Options for stat operations.
+ */
+/// Each condition checks the file being observed, and every condition must 
hold
+/// for the stat to return metadata. With valid, supported options, stat 
returns
+/// `NotFound` for a missing file. 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.
+///
+/// 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 StatOptions {
+  /// Stat the given version of the file instead of the current one.
+  ///
+  /// This selects which stored version the stat describes; it is not a
+  /// condition on the file. A version that does not exist returns `NotFound`.
+  ///
+  /// Check `opendal::Capability::stat_with_version` before using this option.
+  std::optional<std::string> version;
+  /// Stat 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::stat_with_if_match`.
+  std::optional<std::string> if_match;
+  /// Stat 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::stat_with_if_none_match`.
+  std::optional<std::string> if_none_match;
+  /// Stat 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::stat_with_if_modified_since`.
+  std::optional<std::chrono::system_clock::time_point> if_modified_since;
+  /// Stat 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::stat_with_if_unmodified_since`.
+  std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
+  /// Request a `content-type` response header override from services that
+  /// support it, including for presigned stat requests.
+  std::optional<std::string> override_content_type;
+  /// Request a `cache-control` response header override from services that
+  /// support it, including for presigned stat requests.
+  std::optional<std::string> override_cache_control;
+  /// Request a `content-disposition` response header override from services
+  /// that support it, including for presigned stat requests.
+  std::optional<std::string> override_content_disposition;
+};
+
 }  // namespace opendal
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index f3d5ddfaf3..e480af586d 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -80,17 +80,6 @@ mod ffi {
         end: u64,
     }
 
-    struct FfiStatOptions {
-        version: OptionalString,
-        if_match: OptionalString,
-        if_none_match: OptionalString,
-        if_modified_since: OptionalTimestamp,
-        if_unmodified_since: OptionalTimestamp,
-        override_content_type: OptionalString,
-        override_cache_control: OptionalString,
-        override_content_disposition: OptionalString,
-    }
-
     struct FfiReadOptions {
         range: FfiBytesRange,
         version: OptionalString,
@@ -192,6 +181,8 @@ mod ffi {
         include!("opendal-cpp/src/options.rs.h");
         #[namespace = "opendal::ffi::options"]
         type FfiListOptions = crate::options::ffi::FfiListOptions;
+        #[namespace = "opendal::ffi::options"]
+        type FfiStatOptions = crate::options::ffi::FfiStatOptions;
     }
 
     extern "Rust" {
@@ -418,20 +409,6 @@ fn user_metadata(
     })
 }
 
-fn stat_options(opts: ffi::FfiStatOptions) -> Result<od::options::StatOptions> 
{
-    Ok(od::options::StatOptions {
-        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)?,
-        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 read_options(opts: ffi::FfiReadOptions) -> Result<od::options::ReadOptions> 
{
     Ok(od::options::ReadOptions {
         range: bytes_range(opts.range),
@@ -575,7 +552,7 @@ impl Operator {
     }
 
     fn stat_options(&self, path: &str, opts: ffi::FfiStatOptions) -> 
Result<ffi::Metadata> {
-        Ok(self.0.stat_options(path, stat_options(opts)?)?.into())
+        Ok(self.0.stat_options(path, opts.try_into()?)?.into())
     }
 
     fn list(&self, path: &str) -> Result<Vec<ffi::Entry>> {
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index 8b62ae1739..04985a987d 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -92,19 +92,6 @@ rust::Vec<ffi::HashMapValue> ToFfiHashMap(
   return values;
 }
 
-ffi::FfiStatOptions ToFfiOptions(const StatOptions &options) {
-  return ffi::FfiStatOptions{
-      ToFfiOptionalString(options.version),
-      ToFfiOptionalString(options.if_match),
-      ToFfiOptionalString(options.if_none_match),
-      ToFfiOptionalTimestamp(options.if_modified_since),
-      ToFfiOptionalTimestamp(options.if_unmodified_since),
-      ToFfiOptionalString(options.override_content_type),
-      ToFfiOptionalString(options.override_cache_control),
-      ToFfiOptionalString(options.override_content_disposition),
-  };
-}
-
 ffi::FfiReadOptions ToFfiOptions(const ReadOptions &options) {
   return ffi::FfiReadOptions{
       ToFfiBytesRange(options.range),
@@ -319,7 +306,7 @@ Metadata Operator::Stat(std::string_view path) {
 
 Metadata Operator::Stat(std::string_view path, const StatOptions &options) {
   return utils::parse_metadata(CheckedOperator(operator_).stat_options(
-      utils::rust_str(path), ToFfiOptions(options)));
+      utils::rust_str(path), utils::ToFfiOptions(options)));
 }
 
 std::vector<Entry> Operator::List(std::string_view path) {
diff --git a/bindings/cpp/src/options.rs b/bindings/cpp/src/options.rs
index 23a12f9600..499da4a14f 100644
--- a/bindings/cpp/src/options.rs
+++ b/bindings/cpp/src/options.rs
@@ -34,6 +34,12 @@ pub mod ffi {
         value: usize,
     }
 
+    struct OptionalTimestamp {
+        has_value: bool,
+        seconds: i64,
+        nanoseconds: u32,
+    }
+
     struct FfiListOptions {
         limit: OptionalUsize,
         start_after: OptionalString,
@@ -41,6 +47,17 @@ pub mod ffi {
         versions: bool,
         deleted: bool,
     }
+
+    struct FfiStatOptions {
+        version: OptionalString,
+        if_match: OptionalString,
+        if_none_match: OptionalString,
+        if_modified_since: OptionalTimestamp,
+        if_unmodified_since: OptionalTimestamp,
+        override_content_type: OptionalString,
+        override_cache_control: OptionalString,
+        override_content_disposition: OptionalString,
+    }
 }
 
 fn optional_string(v: ffi::OptionalString) -> Option<String> {
@@ -51,6 +68,19 @@ fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
     v.has_value.then_some(v.value)
 }
 
+fn optional_timestamp(
+    v: ffi::OptionalTimestamp,
+) -> opendal::Result<Option<opendal::raw::Timestamp>> {
+    if v.has_value {
+        Ok(Some(opendal::raw::Timestamp::new(
+            v.seconds,
+            v.nanoseconds as i32,
+        )?))
+    } else {
+        Ok(None)
+    }
+}
+
 impl From<ffi::FfiListOptions> for opendal::options::ListOptions {
     fn from(opts: ffi::FfiListOptions) -> Self {
         Self {
@@ -65,3 +95,25 @@ impl From<ffi::FfiListOptions> for 
opendal::options::ListOptions {
         }
     }
 }
+
+impl TryFrom<ffi::FfiStatOptions> for opendal::options::StatOptions {
+    type Error = opendal::Error;
+
+    fn try_from(opts: ffi::FfiStatOptions) -> Result<Self, Self::Error> {
+        Ok(Self {
+            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)?,
+            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:
+            // - `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 6d6d53e529..df923ee0ae 100644
--- a/bindings/cpp/src/options_test.rs
+++ b/bindings/cpp/src/options_test.rs
@@ -15,10 +15,13 @@
 // specific language governing permissions and limitations
 // under the License.
 
-//! The generated `ListOptions` conversion in `options.rs` carries every bridge
-//! field to the core field of the same name, and absent values stay absent.
+//! The generated `ListOptions` and `StatOptions` conversions in `options.rs`
+//! carry every bridge field to the core field of the same name, and absent
+//! values stay absent.
 
 use opendal::options::ListOptions;
+use opendal::options::StatOptions;
+use opendal::raw::Timestamp;
 
 use crate::options::ffi;
 
@@ -72,3 +75,91 @@ fn test_list_options_keep_absent_values_absent() {
 
     assert_eq!(ListOptions::from(opts), ListOptions::default());
 }
+
+fn bridge_string(value: Option<&str>) -> ffi::OptionalString {
+    ffi::OptionalString {
+        has_value: value.is_some(),
+        value: value.unwrap_or("ignored").to_string(),
+    }
+}
+
+fn bridge_timestamp(value: Option<(i64, u32)>) -> ffi::OptionalTimestamp {
+    let (seconds, nanoseconds) = value.unwrap_or((7, 7));
+    ffi::OptionalTimestamp {
+        has_value: value.is_some(),
+        seconds,
+        nanoseconds,
+    }
+}
+
+fn absent_stat_options() -> ffi::FfiStatOptions {
+    ffi::FfiStatOptions {
+        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),
+        override_content_type: bridge_string(None),
+        override_cache_control: bridge_string(None),
+        override_content_disposition: bridge_string(None),
+    }
+}
+
+#[test]
+fn test_stat_options_carry_every_field() {
+    let opts = ffi::FfiStatOptions {
+        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))),
+        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")),
+    };
+
+    let expected = StatOptions {
+        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()),
+        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!(StatOptions::try_from(opts).unwrap(), expected);
+}
+
+#[test]
+fn test_stat_options_keep_absent_values_absent() {
+    // C++ sends a value behind `has_value == false`; it must not reach core.
+    assert_eq!(
+        StatOptions::try_from(absent_stat_options()).unwrap(),
+        StatOptions::default()
+    );
+}
+
+#[test]
+fn test_stat_options_reject_out_of_range_timestamps() {
+    // The stat fails before reaching the service, as it did on `main`.
+    for opts in [
+        ffi::FfiStatOptions {
+            if_modified_since: bridge_timestamp(Some((i64::MAX, 0))),
+            ..absent_stat_options()
+        },
+        ffi::FfiStatOptions {
+            if_unmodified_since: bridge_timestamp(Some((i64::MAX, 0))),
+            ..absent_stat_options()
+        },
+    ] {
+        let err = StatOptions::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 c1b357ef5d..8c916f321a 100644
--- a/bindings/cpp/src/utils/options_converter.cpp
+++ b/bindings/cpp/src/utils/options_converter.cpp
@@ -22,7 +22,9 @@
 
 #include "utils/options_converter.hpp"
 
+#include <chrono>
 #include <cstddef>
+#include <cstdint>
 #include <optional>
 #include <string>
 
@@ -48,6 +50,29 @@ ffi::options::OptionalUsize ToFfiOptionalUsize(
   return ffi::options::OptionalUsize{false, 0};
 }
 
+ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
+    const std::optional<std::chrono::system_clock::time_point> &value) {
+  if (!value.has_value()) {
+    return ffi::options::OptionalTimestamp{false, 0, 0};
+  }
+
+  auto duration = value->time_since_epoch();
+  auto seconds_duration =
+      std::chrono::duration_cast<std::chrono::seconds>(duration);
+  auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
+                         duration - seconds_duration)
+                         .count();
+  auto seconds = seconds_duration.count();
+  if (nanoseconds < 0) {
+    --seconds;
+    nanoseconds += 1000000000;
+  }
+
+  return ffi::options::OptionalTimestamp{
+      true, static_cast<std::int64_t>(seconds),
+      static_cast<std::uint32_t>(nanoseconds)};
+}
+
 }  // namespace
 
 ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options) {
@@ -60,4 +85,17 @@ ffi::options::FfiListOptions ToFfiOptions(const ListOptions 
&options) {
   };
 }
 
+ffi::options::FfiStatOptions ToFfiOptions(const StatOptions &options) {
+  return ffi::options::FfiStatOptions{
+      ToFfiOptionalString(options.version),
+      ToFfiOptionalString(options.if_match),
+      ToFfiOptionalString(options.if_none_match),
+      ToFfiOptionalTimestamp(options.if_modified_since),
+      ToFfiOptionalTimestamp(options.if_unmodified_since),
+      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 ba41d354f3..d24f3f646d 100644
--- a/bindings/cpp/src/utils/options_converter.hpp
+++ b/bindings/cpp/src/utils/options_converter.hpp
@@ -28,5 +28,6 @@
 namespace opendal::utils {
 
 ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options);
+ffi::options::FfiStatOptions ToFfiOptions(const StatOptions &options);
 
 }  // namespace opendal::utils
diff --git a/bindings/cpp/tests/options_test.cpp 
b/bindings/cpp/tests/options_test.cpp
index 5288f6f493..f0cbc8aa30 100644
--- a/bindings/cpp/tests/options_test.cpp
+++ b/bindings/cpp/tests/options_test.cpp
@@ -17,9 +17,14 @@
  * under the License.
  */
 
+#include <chrono>
 #include <cstddef>
+#include <cstdint>
+#include <exception>
 #include <string>
+#include <utility>
 
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include "opendal.hpp"
 #include "utils/options_converter.hpp"
@@ -80,3 +85,141 @@ TEST(OptionsTest, DefaultListOptionsReachBridgeAbsent) {
   EXPECT_FALSE(ffi.versions);
   EXPECT_FALSE(ffi.deleted);
 }
+
+TEST(OptionsTest, StatOptionsPositionalInitializerReachesBridge) {
+  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
+  // `StatOptions` was generated.
+  const opendal::StatOptions options{
+      /*version=*/"version",
+      /*if_match=*/"if_match",
+      /*if_none_match=*/"if_none_match",
+      /*if_modified_since=*/modified,
+      /*if_unmodified_since=*/unmodified,
+      /*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_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.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, StatOptionsStructuredBindingsKeepMemberOrder) {
+  opendal::StatOptions options;
+  auto &[version, if_match, if_none_match, if_modified_since,
+         if_unmodified_since, override_content_type, override_cache_control,
+         override_content_disposition] = options;
+
+  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(&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, DefaultStatOptionsReachBridgeAbsent) {
+  const opendal::StatOptions options;
+
+  const auto ffi = opendal::utils::ToFfiOptions(options);
+
+  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.override_content_type.has_value);
+  EXPECT_FALSE(ffi.override_cache_control.has_value);
+  EXPECT_FALSE(ffi.override_content_disposition.has_value);
+}
+
+TEST(OptionsTest, StatOptionsOverridesSucceedOnMemory) {
+  opendal::Operator op("memory");
+  op.Write("stat_overrides", "hello");
+
+  opendal::StatOptions options;
+  options.override_content_type = "text/plain";
+  options.override_cache_control = "no-cache";
+  options.override_content_disposition = "attachment";
+
+  EXPECT_EQ(op.Stat("stat_overrides", options).content_length, 5);
+}
+
+TEST(OptionsTest, StatOptionsErrorsStartWithErrorKind) {
+  using ::testing::AllOf;
+  using ::testing::HasSubstr;
+  using ::testing::StartsWith;
+  using ::testing::ThrowsMessage;
+
+  opendal::Operator op("memory");
+  op.Write("stat_errors", "hello");
+
+  // With valid, supported options, a missing file fails with `NotFound`. The
+  // memory service ignores the `override_*` members.
+  opendal::StatOptions overrides;
+  overrides.override_content_type = "text/plain";
+  overrides.override_cache_control = "no-cache";
+  overrides.override_content_disposition = "attachment";
+  for (const auto &options : {opendal::StatOptions{}, overrides}) {
+    EXPECT_THAT([&] { op.Stat("stat_errors_missing", options); },
+                ThrowsMessage<std::exception>(StartsWith("NotFound")));
+  }
+
+  // The memory service advertises none of these conditions, so core rejects
+  // each one once it arrives, before looking for the file.
+  opendal::StatOptions version;
+  version.version = "version";
+  opendal::StatOptions if_match;
+  if_match.if_match = "etag";
+  opendal::StatOptions if_none_match;
+  if_none_match.if_none_match = "etag";
+  opendal::StatOptions if_modified_since;
+  if_modified_since.if_modified_since = std::chrono::system_clock::now();
+  opendal::StatOptions if_unmodified_since;
+  if_unmodified_since.if_unmodified_since = std::chrono::system_clock::now();
+  const std::pair<std::string, opendal::StatOptions> 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 char *path : {"stat_errors", "stat_errors_missing"}) {
+      EXPECT_THAT([&] { op.Stat(path, item.second); },
+                  ThrowsMessage<std::exception>(AllOf(
+                      StartsWith("Unsupported"),
+                      HasSubstr("with the arguments " + item.first + "."))))
+          << item.first << " on " << path;
+    }
+  }
+}
diff --git a/dev/src/generate/cpp.rs b/dev/src/generate/cpp.rs
index 59ccd6ef0e..ebd92e55a1 100644
--- a/dev/src/generate/cpp.rs
+++ b/dev/src/generate/cpp.rs
@@ -35,6 +35,8 @@ use anyhow::{Context, Result, bail};
 use minijinja::value::Serde;
 use minijinja::{Environment, context};
 use serde::Serialize;
+use std::cell::OnceCell;
+use std::collections::BTreeMap;
 use std::fs;
 use std::path::Path;
 
@@ -58,21 +60,37 @@ struct CapabilityField {
 const HPP_COLUMN_LIMIT: usize = 80;
 /// Prefix of a member doc comment in the generated header.
 const HPP_DOC_PREFIX: &str = "  /// ";
+/// Prefix of a struct doc comment in the generated options header.
+const HPP_STRUCT_DOC_PREFIX: &str = "/// ";
 
 /// Greedily wrap `text` at word boundaries so each line fits after `prefix`
 /// within `limit` columns, matching clang-format's comment reflow.
+///
+/// A `//` comment line that ends with a backslash continues on the next
+/// source line, so a word that ends with a backslash stays on one line with
+/// the word after it, as clang-format keeps them.
 fn wrap_doc(text: &str, prefix: &str, limit: usize) -> Vec<String> {
     let width = limit - prefix.len();
+    let mut units: Vec<String> = Vec::new();
+    for word in text.split_whitespace() {
+        match units.last_mut() {
+            Some(unit) if unit.ends_with('\\') => {
+                unit.push(' ');
+                unit.push_str(word);
+            }
+            _ => units.push(word.to_string()),
+        }
+    }
     let mut lines = Vec::new();
     let mut line = String::new();
-    for word in text.split_whitespace() {
-        if !line.is_empty() && line.len() + 1 + word.len() > width {
+    for unit in units {
+        if !line.is_empty() && line.len() + 1 + unit.len() > width {
             lines.push(std::mem::take(&mut line));
         }
         if !line.is_empty() {
             line.push(' ');
         }
-        line.push_str(word);
+        line.push_str(&unit);
     }
     if !line.is_empty() {
         lines.push(line);
@@ -536,17 +554,33 @@ struct OptionsSpec {
 const OPTIONS: &[OptionsSpec] = {
     use OptionKind::*;
 
-    &[OptionsSpec {
-        name: "ListOptions",
-        brief: "Options for list and lister operations.",
-        fields: &[
-            ("limit", OptionUsize),
-            ("start_after", OptionString),
-            ("recursive", Bool),
-            ("versions", Bool),
-            ("deleted", Bool),
-        ],
-    }]
+    &[
+        OptionsSpec {
+            name: "ListOptions",
+            brief: "Options for list and lister operations.",
+            fields: &[
+                ("limit", OptionUsize),
+                ("start_after", OptionString),
+                ("recursive", Bool),
+                ("versions", Bool),
+                ("deleted", Bool),
+            ],
+        },
+        OptionsSpec {
+            name: "StatOptions",
+            brief: "Options for stat operations.",
+            fields: &[
+                ("version", OptionString),
+                ("if_match", OptionString),
+                ("if_none_match", OptionString),
+                ("if_modified_since", OptionTimestamp),
+                ("if_unmodified_since", OptionTimestamp),
+                ("override_content_type", OptionString),
+                ("override_cache_control", OptionString),
+                ("override_content_disposition", OptionString),
+            ],
+        },
+    ]
 };
 
 /// Render model of one options struct. Every per-kind decision is made in
@@ -565,15 +599,20 @@ struct OptionsModel {
     unexposed: Vec<String>,
     /// Whether the Rust conversion leaves core fields to `Default::default()`.
     fills_defaults: bool,
+    /// Whether a member conversion can fail, so the Rust conversion into core
+    /// is a `TryFrom` instead of a `From`.
+    fallible: bool,
+    /// Struct doc after the `@brief` block, as `struct_doc_lines` renders it
+    /// for `///` comments. An empty line separates paragraphs.
+    hpp_doc_lines: Vec<String>,
 }
 
 #[derive(Debug, PartialEq, Serialize)]
 struct OptionMember {
     /// Field name in core, the bridge struct, and the public C++ struct.
     name: String,
-    /// Core field doc with rustdoc links rendered as code spans, each
-    /// paragraph wrapped for the header's `///` comments. An empty line
-    /// separates paragraphs.
+    /// Core field doc as `option_doc_lines` renders it for the header's `///`
+    /// comments. An empty line separates paragraphs.
     hpp_doc_lines: Vec<String>,
     /// Declaration of the public C++ member.
     hpp_member: String,
@@ -583,6 +622,46 @@ struct OptionMember {
     cpp_value: String,
     /// Expression converting the bridge field into the core field.
     rust_value: String,
+    /// Whether `rust_value` can fail and ends with `?`.
+    fallible: bool,
+}
+
+/// Core names that option docs refer to, with their C++ spellings.
+struct CppNames {
+    /// Core capabilities; each is a member of the generated
+    /// `opendal::Capability`.
+    capabilities: Vec<capability::CapabilityField>,
+    /// Each core `ErrorKind` variant and its name in an error message, which
+    /// begins the `what()` of the exception that C++ callers catch.
+    error_kinds: BTreeMap<String, String>,
+}
+
+impl CppNames {
+    fn parse(workspace_dir: &Path) -> Result<Self> {
+        let capabilities =
+            
capability::parse(&workspace_dir.join("core/core/src/types/capability.rs"))?;
+        let errors = workspace_dir.join("core/core/src/types/error.rs");
+        // `From<ErrorKind> for &'static str`, which `Display` uses, names each
+        // kind with a line such as `ErrorKind::NotFound => "NotFound",`.
+        let error_kinds: BTreeMap<String, String> = fs::read_to_string(&errors)
+            .with_context(|| format!("failed to read {}", errors.display()))?
+            .lines()
+            .filter_map(|line| {
+                let (kind, name) = line
+                    .trim()
+                    .strip_prefix("ErrorKind::")?
+                    .split_once(" => \"")?;
+                Some((kind.to_string(), name.strip_suffix("\",")?.to_string()))
+            })
+            .collect();
+        if error_kinds.get("Unsupported").map(String::as_str) != 
Some("Unsupported") {
+            bail!("no ErrorKind names parsed from {}", errors.display());
+        }
+        Ok(Self {
+            capabilities,
+            error_kinds,
+        })
+    }
 }
 
 /// Map one core option field to its public C++ member, bridge field, and
@@ -594,7 +673,7 @@ fn option_member(
     options: &str,
     field: &core_options::OptionField,
     kind: OptionKind,
-    capabilities: &[capability::CapabilityField],
+    names: &CppNames,
 ) -> Result<OptionMember> {
     let name = field.name.as_str();
     let member = format!("options.{name}");
@@ -617,65 +696,213 @@ fn option_member(
             format!("ToFfiOptionalString({member})"),
             format!("optional_string({bridge_field})"),
         ),
+        // Core rejects a time outside its range.
+        OptionKind::OptionTimestamp => (
+            "std::optional<std::chrono::system_clock::time_point>",
+            "",
+            "OptionalTimestamp",
+            format!("ToFfiOptionalTimestamp({member})"),
+            format!("optional_timestamp({bridge_field})?"),
+        ),
         _ => bail!("the C++ bridge cannot carry `{options}::{name}` of kind 
{kind:?} yet"),
     };
     Ok(OptionMember {
         name: name.to_string(),
-        hpp_doc_lines: option_doc_lines(&field.doc, capabilities),
+        hpp_doc_lines: option_doc_lines(&field.doc, HPP_DOC_PREFIX, names),
         hpp_member: format!("{cpp_type} {name}{cpp_init};"),
         bridge_type,
+        fallible: rust_value.ends_with('?'),
         cpp_value,
         rust_value,
     })
 }
 
-/// The core doc comment of an option field as it reads in the C++ header.
+/// A core doc comment as it reads in `///` comments that start with
+/// `prefix` in the C++ header.
 ///
-/// Each paragraph is wrapped to fit the header's `///` comments, and an empty
-/// line separates paragraphs. Rustdoc links become plain code spans, because
-/// Doxygen cannot resolve Rust paths:
-/// ``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
-/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span. Code
-/// spans that name a C++ member then use its C++ name (see `cpp_code_span`);
-/// other code spans stay as written.
-fn option_doc_lines(doc: &[String], capabilities: 
&[capability::CapabilityField]) -> Vec<String> {
-    let mut lines = Vec::new();
-    for paragraph in doc.split(|line| line.trim().is_empty()) {
-        if paragraph.is_empty() {
+/// - Each paragraph, heading, and list item is wrapped to fit the comment
+///   lines. An empty line separates paragraphs, as in core.
+/// - 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)``
+///   and ``[`crate::layers::SimulateLayer`]`` keep only their code span, and
+///   `[the specification][crate::docs::specs::checksum]` reads
+///   `the specification`.
+/// - Code spans that name a core capability or error kind use their C++
+///   spelling (see `cpp_code_span`); other code spans stay as written.
+/// - Outside code spans, `\` becomes `\\` and `@` becomes `\@`, so Doxygen
+///   shows them instead of reading a command. Code spans stay verbatim.
+/// - 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.
+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 blocks: Vec<(bool, String)> = Vec::new();
+    let mut after_blank = false;
+    let mut continues = false;
+    for line in doc {
+        let line = line.trim();
+        if line.is_empty() {
+            after_blank = !blocks.is_empty();
+            continues = false;
             continue;
         }
+        let heading = line.starts_with('#');
+        match blocks.last_mut() {
+            Some((_, text)) if continues && !heading && !line.starts_with("- 
") => {
+                text.push(' ');
+                text.push_str(line);
+            }
+            _ => blocks.push((after_blank, line.to_string())),
+        }
+        after_blank = false;
+        continues = !heading;
+    }
+    let mut lines = Vec::new();
+    for (after_blank, text) in blocks {
+        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
+}
+
+/// The doc of a public options struct after its `@brief` block.
+///
+/// The released `@brief` replaces core's summary paragraph, so the doc is
+/// the rest of core's struct doc, 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.
+fn struct_doc_lines(
+    core_doc: &[String],
+    member_docs: &[&[String]],
+    names: &CppNames,
+) -> Vec<String> {
+    let details: Vec<String> = core_doc
+        .iter()
+        .skip_while(|line| !line.trim().is_empty())
+        .cloned()
+        .collect();
+    let mut lines = option_doc_lines(&details, HPP_STRUCT_DOC_PREFIX, names);
+    let docs = 
std::iter::once(details.as_slice()).chain(member_docs.iter().copied());
+    if let Some(kind) = first_error_kind(docs.flatten(), names) {
         if !lines.is_empty() {
             lines.push(String::new());
         }
-        let text = paragraph
-            .iter()
-            .map(|line| rewrite_code_spans(line.trim(), |code| 
cpp_code_span(code, capabilities)))
-            .collect::<Vec<_>>()
-            .join(" ");
-        lines.extend(wrap_doc(&text, HPP_DOC_PREFIX, HPP_COLUMN_LIMIT));
+        let note = format!(
+            "When the operation fails with an error kind that these docs name, 
such as \
+             `{kind}`, it throws a `std::exception` whose `what()` starts with 
that kind."
+        );
+        lines.extend(wrap_doc(&note, HPP_STRUCT_DOC_PREFIX, HPP_COLUMN_LIMIT));
     }
     lines
 }
 
-/// The C++ name of a code span that names a member of the C++ surface, or
-/// `None` to keep the code span as written.
+/// The C++ spelling of the first error kind that a code span in `doc` names.
+fn first_error_kind<'a>(
+    doc: impl IntoIterator<Item = &'a String>,
+    names: &CppNames,
+) -> Option<String> {
+    let first = OnceCell::new();
+    for line in doc {
+        rewrite_code_spans(line, |code| {
+            if let Some(kind) = error_kind_name(code, names) {
+                let _ = first.set(kind.to_string());
+            }
+            None
+        });
+    }
+    first.into_inner()
+}
+
+/// Replace each reference-style rustdoc link to a crate item,
+/// `[text][crate::path]`, with its text.
+fn strip_crate_reference_links(line: &str) -> String {
+    let mut out = String::with_capacity(line.len());
+    let mut rest = line;
+    while let Some(pos) = rest.find("][crate::") {
+        let target = &rest[pos + 2..];
+        let (Some(open), Some(close)) = (rest[..pos].rfind('['), 
target.find(']')) else {
+            break;
+        };
+        out.push_str(&rest[..open]);
+        out.push_str(&rest[open + 1..pos]);
+        rest = &target[close + 1..];
+    }
+    out.push_str(rest);
+    out
+}
+
+/// The C++ spelling of a code span that names a core capability or error
+/// kind, or `None` to keep the code span as written.
 ///
-/// A core capability such as `Capability::list_with_start_after` reads
-/// `opendal::Capability::list_with_start_after`, the member of the
-/// `opendal::Capability` that `Operator::Info()` returns, spelled by
-/// `cpp_name`. Option members keep their core names in C++, so a span such as
+/// - A core capability such as `Capability::list_with_start_after` reads
+///   `opendal::Capability::list_with_start_after`, the member of the
+///   `opendal::Capability` that `Operator::Info()` returns, spelled by
+///   `cpp_name`.
+/// - A core error kind such as `ErrorKind::NotFound` reads `NotFound`, the
+///   name that begins the `what()` of the exception that C++ callers catch.
+///
+/// Option members keep their core names in C++, so a span such as
 /// `start_after` stays as written.
-fn cpp_code_span(code: &str, capabilities: &[capability::CapabilityField]) -> 
Option<String> {
+fn cpp_code_span(code: &str, names: &CppNames) -> Option<String> {
+    if let Some(kind) = error_kind_name(code, names) {
+        return Some(kind.to_string());
+    }
     let name = code
         .strip_prefix("crate::")
         .unwrap_or(code)
         .strip_prefix("Capability::")?;
-    capabilities
+    names
+        .capabilities
         .iter()
         .any(|f| f.name == name)
         .then(|| format!("opendal::Capability::{}", cpp_name(name)))
 }
 
+/// The error message name of a code span that names a core error kind, such
+/// as `crate::ErrorKind::NotFound`.
+fn error_kind_name<'a>(code: &str, names: &'a CppNames) -> Option<&'a str> {
+    let kind = code
+        .strip_prefix("crate::")
+        .unwrap_or(code)
+        .strip_prefix("ErrorKind::")?;
+    names.error_kinds.get(kind).map(String::as_str)
+}
+
+/// Escape `text` for a Doxygen comment: outside code spans, `\` becomes `\\`
+/// and `@` becomes `\@`, so Doxygen shows them instead of reading a command.
+/// Code spans, which Doxygen shows verbatim, stay as written.
+fn doxygen_text(text: &str) -> String {
+    let mut out = String::with_capacity(text.len());
+    let mut rest = text;
+    loop {
+        let span = rest
+            .find('`')
+            .and_then(|start| Some(start..start + 2 + rest[start + 
1..].find('`')?));
+        let plain = span.as_ref().map_or(rest, |span| &rest[..span.start]);
+        for c in plain.chars() {
+            if matches!(c, '\\' | '@') {
+                out.push('\\');
+            }
+            out.push(c);
+        }
+        let Some(span) = span else {
+            return out;
+        };
+        out.push_str(&rest[span.clone()]);
+        rest = &rest[span.end..];
+    }
+}
+
 /// Check `specs` against the parsed core structs and build their render
 /// models.
 ///
@@ -686,7 +913,7 @@ fn cpp_code_span(code: &str, capabilities: 
&[capability::CapabilityField]) -> Op
 fn options_models(
     parsed: &[core_options::OptionsStruct],
     specs: &[OptionsSpec],
-    capabilities: &[capability::CapabilityField],
+    names: &CppNames,
 ) -> Result<Vec<OptionsModel>> {
     let mut models = Vec::with_capacity(specs.len());
     for spec in specs {
@@ -695,6 +922,7 @@ fn options_models(
             .find(|s| s.name == spec.name)
             .with_context(|| format!("OPTIONS struct `{}` is missing from 
core", spec.name))?;
         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() {
             if spec.fields[..i].iter().any(|(listed, _)| *listed == name) {
                 bail!("OPTIONS lists `{}::{name}` twice", spec.name);
@@ -716,7 +944,8 @@ fn options_models(
                     field.kind
                 );
             }
-            members.push(option_member(spec.name, field, kind, capabilities)?);
+            members.push(option_member(spec.name, field, kind, names)?);
+            member_docs.push(field.doc.as_slice());
         }
         let unexposed: Vec<String> = core
             .fields
@@ -729,6 +958,8 @@ fn options_models(
             bridge_name: format!("Ffi{}", spec.name),
             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(&core.doc, &member_docs, names),
             members,
             unexposed,
         });
@@ -738,7 +969,11 @@ fn options_models(
 
 fn generate_options(workspace_dir: &Path) -> Result<()> {
     for (relative, rendered) in render_options(workspace_dir)? {
-        fs::write(workspace_dir.join(relative), format!("{rendered}\n"))?;
+        let path = workspace_dir.join(relative);
+        if let Some(parent) = path.parent() {
+            fs::create_dir_all(parent)?;
+        }
+        fs::write(path, format!("{rendered}\n"))?;
     }
     Ok(())
 }
@@ -746,8 +981,8 @@ fn generate_options(workspace_dir: &Path) -> Result<()> {
 /// Render every options output as `(path relative to workspace, content)`.
 fn render_options(workspace_dir: &Path) -> Result<Vec<(&'static str, String)>> 
{
     let parsed = 
core_options::parse(&workspace_dir.join("core/core/src/types/options.rs"))?;
-    let capabilities = 
capability::parse(&workspace_dir.join("core/core/src/types/capability.rs"))?;
-    let options = options_models(&parsed, OPTIONS, &capabilities)?;
+    let names = CppNames::parse(workspace_dir)?;
+    let options = options_models(&parsed, OPTIONS, &names)?;
 
     let mut env = Environment::new();
     env.add_template("options_hpp", include_str!("cpp/options_hpp.j2"))?;
@@ -786,6 +1021,7 @@ fn render_options(workspace_dir: &Path) -> 
Result<Vec<(&'static str, String)>> {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use regex::Regex;
 
     fn core_fields() -> Vec<capability::CapabilityField> {
         
capability::parse(&workspace_dir().join("core/core/src/types/capability.rs"))
@@ -911,10 +1147,11 @@ mod tests {
         assert!(err.contains("`cache_control` is missing from core"));
     }
 
-    /// `ListOptions` as `bindings/cpp/include/data_structure.hpp` declared it 
on
-    /// `main` before it was generated, copied verbatim. Callers depend on each
-    /// member's name, type, default member initializer, and position. The
-    /// generated header adds member doc comments, which this text omits.
+    /// `ListOptions` and `StatOptions` 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.
     const MAIN_LIST_OPTIONS: &str = r#"/**
  * @struct ListOptions
  * @brief Options for list and lister operations.
@@ -927,6 +1164,25 @@ struct ListOptions {
   bool deleted{false};
 };"#;
 
+    const MAIN_STAT_OPTIONS: &str = r#"/**
+ * @struct StatOptions
+ * @brief Options for stat operations.
+ */
+struct StatOptions {
+  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::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")
+    }
+
     fn parsed_options() -> Vec<core_options::OptionsStruct> {
         
core_options::parse(&workspace_dir().join("core/core/src/types/options.rs"))
             .expect("parse core options")
@@ -941,19 +1197,34 @@ struct ListOptions {
             .expect("rendered output")
     }
 
+    /// `text` without its comment lines.
+    fn code_lines(text: &str) -> String {
+        text.lines()
+            .filter(|line| {
+                let line = line.trim_start();
+                !["///", "/**", "*"]
+                    .iter()
+                    .any(|start| line.starts_with(start))
+            })
+            .map(|line| format!("{line}\n"))
+            .collect()
+    }
+
     #[test]
-    fn test_rendered_options_header_keeps_main_list_options() {
+    fn test_rendered_options_header_keeps_main_declarations() {
         let header = rendered_options("bindings/cpp/include/options.hpp");
-        let declarations: String = header
-            .lines()
-            .filter(|line| !line.starts_with("  ///"))
-            .map(|line| format!("{line}\n"))
-            .collect();
-        assert!(
-            declarations.contains(MAIN_LIST_OPTIONS),
-            "header no longer 
declares:\n{MAIN_LIST_OPTIONS}\n\nheader:\n{header}"
-        );
-        assert_eq!(header.matches("\nstruct ").count(), 1);
+        let code = code_lines(&header);
+        for main in [MAIN_LIST_OPTIONS, MAIN_STAT_OPTIONS] {
+            assert!(
+                code.contains(&code_lines(main)),
+                "header no longer declares:\n{main}\n\nheader:\n{header}"
+            );
+            // The `@struct` and `@brief` lines stay too.
+            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(), 2);
+        assert!(header.contains("\n#include <chrono>\n"));
     }
 
     /// Split doc text into paragraphs, each joined into one line of words.
@@ -972,84 +1243,163 @@ struct ListOptions {
             .collect()
     }
 
+    /// Core doc text as the C++ header must read it, one entry per 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");
+        let text = Regex::new(r"\[(`[^`]*`)\](\([^)]*\))?")
+            .unwrap()
+            .replace_all(&text, "$1");
+        let text = Regex::new(r"\[([^\]]*)\]\[crate::[^\]]*\]")
+            .unwrap()
+            .replace_all(&text, "$1");
+        let text = text
+            .replace("`crate::Capability::", "`Capability::")
+            .replace("`Capability::", "`opendal::Capability::")
+            .replace("`crate::ErrorKind::", "`")
+            .replace("`ErrorKind::", "`");
+        paragraphs(text.lines())
+    }
+
+    /// A rendered comment line as core wrote it: outside code spans, Doxygen
+    /// escapes are undone and the empty HTML comment after a trailing
+    /// backslash is dropped.
+    fn doxygen_plain(line: &str) -> String {
+        line.replace("<!---->", "")
+            .split('`')
+            .enumerate()
+            .map(|(i, part)| match i % 2 {
+                0 => part
+                    .replace(r"\\", "\0")
+                    .replace(r"\@", "@")
+                    .replace('\0', r"\"),
+                _ => part.to_string(),
+            })
+            .collect::<Vec<_>>()
+            .join("`")
+    }
+
+    /// The doc comment of member `name` inside `struct struct_name { ... };`
+    /// in `header`, as core wrote it.
+    fn member_comment(header: &str, struct_name: &str, name: &str) -> 
Vec<String> {
+        let start = header
+            .find(&format!("\nstruct {struct_name} {{\n"))
+            .unwrap_or_else(|| panic!("header lacks `struct {struct_name}`"));
+        let body = &header[start + 1..];
+        let lines: Vec<&str> = 
body[..body.find("\n};\n").unwrap()].lines().collect();
+        let decl = lines
+            .iter()
+            .position(|line| {
+                !line.starts_with("  ///")
+                    && (line.ends_with(&format!(" {name};"))
+                        || line.ends_with(&format!(" {name}{{false}};")))
+            })
+            .unwrap_or_else(|| panic!("`{struct_name}` lacks `{name}`"));
+        let mut comment: Vec<String> = lines[..decl]
+            .iter()
+            .rev()
+            .map_while(|line| line.strip_prefix("  ///"))
+            .map(doxygen_plain)
+            .collect();
+        comment.reverse();
+        comment
+    }
+
+    /// The `///` doc between the `@brief` block of `struct_name` and its
+    /// declaration in `header`, as core wrote it.
+    fn struct_comment(header: &str, struct_name: &str) -> Vec<String> {
+        let start = header
+            .find(&format!(" * @struct {struct_name}\n"))
+            .unwrap_or_else(|| panic!("header lacks `@struct {struct_name}`"));
+        let block = &header[start..];
+        let block = &block[block.find(" */\n").unwrap() + 4..];
+        block[..block.find(&format!("struct {struct_name} {{\n")).unwrap()]
+            .lines()
+            .map(|line| doxygen_plain(line.strip_prefix("///").expect("struct 
doc line")))
+            .collect()
+    }
+
     #[test]
     fn test_rendered_options_header_documents_members_with_core_docs() {
         let header = rendered_options("bindings/cpp/include/options.hpp");
-        let lines: Vec<&str> = header.lines().collect();
-        let list = parsed_options()
-            .into_iter()
-            .find(|s| s.name == "ListOptions")
-            .unwrap();
-        for (name, _) in OPTIONS[0].fields {
-            // Core's full doc, with `[`code`](target)` and `[`code`]` links
-            // reduced to their code span.
-            let core_doc = list
-                .fields
-                .iter()
-                .find(|f| f.name == *name)
-                .unwrap()
-                .doc
-                .join("\n");
-            let mut plain = String::new();
-            let mut rest = core_doc.as_str();
-            while let Some(at) = rest.find("](") {
-                let close = rest[at..].find(')').unwrap();
-                plain.push_str(&rest[..at + 1]);
-                rest = &rest[at + close + 1..];
+        let parsed = parsed_options();
+        let kind = Regex::new(r"ErrorKind::(\w+)").unwrap();
+        for spec in OPTIONS {
+            let core = parsed.iter().find(|s| s.name == spec.name).unwrap();
+            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 comment = member_comment(&header, spec.name, name);
+                assert_eq!(
+                    paragraphs(comment.iter().map(String::as_str)),
+                    expected,
+                    "doc of `{}::{name}`",
+                    spec.name
+                );
+                docs.push(core_doc.join(" "));
             }
-            plain.push_str(rest);
-            // C++ callers read capabilities from the `opendal::Capability`
-            // that `Operator::Info()` returns.
-            let plain = plain
-                .replace("[`", "`")
-                .replace("`]", "`")
-                .replace("`Capability::", "`opendal::Capability::");
-            let expected = paragraphs(plain.lines());
-            assert!(
-                !expected.is_empty(),
-                "core `ListOptions::{name}` has no doc"
-            );
 
-            let decl = lines
-                .iter()
-                .position(|line| {
-                    !line.starts_with("  ///")
-                        && (line.ends_with(&format!(" {name};"))
-                            || line.ends_with(&format!(" {name}{{false}};")))
-                })
-                .unwrap_or_else(|| panic!("header lacks `{name}`"));
-            let mut comment: Vec<&str> = lines[..decl]
+            // Core's struct doc after its summary, which the released
+            // `@brief` replaces, then how C++ callers see the first error
+            // kind that these docs name.
+            let details: Vec<String> = core
+                .doc
                 .iter()
-                .rev()
-                .map_while(|line| line.strip_prefix("  ///"))
+                .skip_while(|line| !line.trim().is_empty())
+                .cloned()
                 .collect();
-            comment.reverse();
+            let mut expected = expected_paragraphs(&details);
+            docs.insert(0, details.join(" "));
+            if let Some(first) = kind.captures(&docs.join(" ")) {
+                expected.push(format!(
+                    "When the operation fails with an error kind that these 
docs name, such as \
+                     `{}`, it throws a `std::exception` whose `what()` starts 
with that kind.",
+                    &first[1]
+                ));
+            }
+            assert!(!expected.is_empty(), "`{}` has no struct doc", spec.name);
             assert_eq!(
-                paragraphs(comment),
+                paragraphs(
+                    struct_comment(&header, spec.name)
+                        .iter()
+                        .map(String::as_str)
+                ),
                 expected,
-                "doc of `ListOptions::{name}`"
+                "doc of `{}`",
+                spec.name
             );
         }
-        // A rendered intra-doc link, copied from core's `start_after` doc.
-        assert!(header.contains(
-            "  ///\n  /// Setting this requires 
`opendal::Capability::list_with_start_after`.\n"
-        ));
-        assert!(!header.contains("[`"));
-        assert!(!header.contains("](crate::"));
-        assert!(!header.contains(" `Capability::"));
+        for rust in ["[`", "](", "crate::", "ErrorKind::", "`Capability::"] {
+            assert!(!header.contains(rust), "header contains `{rust}`");
+        }
 
         // Each referenced capability is a member of the generated C++ class.
         let capability_header = 
rendered("bindings/cpp/include/capability.hpp");
-        let mut referenced = 0;
         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.hpp lacks `{member}`"
             );
-            referenced += 1;
         }
-        assert_eq!(referenced, 4);
+    }
+
+    #[test]
+    fn test_cpp_names_parse_error_kinds_as_messages_name_them() {
+        let names = core_names();
+        for kind in ["NotFound", "ConditionNotMatch", "Unsupported"] {
+            assert_eq!(names.error_kinds.get(kind).map(String::as_str), 
Some(kind));
+        }
     }
 
     #[test]
@@ -1062,7 +1412,7 @@ struct ListOptions {
         ]
         .map(String::from);
         assert_eq!(
-            option_doc_lines(&doc, &core_fields()),
+            option_doc_lines(&doc, HPP_DOC_PREFIX, &core_names()),
             [
                 "Requires `opendal::Capability::list_with_limit`.",
                 "",
@@ -1081,11 +1431,14 @@ struct ListOptions {
             "",
             "Requires [`crate::Capability::list_with_versions`] and 
`Capability::delete`.",
             "",
-            "Unknown `Capability::no_such_flag`, 
[`crate::ErrorKind::Unsupported`], `glob`, and prose Capability::list stay.",
+            "Fails with [`crate::ErrorKind::Unsupported`] or 
`ErrorKind::ConditionNotMatch`.",
+            "A missing file returns [`crate::ErrorKind::NotFound`].",
+            "",
+            "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`, 
`glob`, and prose Capability::list stay.",
         ]
         .map(String::from);
         assert_eq!(
-            option_doc_lines(&doc, &core_fields()),
+            option_doc_lines(&doc, HPP_DOC_PREFIX, &core_names()),
             [
                 "- Pagination: `limit`, `start_after`.",
                 "",
@@ -1094,16 +1447,96 @@ struct ListOptions {
                 "Requires `opendal::Capability::list_with_versions` and",
                 "`opendal::Capability::delete_feature`.",
                 "",
-                "Unknown `Capability::no_such_flag`, 
`crate::ErrorKind::Unsupported`,",
-                "`glob`, and prose Capability::list stay.",
+                "Fails with `Unsupported` or `ConditionNotMatch`. A missing 
file returns",
+                "`NotFound`.",
+                "",
+                "Unknown `Capability::no_such_flag`, `ErrorKind::NoSuchKind`, 
`glob`, and",
+                "prose Capability::list stay.",
+            ]
+        );
+    }
+
+    #[test]
+    fn test_option_doc_lines_escape_for_doxygen() {
+        let doc = [
+            r#"Match "quoted" text and an @tag in `C:\x` or `a@b` code, keep 
C:\dir\ paths together."#,
+            "",
+            r"Ends with C:\",
+        ]
+        .map(String::from);
+        let lines = option_doc_lines(&doc, HPP_DOC_PREFIX, &core_names());
+        assert_eq!(
+            lines,
+            [
+                r#"Match "quoted" text and an \@tag in `C:\x` or `a@b` code, 
keep"#,
+                r"C:\\dir\\ paths together.",
+                "",
+                r"Ends with C:\\<!---->",
             ]
         );
+        // A comment line that ends with a backslash would continue onto the
+        // next source line.
+        assert!(lines.iter().all(|line| !line.ends_with('\\')));
+    }
+
+    #[test]
+    fn test_struct_doc_lines_render_core_details() {
+        let names = core_names();
+        let doc = [
+            "Summary that the `@brief` replaces.",
+            "",
+            "# Groups",
+            "- Pagination: `limit`, `start_after`.",
+            "- Versioning: `versions`,",
+            "  `deleted`.",
+            "",
+            "A missing file returns [`crate::ErrorKind::NotFound`]. See the",
+            "[specification][crate::docs::specs::conditional_operations] for 
more.",
+        ]
+        .map(String::from);
+        let member: &[String] = &["Fails with 
`ErrorKind::Unsupported`.".to_string()];
+        assert_eq!(
+            struct_doc_lines(&doc, &[member], &names),
+            [
+                "# Groups",
+                "- Pagination: `limit`, `start_after`.",
+                "- Versioning: `versions`, `deleted`.",
+                "",
+                "A missing file returns `NotFound`. See the specification for 
more.",
+                "",
+                "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.",
+            ]
+        );
+
+        // A member doc gives the example when the struct doc names no kind,
+        // and without any kind there is no note.
+        let summary_only = ["Summary only.".to_string()];
+        assert_eq!(
+            struct_doc_lines(&summary_only, &[&[], member], &names),
+            [
+                "When the operation fails with an error kind that these docs 
name, such as",
+                "`Unsupported`, it throws a `std::exception` whose `what()` 
starts with that",
+                "kind.",
+            ]
+        );
+        assert!(struct_doc_lines(&summary_only, &[&[]], &names).is_empty());
+    }
+
+    #[test]
+    fn test_wrap_doc_keeps_backslash_with_next_word() {
+        assert_eq!(
+            wrap_doc(r"aaa b\ ccc ddd", "// ", 10),
+            ["aaa", r"b\ ccc", "ddd"]
+        );
+        assert_eq!(wrap_doc(r"aaa b\\ c", "// ", 10), ["aaa", r"b\\ c"]);
     }
 
     #[test]
     fn test_new_core_field_stays_unexposed() {
         let mut parsed = parsed_options();
-        let before = options_models(&parsed, OPTIONS, &core_fields()).unwrap();
+        let before = options_models(&parsed, OPTIONS, &core_names()).unwrap();
         let list = parsed.iter_mut().find(|s| s.name == 
"ListOptions").unwrap();
         list.fields.insert(
             1,
@@ -1114,7 +1547,7 @@ struct ListOptions {
             },
         );
 
-        let after = options_models(&parsed, OPTIONS, &core_fields()).unwrap();
+        let after = options_models(&parsed, OPTIONS, &core_names()).unwrap();
 
         assert_eq!(before[0].members, after[0].members);
         assert_eq!(after[0].unexposed[0], "new_mid");
@@ -1122,6 +1555,24 @@ struct ListOptions {
         assert!(after[0].fills_defaults);
     }
 
+    #[test]
+    fn test_stat_options_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!(fallible, [("ListOptions", false), ("StatOptions", true)]);
+
+        let rust = rendered_options("bindings/cpp/src/options.rs");
+        assert!(
+            rust.contains("impl From<ffi::FfiListOptions> for 
opendal::options::ListOptions {")
+        );
+        assert!(rust.contains(
+            "impl TryFrom<ffi::FfiStatOptions> for 
opendal::options::StatOptions {\n    type Error = opendal::Error;\n"
+        ));
+        assert!(rust.contains(
+            "            if_modified_since: 
optional_timestamp(opts.if_modified_since)?,\n"
+        ));
+    }
+
     #[test]
     fn test_options_models_reject_incompatible_specs() {
         use OptionKind::*;
@@ -1133,7 +1584,7 @@ struct ListOptions {
                 brief: "",
                 fields,
             };
-            options_models(&parsed, &[spec], &core_fields())
+            options_models(&parsed, &[spec], &core_names())
                 .unwrap_err()
                 .to_string()
         };
@@ -1158,26 +1609,41 @@ struct ListOptions {
             "core `ListOptions::limit` has kind OptionUsize, but OPTIONS lists 
OptionU64"
         );
         // Core changing a listed field to another kind the bridge carries must
-        // fail too, instead of silently turning `start_after` into a `bool`.
-        let mut changed = parsed.clone();
-        let list = changed
-            .iter_mut()
-            .find(|s| s.name == "ListOptions")
-            .unwrap();
-        list.fields
-            .iter_mut()
-            .find(|f| f.name == "start_after")
-            .unwrap()
-            .kind = Bool;
-        assert_eq!(
-            options_models(&changed, OPTIONS, &core_fields())
-                .unwrap_err()
-                .to_string(),
-            "core `ListOptions::start_after` has kind Bool, but OPTIONS lists 
OptionString"
-        );
+        // fail too, instead of silently changing the public member type.
+        for (options, field, kind, expected) in [
+            (
+                "ListOptions",
+                "start_after",
+                Bool,
+                "core `ListOptions::start_after` has kind Bool, but OPTIONS 
lists OptionString",
+            ),
+            (
+                "StatOptions",
+                "if_modified_since",
+                OptionString,
+                "core `StatOptions::if_modified_since` has kind OptionString, 
but OPTIONS lists OptionTimestamp",
+            ),
+        ] {
+            let mut changed = parsed.clone();
+            changed
+                .iter_mut()
+                .find(|s| s.name == options)
+                .unwrap()
+                .fields
+                .iter_mut()
+                .find(|f| f.name == field)
+                .unwrap()
+                .kind = kind;
+            assert_eq!(
+                options_models(&changed, OPTIONS, &core_names())
+                    .unwrap_err()
+                    .to_string(),
+                expected
+            );
+        }
         assert_eq!(
-            error("ReadOptions", &[("if_modified_since", OptionTimestamp)]),
-            "the C++ bridge cannot carry `ReadOptions::if_modified_since` of 
kind OptionTimestamp yet"
+            error("ReadOptions", &[("range", BytesRange)]),
+            "the C++ bridge cannot carry `ReadOptions::range` of kind 
BytesRange yet"
         );
     }
 
diff --git a/dev/src/generate/cpp/options_converter_cpp.j2 
b/dev/src/generate/cpp/options_converter_cpp.j2
index f06f8b95be..9b5227ae12 100644
--- a/dev/src/generate/cpp/options_converter_cpp.j2
+++ b/dev/src/generate/cpp/options_converter_cpp.j2
@@ -22,7 +22,9 @@
 
 #include "utils/options_converter.hpp"
 
+#include <chrono>
 #include <cstddef>
+#include <cstdint>
 #include <optional>
 #include <string>
 
@@ -48,6 +50,29 @@ ffi::options::OptionalUsize ToFfiOptionalUsize(
   return ffi::options::OptionalUsize{false, 0};
 }
 
+ffi::options::OptionalTimestamp ToFfiOptionalTimestamp(
+    const std::optional<std::chrono::system_clock::time_point> &value) {
+  if (!value.has_value()) {
+    return ffi::options::OptionalTimestamp{false, 0, 0};
+  }
+
+  auto duration = value->time_since_epoch();
+  auto seconds_duration =
+      std::chrono::duration_cast<std::chrono::seconds>(duration);
+  auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
+                         duration - seconds_duration)
+                         .count();
+  auto seconds = seconds_duration.count();
+  if (nanoseconds < 0) {
+    --seconds;
+    nanoseconds += 1000000000;
+  }
+
+  return ffi::options::OptionalTimestamp{
+      true, static_cast<std::int64_t>(seconds),
+      static_cast<std::uint32_t>(nanoseconds)};
+}
+
 }  // namespace
 {%- for s in options %}
 
diff --git a/dev/src/generate/cpp/options_hpp.j2 
b/dev/src/generate/cpp/options_hpp.j2
index df368aca02..eed6755028 100644
--- a/dev/src/generate/cpp/options_hpp.j2
+++ b/dev/src/generate/cpp/options_hpp.j2
@@ -22,6 +22,7 @@
 
 #pragma once
 
+#include <chrono>
 #include <cstddef>
 #include <optional>
 #include <string>
@@ -33,6 +34,9 @@ namespace opendal {
  * @struct {{ s.name }}
  * @brief {{ s.brief }}
  */
+{%- for line in s.hpp_doc_lines %}
+///{% if line %} {{ line }}{% endif %}
+{%- endfor %}
 struct {{ s.name }} {
 {%- for m in s.members %}
 {%- for line in m.hpp_doc_lines %}
diff --git a/dev/src/generate/cpp/options_rs.j2 
b/dev/src/generate/cpp/options_rs.j2
index 0961ba943e..e5a492a74b 100644
--- a/dev/src/generate/cpp/options_rs.j2
+++ b/dev/src/generate/cpp/options_rs.j2
@@ -33,6 +33,12 @@ pub mod ffi {
         has_value: bool,
         value: usize,
     }
+
+    struct OptionalTimestamp {
+        has_value: bool,
+        seconds: i64,
+        nanoseconds: u32,
+    }
 {%- for s in options %}
 
     struct {{ s.bridge_name }} {
@@ -50,11 +56,31 @@ fn optional_string(v: ffi::OptionalString) -> 
Option<String> {
 fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
     v.has_value.then_some(v.value)
 }
+
+fn optional_timestamp(
+    v: ffi::OptionalTimestamp,
+) -> opendal::Result<Option<opendal::raw::Timestamp>> {
+    if v.has_value {
+        Ok(Some(opendal::raw::Timestamp::new(
+            v.seconds,
+            v.nanoseconds as i32,
+        )?))
+    } else {
+        Ok(None)
+    }
+}
 {%- for s in options %}
+{% if s.fallible %}
+impl TryFrom<ffi::{{ s.bridge_name }}> for opendal::options::{{ s.name }} {
+    type Error = opendal::Error;
 
+    fn try_from(opts: ffi::{{ s.bridge_name }}) -> Result<Self, Self::Error> {
+        Ok(Self {
+{%- else %}
 impl From<ffi::{{ s.bridge_name }}> for opendal::options::{{ s.name }} {
     fn from(opts: ffi::{{ s.bridge_name }}) -> Self {
         Self {
+{%- endif %}
 {%- for m in s.members %}
             {{ m.name }}: {{ m.rust_value }},
 {%- endfor %}
@@ -67,7 +93,11 @@ impl From<ffi::{{ s.bridge_name }}> for opendal::options::{{ 
s.name }} {
 {%- if s.fills_defaults %}
             ..Default::default()
 {%- endif %}
+{%- if s.fallible %}
+        })
+{%- else %}
         }
+{%- endif %}
     }
 }
 {%- endfor %}
\ No newline at end of file

Reply via email to