1515#include < basetsd.h>
1616#endif
1717
18+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
19+ #error "string_view gets auto-detected"
20+ #endif
21+
22+ // clang-format off
23+ // detect if string_view supported (C++17 required)
24+ #ifdef __has_include
25+ #if __has_include(<version>)
26+ // gcc >= 9, clang >= 9, msvc >= 19.22
27+ #include < version>
28+ #if __cpp_lib_string_view >= 201603L
29+ #define CXXBRIDGE_HAS_STRING_VIEW
30+ #endif
31+ #else
32+ // no <version> include
33+ #if defined(__cpp_lib_string_view) && __cpp_lib_string_view >= 201603L
34+ // gcc: 8, clang: 5 - 8, msvc: 19.15 - 19.21
35+ #define CXXBRIDGE_HAS_STRING_VIEW
36+ #else
37+ // only include if compiled with c++17
38+ #if (__GNUC__ >= 7 && __cplusplus >= 201703L) || (_MSVC_LANG >= 201703L)
39+ // gcc: 7, msvc: 19.14
40+ #define CXXBRIDGE_HAS_STRING_VIEW
41+ #endif
42+ #endif
43+ #endif
44+ #else
45+ // no __has_include
46+ #if _MSC_VER >= 1910L && _MSVC_LANG > 201402L
47+ // msvc: 19.10 requires c++latest (!)
48+ #define CPPBRIDGE_HAS_STRING_VIEW
49+ #endif
50+ #endif
51+ // clang-format on
52+
53+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
54+ #include < string_view>
55+ #endif
56+
1857namespace rust {
1958inline namespace cxxbridge1 {
2059
@@ -34,6 +73,9 @@ class String final {
3473 String (String &&) noexcept ;
3574 ~String () noexcept ;
3675
76+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
77+ String (std::string_view sv) : String(sv.data(), sv.length()) {}
78+ #endif
3779 String (const std::string &);
3880 String (const char *);
3981 String (const char *, size_t );
@@ -42,6 +84,11 @@ class String final {
4284 String &operator =(String &&) noexcept ;
4385
4486 explicit operator std::string () const ;
87+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
88+ explicit operator std::string_view () const noexcept {
89+ return {this ->data (), this ->size ()};
90+ }
91+ #endif
4592
4693 // Note: no null terminator.
4794 const char *data () const noexcept ;
@@ -71,13 +118,21 @@ class String final {
71118class Str final {
72119public:
73120 Str () noexcept ;
121+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
122+ Str (std::string_view sv) : Str(sv.data(), sv.length()) {}
123+ #endif
74124 Str (const std::string &);
75125 Str (const char *);
76126 Str (const char *, size_t );
77127
78128 Str &operator =(const Str &) noexcept = default ;
79129
80130 explicit operator std::string () const ;
131+ #ifdef CXXBRIDGE_HAS_STRING_VIEW
132+ explicit operator std::string_view () const noexcept {
133+ return {this ->data (), this ->size ()};
134+ }
135+ #endif
81136
82137 // Note: no null terminator.
83138 const char *data () const noexcept ;
0 commit comments