| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2016 The LUCI Authors. All rights reserved. |
| 2 # Use of this source code is governed by the Apache v2.0 license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import os |
| 6 import sys |
| 7 |
| 8 |
| 9 def write_uvarint(w, val): |
| 10 """Writes a varint value to the supplied file-like object. |
| 11 |
| 12 Args: |
| 13 w (object): A file-like object to write to. Must implement write. |
| 14 val (number): The value to write. Must be >= 0. |
| 15 |
| 16 Returns (int): The number of bytes that were written. |
| 17 |
| 18 Raises: |
| 19 ValueError if 'val' is < 0. |
| 20 """ |
| 21 if val < 0: |
| 22 raise ValueError('Cannot encode negative value, %d' % (val,)) |
| 23 |
| 24 count = 0 |
| 25 while val > 0 or count == 0: |
| 26 byte = (val & 0b01111111) |
| 27 val >>= 7 |
| 28 if val > 0: |
| 29 byte |= 0b10000000 |
| 30 |
| 31 w.write(chr(byte)) |
| 32 count += 1 |
| 33 return count |
| 34 |
| 35 |
| 36 def read_uvarint(r): |
| 37 """Reads a uvarint from a stream. |
| 38 |
| 39 This is targeted towards testing, and will not be used in production code. |
| 40 |
| 41 Args: |
| 42 r (object): A file-like object to read from. Must implement read. |
| 43 |
| 44 Returns: (value, count) |
| 45 value (int): The decoded varint number. |
| 46 count (int): The number of bytes that were read from 'r'. |
| 47 |
| 48 Raises: |
| 49 ValueError if the encoded varint is not terminated. |
| 50 """ |
| 51 count = 0 |
| 52 result = 0 |
| 53 while True: |
| 54 byte = r.read(1) |
| 55 if len(byte) == 0: |
| 56 raise ValueError('UVarint was not terminated') |
| 57 |
| 58 byte = ord(byte) |
| 59 result |= ((byte & 0b01111111) << (7 * count)) |
| 60 count += 1 |
| 61 if byte & 0b10000000 == 0: |
| 62 break |
| 63 return result, count |
| OLD | NEW |