MINOR: tools: add a function varint_bytes() to report the size of a varint
It will sometimes be useful to encode varints to know the output size in
advance. Two versions are provided, one inline using a switch/case construct
which will be trivial for use with constants (and will be very fast albeit
huge) and one function iterating on the number which is 5 times smaller,
for use with variables.
diff --git a/src/standard.c b/src/standard.c
index 717c14a..08a2c0d 100644
--- a/src/standard.c
+++ b/src/standard.c
@@ -4340,6 +4340,26 @@
return 1;
}
+
+/* returns the number of bytes needed to encode <v> as a varint. An inline
+ * version exists for use with constants (__varint_bytes()).
+ */
+int varint_bytes(uint64_t v)
+{
+ int len = 1;
+
+ if (v >= 240) {
+ v = (v - 240) >> 4;
+ while (1) {
+ len++;
+ if (v < 128)
+ break;
+ v = (v - 128) >> 7;
+ }
+ }
+ return len;
+}
+
/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
#ifndef USE_OBSOLETE_LINKER
__attribute__((weak,format(printf, 1, 2)))