From a11dc9b7dfda07a11b702ef27578feb391caf811 Mon Sep 17 00:00:00 2001 From: Philip Pronin Date: Mon, 9 Feb 2015 17:54:29 -0800 Subject: [PATCH] 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 --- folly/Varint.h | 12 ++++++++++-- folly/test/VarintTest.cpp | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) 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 #include 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 +uint64_t decodeVarint(Range& 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 +inline uint64_t decodeVarint(Range& data) { + static_assert( + std::is_same::type, char>::value || + std::is_same::type, unsigned char>::value, + "Only character ranges are supported"); + const int8_t* begin = reinterpret_cast(data.begin()); const int8_t* end = reinterpret_cast(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 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(&c), 1); + EXPECT_EQ(decodeVarint(br), 0); + + MutableByteRange mbr(reinterpret_cast(&c), 1); + EXPECT_EQ(decodeVarint(mbr), 0); +} + TEST(Varint, Simple) { testVarint(0, {0}); testVarint(1, {1}); -- 2.34.1