Chromium Code Reviews| 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..405ee2f60cd9349e14f9f2c68c6e3ae44e54a72d |
| --- /dev/null |
| +++ b/client/libs/logdog/varint.py |
| @@ -0,0 +1,65 @@ |
| +# 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 json |
| +import sys |
| + |
| + |
| +def write_uvarint(w, val): |
| + """Returns (int): The number of bytes that were written. |
| + |
| + Writes a varint value to the supplied file-like object. |
| + |
| + Args: |
| + w (object): A file-like object to write to. Must implement write. |
|
martiniss
2016/05/10 22:12:38
"Must implement write" not needed IMO.
dnj (Google)
2016/05/12 17:54:03
Well, file-like objects can implement "read" and "
|
| + val (number): The value to write. Must be >= 0. |
| + |
| + 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 & 0x7f) |
| + val >>= 7 |
| + if val > 0: |
| + byte |= 0x80 |
| + |
| + w.write(chr(byte)) |
| + count += 1 |
| + if val == 0: |
| + 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 string has trailing data. |
| + """ |
| + 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 & 0x7f) << (7 * count)) |
| + count += 1 |
| + if byte & 0x80 == 0: |
| + break |
| + return result, count |