[PATCH 03 of 15] util: implement varint functions
Boris Feld
boris.feld at octobus.net
Fri Jan 19 15:08:47 EST 2018
# HG changeset patch
# User Gregory Szorc <gregory.szorc at gmail.com>
# Date 1474779566 25200
# Sat Sep 24 21:59:26 2016 -0700
# Node ID b80a8e39ac9bf984c25a666bd7f6c47d876d26af
# Parent f6baa2844ea380da1a63832a35b1b83007c181a3
# EXP-Topic b2-stream
# Available At https://bitbucket.org/octobus/mercurial-devel/
# hg pull https://bitbucket.org/octobus/mercurial-devel/ -r b80a8e39ac9b
util: implement varint functions
This will be useful in an incoming version-2 of the stream format.
diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -3874,3 +3874,36 @@ def readexactly(stream, n):
" (got %d bytes, expected %d)")
% (len(s), n))
return s
+
+def uvarintencode(value):
+ """Encode an unsigned integer value to a varint.
+
+ A varint is a variable length integer of 1 or more bytes. Each byte
+ except the last has the most significant bit set. The lower 7 bits of
+ each byte store the 2's complement representation, least significant group
+ first.
+ """
+ bits = value & 0x7f
+ value >>= 7
+ bytes = []
+ while value:
+ bytes.append(pycompat.bytechr(0x80 | bits))
+ bits = value & 0x7f
+ value >>= 7
+ bytes.append(pycompat.bytechr(bits))
+
+ return ''.join(bytes)
+
+def uvarintdecodestream(fh):
+ """Decode an unsigned variable length integer from a stream.
+
+ The passed argument is anything that has a ``.read(N)`` method.
+ """
+ result = 0
+ shift = 0
+ while True:
+ byte = ord(readexactly(fh, 1))
+ result |= ((byte & 0x7f) << shift)
+ if not (byte & 0x80):
+ return result
+ shift += 7
More information about the Mercurial-devel
mailing list