adding is_non_positive traits
authorMarcelo Juchem <marcelo@fb.com>
Tue, 12 Mar 2013 22:55:06 +0000 (15:55 -0700)
committerJordan DeLong <jdelong@fb.com>
Tue, 19 Mar 2013 00:09:08 +0000 (17:09 -0700)
Summary:
template <typename SomeInt>
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
folly/test/TraitsTest.cpp

index d3002dce5a07bd90a3171fb0136c132843c4d1f3..bc0a0bf68847f1270b389eb9a87d5a6b3ce2088e 100644 (file)
@@ -278,9 +278,9 @@ struct IsOneOf<T, T1, Ts...> {
 };
 
 /*
- * 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<T, false> {
 
 } // namespace detail {
 
+// same as `x < 0`
 template <typename T>
 constexpr bool is_negative(T x) {
   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
 }
 
+// same as `x <= 0`
+template <typename T>
+constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
+
 } // namespace folly
 
 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string);
index ae13d66d02b356f0fccfffed89ff729c2c7cbccd..a2760ca8fa6718c97cdea20b14bea8041d753649 100644 (file)
@@ -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<vector<int>>::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);