Skip to content

Commit

Permalink
Support std::initializer_list in folly::range
Browse files Browse the repository at this point in the history
Summary:
Support `std::initializer_list<T>` in the `folly::range` and `folly::crange` helper functions, returning `folly::Range<const T*>`.

This is to make it easier to forward `std::initializer_list<T>` parameters to `folly::Range` ones in customer code.

Reviewed By: ot

Differential Revision: D54115340

fbshipit-source-id: d47b2fee73415890f746dba578f0d7770c90637e
  • Loading branch information
Aleksei Averchenko authored and facebook-github-bot committed Feb 26, 2024
1 parent 4c624e2 commit 2d434ee
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions folly/Range.h
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,16 @@ constexpr Range<T const*> crange(std::array<T, n> const& array) {
return Range<T const*>{array};
}

template <class T>
constexpr Range<T const*> range(std::initializer_list<T> ilist) {
return Range<T const*>(ilist.begin(), ilist.end());
}

template <class T>
constexpr Range<T const*> crange(std::initializer_list<T> ilist) {
return Range<T const*>(ilist.begin(), ilist.end());
}

using StringPiece = Range<const char*>;
using MutableStringPiece = Range<char*>;
using ByteRange = Range<const unsigned char*>;
Expand Down
16 changes: 16 additions & 0 deletions folly/test/RangeTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,22 @@ TEST(Range, MutableStringPieceExplicitConversionOperator) {
EXPECT_EQ("hello", piecec.to<fake_string_view>(fake_tag{}));
}

TEST(Range, InitializerList) {
auto check = [](Range<int const*> r) {
ASSERT_EQ(r.size(), 3);
EXPECT_EQ(*r.begin(), 1);
EXPECT_EQ(*(r.begin() + 1), 2);
EXPECT_EQ(*(r.begin() + 2), 3);
};

check(range({1, 2, 3}));
check(crange({1, 2, 3}));

static constexpr auto ilist = {1, 2, 3};
check(range(ilist));
check(crange(ilist));
}

#if FOLLY_HAS_STRING_VIEW
namespace {
std::size_t stringViewSize(std::string_view s) {
Expand Down

0 comments on commit 2d434ee

Please sign in to comment.