Issue with find and npos
authorRajat Goel <rajatgoel2010@fb.com>
Wed, 16 Oct 2013 00:25:36 +0000 (17:25 -0700)
committerSara Golemon <sgolemon@fb.com>
Thu, 24 Oct 2013 21:53:41 +0000 (14:53 -0700)
Summary:
I dont know whats the expected behavior but for std::string it seems
to work.

@override-unit-failures

Test Plan:
unit-tests

[ RUN      ] FBString.findWithNpos
folly/test/FBStringTest.cpp:1147: Failure
Value of: fbstr.find(":", fbstring::npos)
Actual: 9
Expected: fbstring::npos
Which is: 18446744073709551615

Reviewed By: andrei.alexandrescu@fb.com

FB internal diff: D1012870

folly/FBString.h
folly/test/FBStringTest.cpp

index 541baa0ff9949f58b6b938420d80f05c0b442fe0..6f5ea13194978aad661e2227f6fcc34e90ba8d26 100644 (file)
@@ -1794,7 +1794,9 @@ public:
                  const size_type nsize) const {
     if (!nsize) return pos;
     auto const size = this->size();
-    if (nsize + pos > size) return npos;
+    // nsize + pos can overflow (eg pos == npos), guard against that by checking
+    // that nsize + pos does not wrap around.
+    if (nsize + pos > size || nsize + pos < pos) return npos;
     // Don't use std::search, use a Boyer-Moore-like trick by comparing
     // the last characters first
     auto const haystack = data();
index 3e294282449be887f643b9f25ed763bc6f1db6ad..3efd652e4a9647ec08009ddf1318ada672777070 100644 (file)
@@ -1139,6 +1139,11 @@ TEST(FBString, testFixedBugs) {
   }
 }
 
+TEST(FBString, findWithNpos) {
+  fbstring fbstr("localhost:80");
+  EXPECT_EQ(fbstring::npos, fbstr.find(":", fbstring::npos));
+}
+
 TEST(FBString, testHash) {
   fbstring a;
   fbstring b;