Skip to content

Commit b9f3c42

Browse files
committed
Add an explicit conversion operator from rust::Str to std::string_view.
1 parent 66f1995 commit b9f3c42

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

book/src/binding/str.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ public:
2525
Str &operator=(const Str &) & noexcept;
2626
2727
explicit operator std::string() const;
28+
#if __cplusplus >= 201703L
29+
explicit operator std::string_view() const;
30+
#endif
2831
2932
// Note: no null terminator.
3033
const char *data() const noexcept;

include/cxx.h

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@
99
#include <iosfwd>
1010
#include <iterator>
1111
#include <new>
12-
#if __cplusplus >= 202002L
13-
#include <ranges>
14-
#endif
1512
#include <stdexcept>
1613
#include <string>
1714
#include <type_traits>
@@ -23,6 +20,14 @@
2320
#include <sys/types.h>
2421
#endif
2522

23+
#if __cplusplus >= 201703L
24+
#include <string_view>
25+
#endif
26+
27+
#if __cplusplus >= 202002L
28+
#include <ranges>
29+
#endif
30+
2631
namespace rust {
2732
inline namespace cxxbridge1 {
2833

@@ -123,6 +128,9 @@ class Str final {
123128
Str &operator=(const Str &) & noexcept = default;
124129

125130
explicit operator std::string() const;
131+
#if __cplusplus >= 201703L
132+
explicit operator std::string_view() const;
133+
#endif
126134

127135
// Note: no null terminator.
128136
const char *data() const noexcept;

src/cxx.cc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,12 @@ Str::operator std::string() const {
325325
return std::string(this->data(), this->size());
326326
}
327327

328+
#if __cplusplus >= 201703L
329+
Str::operator std::string_view() const {
330+
return std::string_view(this->data(), this->size());
331+
}
332+
#endif
333+
328334
const char *Str::data() const noexcept { return cxxbridge1$str$ptr(this); }
329335

330336
std::size_t Str::size() const noexcept { return cxxbridge1$str$len(this); }

tests/ffi/tests.cc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,11 @@ extern "C" const char *cxx_run_test() noexcept {
874874
rust::Str out_param;
875875
r_return_str_via_out_param(Shared{2020}, out_param);
876876
ASSERT(out_param == "2020");
877+
878+
#if __cplusplus >= 201703L
879+
std::string_view out_param_as_string_view{out_param};
880+
ASSERT(out_param_as_string_view == "2020");
881+
#endif
877882
}
878883

879884
rust::Str cstr = "test";

0 commit comments

Comments
 (0)