From 6699f91a5664b78f767904ccdfcfdb0e23b44865 Mon Sep 17 00:00:00 2001 From: Tom Jackson Date: Wed, 9 Sep 2015 12:23:51 -0700 Subject: [PATCH] Handle take(-1) better MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 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 --- folly/gen/Base-inl.h | 8 +++++++- folly/gen/test/BaseTest.cpp | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/folly/gen/Base-inl.h b/folly/gen/Base-inl.h index 23b91973..7eded731 100644 --- a/folly/gen/Base-inl.h +++ b/folly/gen/Base-inl.h @@ -2308,7 +2308,13 @@ constexpr detail::Indirect indirect{}; constexpr detail::Unwrap unwrap{}; -inline detail::Take take(size_t count) { return detail::Take(count); } +template +inline detail::Take take(Number count) { + if (count < 0) { + throw std::invalid_argument("Negative value passed to take()"); + } + return detail::Take(static_cast(count)); +} inline detail::Stride stride(size_t s) { return detail::Stride(s); } diff --git a/folly/gen/test/BaseTest.cpp b/folly/gen/test/BaseTest.cpp index e97cf6c3..512dcc9f 100644 --- a/folly/gen/test/BaseTest.cpp +++ b/folly/gen/test/BaseTest.cpp @@ -349,6 +349,11 @@ TEST(Gen, Take) { | as(); EXPECT_EQ(expected, actual); } + { + int64_t limit = 5; + take(limit - 5); + EXPECT_THROW(take(limit - 6), std::invalid_argument); + } } -- 2.34.1