Permalink
Browse files

StringPiece comparisons are broken

Summary:
8-bit StringPiece comparisons are broken.
The reason is char_traits is magic for 'char', but not 'const char'.

Test Plan: test added

Reviewed By: chip@fb.com

FB internal diff: D861521
  • Loading branch information...
1 parent 753903f commit a664fa91fed10a492ec4560f3e97a4e1b8c7e59d @tudor tudor committed with jdelong Jun 24, 2013
Showing with 43 additions and 1 deletion.
  1. +2 −1 folly/Range.h
  2. +41 −0 folly/test/RangeTest.cpp
View
@@ -123,7 +123,8 @@ class Range : private boost::totally_ordered<Range<Iter> > {
typename std::iterator_traits<Iter>::reference>::type
value_type;
typedef typename std::iterator_traits<Iter>::reference reference;
- typedef std::char_traits<value_type> traits_type;
+ typedef std::char_traits<typename std::remove_const<value_type>::type>
+ traits_type;
static const size_type npos;
View
@@ -207,6 +207,47 @@ TEST(StringPiece, All) {
EXPECT_EQ(s2, s);
}
+template <class T>
+void expectLT(const T& a, const T& b) {
+ EXPECT_TRUE(a < b);
+ EXPECT_TRUE(a <= b);
+ EXPECT_FALSE(a == b);
+ EXPECT_FALSE(a >= b);
+ EXPECT_FALSE(a > b);
+
+ EXPECT_FALSE(b < a);
+ EXPECT_FALSE(b <= a);
+ EXPECT_TRUE(b >= a);
+ EXPECT_TRUE(b > a);
+}
+
+template <class T>
+void expectEQ(const T& a, const T& b) {
+ EXPECT_FALSE(a < b);
+ EXPECT_TRUE(a <= b);
+ EXPECT_TRUE(a == b);
+ EXPECT_TRUE(a >= b);
+ EXPECT_FALSE(a > b);
+}
+
+TEST(StringPiece, EightBitComparisons) {
+ char values[] = {'\x00', '\x20', '\x40', '\x7f', '\x80', '\xc0', '\xff'};
+ constexpr size_t count = sizeof(values) / sizeof(values[0]);
+ for (size_t i = 0; i < count; ++i) {
+ std::string a(1, values[i]);
+ // Defeat copy-on-write
+ std::string aCopy(a.data(), a.size());
+ expectEQ(a, aCopy);
+ expectEQ(StringPiece(a), StringPiece(aCopy));
+
+ for (size_t j = i + 1; j < count; ++j) {
+ std::string b(1, values[j]);
+ expectLT(a, b);
+ expectLT(StringPiece(a), StringPiece(b));
+ }
+ }
+}
+
TEST(StringPiece, ToByteRange) {
StringPiece a("hello");
ByteRange b(a);

0 comments on commit a664fa9

Please sign in to comment.