From 1bf1654c689b31ac7b53f499b8f1810548fbda7a Mon Sep 17 00:00:00 2001 From: Marcelo Juchem Date: Tue, 12 Mar 2013 15:55:06 -0700 Subject: [PATCH] adding is_non_positive traits Summary: template void foo(SomeInt x) { // yields an error in clang when SomeInt is unsigned and -Werror is used if(x <= 0) { //... } } Test Plan: added unit tests Reviewed By: andrei.alexandrescu@fb.com FB internal diff: D735735 --- folly/Traits.h | 9 +++++++-- folly/test/TraitsTest.cpp | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/folly/Traits.h b/folly/Traits.h index d3002dce..bc0a0bf6 100644 --- a/folly/Traits.h +++ b/folly/Traits.h @@ -278,9 +278,9 @@ struct IsOneOf { }; /* - * Complementary type traits to check for a negative value. + * Complementary type traits to check for a negative/non-positive value. * - * if(x < 0) yields an error in clang for unsigned types when -Werror is used + * `if(x < 0)` yields an error in clang for unsigned types when -Werror is used */ namespace detail { @@ -297,11 +297,16 @@ struct is_negative_impl { } // namespace detail { +// same as `x < 0` template constexpr bool is_negative(T x) { return folly::detail::is_negative_impl::value>::check(x); } +// same as `x <= 0` +template +constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); } + } // namespace folly FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string); diff --git a/folly/test/TraitsTest.cpp b/folly/test/TraitsTest.cpp index ae13d66d..a2760ca8 100644 --- a/folly/test/TraitsTest.cpp +++ b/folly/test/TraitsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2012 Facebook, Inc. + * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,6 +82,20 @@ TEST(Traits, bitAndInit) { EXPECT_FALSE(IsZeroInitializable>::value); } +TEST(Traits, is_negative) { + EXPECT_TRUE(folly::is_negative(-1)); + EXPECT_FALSE(folly::is_negative(0)); + EXPECT_FALSE(folly::is_negative(1)); + EXPECT_FALSE(folly::is_negative(0u)); + EXPECT_FALSE(folly::is_negative(1u)); + + EXPECT_TRUE(folly::is_non_positive(-1)); + EXPECT_TRUE(folly::is_non_positive(0)); + EXPECT_FALSE(folly::is_non_positive(1)); + EXPECT_TRUE(folly::is_non_positive(0u)); + EXPECT_FALSE(folly::is_non_positive(1u)); +} + int main(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); -- 2.34.1