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

Side by Side 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 unified diff | Download patch
« no previous file with comments | « client/libs/logdog/tests/varint_test.py ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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
OLDNEW
« 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