Commit 293868b2 authored by Uddipta Maity's avatar Uddipta Maity Committed by Facebook Github Bot

Adding a method to get varint encoding size

Summary: #title

Reviewed By: yfeldblum

Differential Revision: D6864158

fbshipit-source-id: 13c98c3e44db6febae844f099baa9fbecc9db673
parent e8ca7f09
......@@ -21,6 +21,7 @@
#include <folly/Conv.h>
#include <folly/Expected.h>
#include <folly/Likely.h>
#include <folly/Portability.h>
#include <folly/Range.h>
namespace folly {
......@@ -56,6 +57,13 @@ constexpr size_t kMaxVarintLength64 = 10;
*/
size_t encodeVarint(uint64_t val, uint8_t* buf);
/**
* Determine the number of bytes needed to represent "val".
* 32-bit values need at most 5 bytes.
* 64-bit values need at most 10 bytes.
*/
int encodeVarintSize(uint64_t val);
/**
* Decode a value from a given buffer, advances data past the returned value.
* Throws on error.
......@@ -108,6 +116,21 @@ inline size_t encodeVarint(uint64_t val, uint8_t* buf) {
return size_t(p - buf);
}
inline int encodeVarintSize(uint64_t val) {
if (folly::kIsArchAmd64) {
// __builtin_clzll is undefined for 0
int highBit = 64 - __builtin_clzll(val | 1);
return (highBit + 6) / 7;
} else {
int s = 1;
while (val >= 128) {
++s;
val >>= 7;
}
return s;
}
}
template <class T>
inline uint64_t decodeVarint(Range<T*>& data) {
auto expected = tryDecodeVarint(data);
......
......@@ -39,6 +39,7 @@ void testVarint(uint64_t val, std::initializer_list<uint8_t> bytes) {
uint8_t buf[kMaxVarintLength64];
EXPECT_EQ(expected.size(), encodeVarint(val, buf));
EXPECT_TRUE(ByteRange(buf, expected.size()) == expected);
EXPECT_EQ(expected.size(), encodeVarintSize(val));
}
{
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment