From b9f3c420392c3ff4d53dd56df8c31fb4fb9deda0 Mon Sep 17 00:00:00 2001 From: Lukasz Anforowicz Date: Mon, 24 Mar 2025 21:28:19 +0000 Subject: [PATCH] Add an explicit conversion operator from `rust::Str` to `std::string_view`. --- book/src/binding/str.md | 3 +++ include/cxx.h | 14 +++++++++++--- src/cxx.cc | 6 ++++++ tests/ffi/tests.cc | 5 +++++ 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/book/src/binding/str.md b/book/src/binding/str.md index e37a13dfd..214d12dfa 100644 --- a/book/src/binding/str.md +++ b/book/src/binding/str.md @@ -25,6 +25,9 @@ public: Str &operator=(const Str &) & noexcept; explicit operator std::string() const; +#if __cplusplus >= 201703L + explicit operator std::string_view() const; +#endif // Note: no null terminator. const char *data() const noexcept; diff --git a/include/cxx.h b/include/cxx.h index 9f54ecc50..4e261a355 100644 --- a/include/cxx.h +++ b/include/cxx.h @@ -9,9 +9,6 @@ #include #include #include -#if __cplusplus >= 202002L -#include -#endif #include #include #include @@ -23,6 +20,14 @@ #include #endif +#if __cplusplus >= 201703L +#include +#endif + +#if __cplusplus >= 202002L +#include +#endif + namespace rust { inline namespace cxxbridge1 { @@ -123,6 +128,9 @@ class Str final { Str &operator=(const Str &) & noexcept = default; explicit operator std::string() const; +#if __cplusplus >= 201703L + explicit operator std::string_view() const; +#endif // Note: no null terminator. const char *data() const noexcept; diff --git a/src/cxx.cc b/src/cxx.cc index 1e3e355b2..45d9aace7 100644 --- a/src/cxx.cc +++ b/src/cxx.cc @@ -325,6 +325,12 @@ Str::operator std::string() const { return std::string(this->data(), this->size()); } +#if __cplusplus >= 201703L +Str::operator std::string_view() const { + return std::string_view(this->data(), this->size()); +} +#endif + const char *Str::data() const noexcept { return cxxbridge1$str$ptr(this); } std::size_t Str::size() const noexcept { return cxxbridge1$str$len(this); } diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index ad60aacba..2ba67f87d 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -874,6 +874,11 @@ extern "C" const char *cxx_run_test() noexcept { rust::Str out_param; r_return_str_via_out_param(Shared{2020}, out_param); ASSERT(out_param == "2020"); + +#if __cplusplus >= 201703L + std::string_view out_param_as_string_view{out_param}; + ASSERT(out_param_as_string_view == "2020"); +#endif } rust::Str cstr = "test";