From: Philip Pronin <philipp@fb.com> Date: Tue, 10 Feb 2015 01:54:29 +0000 (-0800) Subject: make decodeVarint accept StringPiece X-Git-Tag: v0.25.0~7 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=a11dc9b7dfda07a11b702ef27578feb391caf811;p=folly.git make decodeVarint accept StringPiece 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 --- diff --git a/folly/Varint.h b/folly/Varint.h index a58866fd..5642f691 100644 --- a/folly/Varint.h +++ b/folly/Varint.h @@ -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; diff --git a/folly/test/VarintTest.cpp b/folly/test/VarintTest.cpp index 546ebc3e..058cbf1d 100644 --- a/folly/test/VarintTest.cpp +++ b/folly/test/VarintTest.cpp @@ -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});