make decodeVarint accept StringPiece
authorPhilip Pronin <philipp@fb.com>
Tue, 10 Feb 2015 01:54:29 +0000 (17:54 -0800)
committerSara Golemon <sgolemon@fb.com>
Wed, 11 Feb 2015 02:02:00 +0000 (18:02 -0800)
Summary: `decodeVarint` now accepts all of `StringPiece`, `MutableStringPiece`, `ByteRange`, and `MutableByteRange`.

Test Plan: fbconfig -r folly unicorn/utils && fbmake runtests_opt -j32

Reviewed By: ott@fb.com, lucian@fb.com

Subscribers: trunkagent, chaoyc, search-fbcode-diffs@, unicorn-diffs@, folly-diffs@, yzhan, yfeldblum

FB internal diff: D1836805

Signature: t1:1836805:1423534085:cca5c3e83ad699e5d56e1d1e3394644ec3f94dab

folly/Varint.h
folly/test/VarintTest.cpp

index a58866fd10392b8f6dd2394db056977a5db61dc3..5642f691ccda33a0c8460e2a1ea0920a5d53d081 100644 (file)
@@ -17,6 +17,7 @@
 #ifndef FOLLY_VARINT_H_
 #define FOLLY_VARINT_H_
 
+#include <type_traits>
 #include <folly/Range.h>
 
 namespace folly {
@@ -55,7 +56,8 @@ size_t encodeVarint(uint64_t val, uint8_t* buf);
 /**
  * Decode a value from a given buffer, advances data past the returned value.
  */
-uint64_t decodeVarint(ByteRange& data);
+template <class T>
+uint64_t decodeVarint(Range<T*>& data);
 
 /**
  * ZigZag encoding that maps signed integers with a small absolute value
@@ -88,7 +90,13 @@ inline size_t encodeVarint(uint64_t val, uint8_t* buf) {
   return p - buf;
 }
 
-inline uint64_t decodeVarint(ByteRange& data) {
+template <class T>
+inline uint64_t decodeVarint(Range<T*>& data) {
+  static_assert(
+      std::is_same<typename std::remove_cv<T>::type, char>::value ||
+          std::is_same<typename std::remove_cv<T>::type, unsigned char>::value,
+      "Only character ranges are supported");
+
   const int8_t* begin = reinterpret_cast<const int8_t*>(data.begin());
   const int8_t* end = reinterpret_cast<const int8_t*>(data.end());
   const int8_t* p = begin;
index 546ebc3e5e648843b4f63b27d9cbeca5e4d1d9e3..058cbf1dc1e7b1ebef79666dbd74ed1eac8cee2b 100644 (file)
@@ -65,6 +65,24 @@ void testVarint(uint64_t val, std::initializer_list<uint8_t> bytes) {
   }
 }
 
+TEST(Varint, Interface) {
+  // Make sure decodeVarint() accepts all of StringPiece, MutableStringPiece,
+  // ByteRange, and MutableByteRange.
+  char c = 0;
+
+  StringPiece sp(&c, 1);
+  EXPECT_EQ(decodeVarint(sp), 0);
+
+  MutableStringPiece msp(&c, 1);
+  EXPECT_EQ(decodeVarint(msp), 0);
+
+  ByteRange br(reinterpret_cast<unsigned char*>(&c), 1);
+  EXPECT_EQ(decodeVarint(br), 0);
+
+  MutableByteRange mbr(reinterpret_cast<unsigned char*>(&c), 1);
+  EXPECT_EQ(decodeVarint(mbr), 0);
+}
+
 TEST(Varint, Simple) {
   testVarint(0, {0});
   testVarint(1, {1});