Commit d44f36ab authored by Phil Willoughby's avatar Phil Willoughby Committed by Facebook Github Bot

Add a UDL suffix to define a StringPiece

Summary:
Use it like this:
```
using namespace folly::string_piece_literals;
StringPiece p = "A literal string"_sp;
```

In some compilation environments it can be more efficient than the implicit
conversion from `char const *` to `StringPiece`.

Reviewed By: yfeldblum

Differential Revision: D5562782

fbshipit-source-id: ce715edc65b1510761e127bf89a6936370253a68
parent 148df69f
......@@ -1322,6 +1322,40 @@ struct IsSomeString {
};
};
/**
* _sp is a user-defined literal suffix to make an appropriate Range
* specialization from a literal string.
*
* Modeled after C++17's `sv` suffix.
*/
inline namespace literals {
inline namespace string_piece_literals {
constexpr Range<char const*> operator"" _sp(
char const* str,
size_t len) noexcept {
return Range<char const*>(str, len);
}
constexpr Range<char16_t const*> operator"" _sp(
char16_t const* str,
size_t len) noexcept {
return Range<char16_t const*>(str, len);
}
constexpr Range<char32_t const*> operator"" _sp(
char32_t const* str,
size_t len) noexcept {
return Range<char32_t const*>(str, len);
}
constexpr Range<wchar_t const*> operator"" _sp(
wchar_t const* str,
size_t len) noexcept {
return Range<wchar_t const*>(str, len);
}
} // inline namespace string_piece_literals
} // inline namespace literals
} // namespace folly
FOLLY_POP_WARNING
......
......@@ -1357,3 +1357,21 @@ TEST(Range, ConstexprAccessors) {
static_assert(*piece.begin() == 'h', "");
static_assert(*(piece.end() - 1) == '\0', "");
}
TEST(Range, LiteralSuffix) {
constexpr auto literalPiece = "hello"_sp;
constexpr StringPiece piece = "hello";
EXPECT_EQ(literalPiece, piece);
constexpr auto literalPiece8 = u8"hello"_sp;
constexpr Range<char const*> piece8 = u8"hello";
EXPECT_EQ(literalPiece8, piece8);
constexpr auto literalPiece16 = u"hello"_sp;
constexpr Range<char16_t const*> piece16{u"hello", 5};
EXPECT_EQ(literalPiece16, piece16);
constexpr auto literalPiece32 = U"hello"_sp;
constexpr Range<char32_t const*> piece32{U"hello", 5};
EXPECT_EQ(literalPiece32, piece32);
constexpr auto literalPieceW = L"hello"_sp;
constexpr Range<wchar_t const*> pieceW{L"hello", 5};
EXPECT_EQ(literalPieceW, pieceW);
}
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