Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(86)

Unified Diff: client/libs/logdog/varint.py

Issue 1961603002: Add LogDog Python client library. (Closed) Base URL: https://github.com/luci/luci-py@master
Patch Set: Remove "client." from package name, make pylint happy. Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « client/libs/logdog/tests/varint_test.py ('k') | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: client/libs/logdog/varint.py
diff --git a/client/libs/logdog/varint.py b/client/libs/logdog/varint.py
new file mode 100644
index 0000000000000000000000000000000000000000..518dafdd55ee0f081cb3c683cc005d7e076680d5
--- /dev/null
+++ b/client/libs/logdog/varint.py
@@ -0,0 +1,63 @@
+# Copyright 2016 The LUCI Authors. All rights reserved.
+# Use of this source code is governed by the Apache v2.0 license that can be
+# found in the LICENSE file.
+
+import os
+import sys
+
+
+def write_uvarint(w, val):
+ """Writes a varint value to the supplied file-like object.
+
+ Args:
+ w (object): A file-like object to write to. Must implement write.
+ val (number): The value to write. Must be >= 0.
+
+ Returns (int): The number of bytes that were written.
+
+ Raises:
+ ValueError if 'val' is < 0.
+ """
+ if val < 0:
+ raise ValueError('Cannot encode negative value, %d' % (val,))
+
+ count = 0
+ while val > 0 or count == 0:
+ byte = (val & 0b01111111)
+ val >>= 7
+ if val > 0:
+ byte |= 0b10000000
+
+ w.write(chr(byte))
+ count += 1
+ return count
+
+
+def read_uvarint(r):
+ """Reads a uvarint from a stream.
+
+ This is targeted towards testing, and will not be used in production code.
+
+ Args:
+ r (object): A file-like object to read from. Must implement read.
+
+ Returns: (value, count)
+ value (int): The decoded varint number.
+ count (int): The number of bytes that were read from 'r'.
+
+ Raises:
+ ValueError if the encoded varint is not terminated.
+ """
+ count = 0
+ result = 0
+ while True:
+ byte = r.read(1)
+ if len(byte) == 0:
+ raise ValueError('UVarint was not terminated')
+
+ byte = ord(byte)
+ result |= ((byte & 0b01111111) << (7 * count))
+ count += 1
+ if byte & 0b10000000 == 0:
+ break
+ return result, count
« no previous file with comments | « client/libs/logdog/tests/varint_test.py ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698