From d44f36ab667239d020b0746d8da279b41997d869 Mon Sep 17 00:00:00 2001 From: Phil Willoughby Date: Tue, 8 Aug 2017 03:19:16 -0700 Subject: [PATCH] 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 --- folly/Range.h | 34 ++++++++++++++++++++++++++++++++++ folly/test/RangeTest.cpp | 18 ++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/folly/Range.h b/folly/Range.h index 3bfef1f2..8ae96ce6 100644 --- a/folly/Range.h +++ b/folly/Range.h @@ -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 operator"" _sp( + char const* str, + size_t len) noexcept { + return Range(str, len); +} + +constexpr Range operator"" _sp( + char16_t const* str, + size_t len) noexcept { + return Range(str, len); +} + +constexpr Range operator"" _sp( + char32_t const* str, + size_t len) noexcept { + return Range(str, len); +} + +constexpr Range operator"" _sp( + wchar_t const* str, + size_t len) noexcept { + return Range(str, len); +} +} // inline namespace string_piece_literals +} // inline namespace literals + } // namespace folly FOLLY_POP_WARNING diff --git a/folly/test/RangeTest.cpp b/folly/test/RangeTest.cpp index 3538969c..3aa31786 100644 --- a/folly/test/RangeTest.cpp +++ b/folly/test/RangeTest.cpp @@ -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 piece8 = u8"hello"; + EXPECT_EQ(literalPiece8, piece8); + constexpr auto literalPiece16 = u"hello"_sp; + constexpr Range piece16{u"hello", 5}; + EXPECT_EQ(literalPiece16, piece16); + constexpr auto literalPiece32 = U"hello"_sp; + constexpr Range piece32{U"hello", 5}; + EXPECT_EQ(literalPiece32, piece32); + constexpr auto literalPieceW = L"hello"_sp; + constexpr Range pieceW{L"hello", 5}; + EXPECT_EQ(literalPieceW, pieceW); +} -- 2.34.1