Skip to content
Browse files

Range<const char*> -> Range<const unsigned char*> implicit conversion

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
  • Loading branch information...
1 parent d50251a commit 51ef8c7a10f3fb15618174df794d4db0e6320788 @tudor tudor committed
Showing with 21 additions and 0 deletions.
  1. +12 −0 folly/Range.h
  2. +9 −0 folly/test/RangeTest.cpp
View
12 folly/Range.h
@@ -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 @@ class Range : private boost::totally_ordered<Range<Iter> > {
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);
View
9 folly/test/RangeTest.cpp
@@ -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()));
+}

0 comments on commit 51ef8c7

Please sign in to comment.
Something went wrong with that request. Please try again.