Chromium Code Reviews| 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 json | |
| 7 import sys | |
| 8 | |
| 9 | |
| 10 def write_uvarint(w, val): | |
| 11 """Returns (int): The number of bytes that were written. | |
| 12 | |
| 13 Writes a varint value to the supplied file-like object. | |
| 14 | |
| 15 Args: | |
| 16 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 "
| |
| 17 val (number): The value to write. Must be >= 0. | |
| 18 | |
| 19 Raises: | |
| 20 ValueError if 'val' is < 0. | |
| 21 """ | |
| 22 if val < 0: | |
| 23 raise ValueError('Cannot encode negative value, %d' % (val,)) | |
| 24 | |
| 25 count = 0 | |
| 26 while val > 0 or count == 0: | |
| 27 byte = (val & 0x7f) | |
| 28 val >>= 7 | |
| 29 if val > 0: | |
| 30 byte |= 0x80 | |
| 31 | |
| 32 w.write(chr(byte)) | |
| 33 count += 1 | |
| 34 if val == 0: | |
| 35 return count | |
| 36 | |
| 37 | |
| 38 def read_uvarint(r): | |
| 39 """Reads a uvarint from a stream. | |
| 40 | |
| 41 This is targeted towards testing, and will not be used in production code. | |
| 42 | |
| 43 Args: | |
| 44 r (object): A file-like object to read from. Must implement read. | |
| 45 | |
| 46 Returns: (value, count) | |
| 47 value (int): The decoded varint number. | |
| 48 count (int): The number of bytes that were read from 'r'. | |
| 49 | |
| 50 Raises: | |
| 51 ValueError if the encoded string has trailing data. | |
| 52 """ | |
| 53 count = 0 | |
| 54 result = 0 | |
| 55 while True: | |
| 56 byte = r.read(1) | |
| 57 if len(byte) == 0: | |
| 58 raise ValueError('UVarint was not terminated.') | |
| 59 | |
| 60 byte = ord(byte) | |
| 61 result |= ((byte & 0x7f) << (7 * count)) | |
| 62 count += 1 | |
| 63 if byte & 0x80 == 0: | |
| 64 break | |
| 65 return result, count | |
| OLD | NEW |