Commit 41f67441 authored by Victor Zverovich's avatar Victor Zverovich Committed by Facebook Github Bot

Add conversion from fbstring to std::string_view

Summary:
Add an implicit conversion from `folly::fbstring` to `std::string_view` for
compatibility with `std::string`. Among other things this enables formatting of
`fbstring` with fmt.

Reviewed By: yfeldblum

Differential Revision: D15230438

fbshipit-source-id: 8f5a606c5e2a761cb332421130de638abfab4065
parent 4d8408a7
...@@ -26,6 +26,10 @@ ...@@ -26,6 +26,10 @@
#include <stdexcept> #include <stdexcept>
#include <type_traits> #include <type_traits>
#if FOLLY_HAS_STRING_VIEW
#include <string_view>
#endif
// This file appears in two locations: inside fbcode and in the // This file appears in two locations: inside fbcode and in the
// libstdc++ source code (when embedding fbstring as std::string). // libstdc++ source code (when embedding fbstring as std::string).
// To aid in this schizophrenic use, _LIBSTDCXX_FBSTRING is defined in // To aid in this schizophrenic use, _LIBSTDCXX_FBSTRING is defined in
...@@ -1221,6 +1225,12 @@ class basic_fbstring { ...@@ -1221,6 +1225,12 @@ class basic_fbstring {
return assign(il.begin(), il.end()); return assign(il.begin(), il.end());
} }
#if FOLLY_HAS_STRING_VIEW
operator std::basic_string_view<value_type, traits_type>() const noexcept {
return {data(), size()};
}
#endif
// C++11 21.4.3 iterators: // C++11 21.4.3 iterators:
iterator begin() { iterator begin() {
return store_.mutableData(); return store_.mutableData();
......
...@@ -1739,3 +1739,16 @@ TEST(WFBString, compareToStdWStringLong) { ...@@ -1739,3 +1739,16 @@ TEST(WFBString, compareToStdWStringLong) {
EXPECT_TRUE(fbB >= stdB); EXPECT_TRUE(fbB >= stdB);
} }
#endif #endif
#if FOLLY_HAS_STRING_VIEW
struct custom_traits : public std::char_traits<char> {};
TEST(FBString, convertToStringView) {
folly::fbstring s("foo");
std::string_view sv = s;
EXPECT_EQ(sv, "foo");
folly::basic_fbstring<char, custom_traits> s2("bar");
std::basic_string_view<char, custom_traits> sv2 = s2;
EXPECT_EQ(sv2, "bar");
}
#endif
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment