make Range::size() constexpr
authorAdam Simpkins <simpkins@fb.com>
Wed, 8 Jun 2016 23:15:18 +0000 (16:15 -0700)
committerFacebook Github Bot 6 <facebook-github-bot-6-bot@fb.com>
Wed, 8 Jun 2016 23:23:22 +0000 (16:23 -0700)
Summary:
Declare size() to return a constexpr value, so it can be called on constexpr
Range objects.

This unfortunately does drop the existing assert() check, due to a gcc bug:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448

Reviewed By: lbrandy

Differential Revision: D3394612

fbshipit-source-id: 77ea3b961dc323a39dea6f0e5850f9a311210d09

folly/Range.h
folly/test/RangeTest.cpp

index db2de699df4dffe87000bb1034c6a24a505306b8..4a06491684549db077af179fb49270e4223375f8 100644 (file)
@@ -353,8 +353,13 @@ public:
     reset(str.data(), str.size());
   }
 
     reset(str.data(), str.size());
   }
 
-  size_type size() const {
-    assert(b_ <= e_);
+  constexpr size_type size() const {
+    // It would be nice to assert(b_ <= e_) here.  This can be achieved even
+    // in a C++11 compatible constexpr function:
+    // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
+    // Unfortunately current gcc versions have a bug causing it to reject
+    // this check in a constexpr function:
+    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
     return e_ - b_;
   }
   size_type walk_size() const {
     return e_ - b_;
   }
   size_type walk_size() const {
index 8c98ee48151ced68b49439a774268b362c711f64..294659c90d621ad7e5775cf5f459164b1e55aff8 100644 (file)
@@ -298,9 +298,11 @@ constexpr char helloArray[] = "hello";
 TEST(StringPiece, Constexpr) {
   constexpr StringPiece hello1("hello");
   EXPECT_EQ("hello", hello1);
 TEST(StringPiece, Constexpr) {
   constexpr StringPiece hello1("hello");
   EXPECT_EQ("hello", hello1);
+  static_assert(hello1.size() == 5, "hello size should be 5 at compile time");
 
   constexpr StringPiece hello2(helloArray);
   EXPECT_EQ("hello", hello2);
 
   constexpr StringPiece hello2(helloArray);
   EXPECT_EQ("hello", hello2);
+  static_assert(hello2.size() == 5, "hello size should be 5 at compile time");
 }
 
 TEST(StringPiece, Prefix) {
 }
 
 TEST(StringPiece, Prefix) {