Commit 44cc7697 authored by Kenton Varda's avatar Kenton Varda

Make KJ_MAP support raw arrays as input.

parent 54a611d4
......@@ -333,6 +333,16 @@ TEST(Array, Map) {
EXPECT_STREQ("bcde", str(bar).cStr());
}
TEST(Array, MapRawArray) {
uint foo[4] = {1, 2, 3, 4};
Array<uint> bar = KJ_MAP(i, foo) -> uint { return i * i; };
ASSERT_EQ(4, bar.size());
EXPECT_EQ(1, bar[0]);
EXPECT_EQ(4, bar[1]);
EXPECT_EQ(9, bar[2]);
EXPECT_EQ(16, bar[3]);
}
TEST(Array, ReleaseAsBytesOrChars) {
{
Array<char> chars = kj::heapArray<char>("foo", 3);
......
......@@ -501,7 +501,8 @@ private:
// KJ_MAP
#define KJ_MAP(elementName, array) \
::kj::_::Mapper<KJ_DECLTYPE_REF(array)>(array) * [&](decltype(*(array).begin()) elementName)
::kj::_::Mapper<KJ_DECLTYPE_REF(array)>(array) * \
[&](typename ::kj::_::Mapper<KJ_DECLTYPE_REF(array)>::Element elementName)
// Applies some function to every element of an array, returning an Array of the results, with
// nice syntax. Example:
//
......@@ -523,6 +524,22 @@ struct Mapper {
}
return builder.finish();
}
typedef decltype(*(array).begin()) Element;
};
template <typename T, size_t s>
struct Mapper<T(&)[s]> {
T* array;
Mapper(T* array): array(array) {}
template <typename Func>
auto operator*(Func&& func) -> Array<decltype(func(*array))> {
auto builder = heapArrayBuilder<decltype(func(*array))>(s);
for (size_t i = 0; i < s; i++) {
builder.add(func(array[i]));
}
return builder.finish();
}
typedef decltype(*array)& Element;
};
} // namespace _ (private)
......
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