Range<const char*> -> Range<const unsigned char*> implicit conversion
authorTudor Bosman <tudorb@fb.com>
Thu, 12 Jul 2012 23:33:38 +0000 (16:33 -0700)
committerTudor Bosman <tudorb@fb.com>
Fri, 13 Jul 2012 23:29:51 +0000 (16:29 -0700)
Summary: As they can both be used to represent ranges of bytes.

Test Plan: test added

Reviewed By: andrei.alexandrescu@fb.com

FB internal diff: D518666

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

index 350183a52f1d960fdada6784dbe2277c2c75f7b4..9ddf04525737514debbcdf69290c5079dd8a67b0 100644 (file)
@@ -25,6 +25,7 @@
 #include <iostream>
 #include <string>
 #include <stdexcept>
+#include <type_traits>
 #include <boost/operators.hpp>
 #include <boost/utility/enable_if.hpp>
 #include <boost/type_traits.hpp>
@@ -184,6 +185,16 @@ public:
     e_ = b_ + size;
   }
 
+  // Allow implicit conversion from Range<const char*> (aka StringPiece) to
+  // Range<const unsigned char*> (aka ByteRange), as they're both frequently
+  // used to represent ranges of bytes.
+  template <typename std::enable_if<
+      (std::is_same<Iter, const unsigned char*>::value), int>::type = 0>
+  /* implicit */ Range(const Range<const char*>& other)
+    : b_(reinterpret_cast<const unsigned char*>(other.begin())),
+      e_(reinterpret_cast<const unsigned char*>(other.end())) {
+  }
+
   void clear() {
     b_ = Iter();
     e_ = Iter();
@@ -373,6 +384,7 @@ Range<Iter> makeRange(Iter first, Iter last) {
 }
 
 typedef Range<const char*> StringPiece;
+typedef Range<const unsigned char*> ByteRange;
 
 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
 
index a98e142f09d63adaa30bb928e442112969aa94dc..65ff9e04be861472f1632268127b4118a0b879ad 100644 (file)
@@ -138,3 +138,12 @@ TEST(StringPiece, All) {
   EXPECT_EQ(s, s2);
   EXPECT_EQ(s2, s);
 }
+
+TEST(StringPiece, ToByteRange) {
+  StringPiece a("hello");
+  ByteRange b(a);
+  EXPECT_EQ(static_cast<const void*>(a.begin()),
+            static_cast<const void*>(b.begin()));
+  EXPECT_EQ(static_cast<const void*>(a.end()),
+            static_cast<const void*>(b.end()));
+}