Commit 6699f91a authored by Tom Jackson's avatar Tom Jackson Committed by facebook-github-bot-4

Handle take(-1) better

Summary: It's easy to accidentally pass a negative value to ##take()##, which leads to underflow on conversion to ##size_t##.

Reviewed By: @​rosephilip, @philippv

Differential Revision: D2421459
parent 541d1209
...@@ -2308,7 +2308,13 @@ constexpr detail::Indirect indirect{}; ...@@ -2308,7 +2308,13 @@ constexpr detail::Indirect indirect{};
constexpr detail::Unwrap unwrap{}; constexpr detail::Unwrap unwrap{};
inline detail::Take take(size_t count) { return detail::Take(count); } template <class Number>
inline detail::Take take(Number count) {
if (count < 0) {
throw std::invalid_argument("Negative value passed to take()");
}
return detail::Take(static_cast<size_t>(count));
}
inline detail::Stride stride(size_t s) { return detail::Stride(s); } inline detail::Stride stride(size_t s) { return detail::Stride(s); }
......
...@@ -349,6 +349,11 @@ TEST(Gen, Take) { ...@@ -349,6 +349,11 @@ TEST(Gen, Take) {
| as<vector>(); | as<vector>();
EXPECT_EQ(expected, actual); EXPECT_EQ(expected, actual);
} }
{
int64_t limit = 5;
take(limit - 5);
EXPECT_THROW(take(limit - 6), std::invalid_argument);
}
} }
......
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