1 | """ |
---|
2 | Netstring encoding and decoding. |
---|
3 | |
---|
4 | Ported to Python 3. |
---|
5 | """ |
---|
6 | |
---|
7 | try: |
---|
8 | from typing import Optional, Tuple, List # noqa: F401 |
---|
9 | except ImportError: |
---|
10 | pass |
---|
11 | |
---|
12 | |
---|
13 | def netstring(s): # type: (bytes) -> bytes |
---|
14 | assert isinstance(s, bytes), s # no unicode here |
---|
15 | return b"%d:%s," % (len(s), s,) |
---|
16 | |
---|
17 | def split_netstring(data, numstrings, |
---|
18 | position=0, |
---|
19 | required_trailer=None): # type (bytes, init, int, Optional[bytes]) -> Tuple[List[bytes], int] |
---|
20 | """like string.split(), but extracts netstrings. Ignore all bytes of data |
---|
21 | before the 'position' byte. Return a tuple of (list of elements (numstrings |
---|
22 | in length), new position index). The new position index points to the first |
---|
23 | byte which was not consumed (the 'required_trailer', if any, counts as |
---|
24 | consumed). If 'required_trailer' is not None, throw ValueError if leftover |
---|
25 | data does not exactly equal 'required_trailer'.""" |
---|
26 | assert isinstance(data, bytes) |
---|
27 | assert required_trailer is None or isinstance(required_trailer, bytes) |
---|
28 | assert isinstance(position, int), (repr(position), type(position)) |
---|
29 | elements = [] |
---|
30 | assert numstrings >= 0 |
---|
31 | while position < len(data): |
---|
32 | colon = data.index(b":", position) |
---|
33 | length = int(data[position:colon]) |
---|
34 | string = data[colon+1:colon+1+length] |
---|
35 | assert len(string) == length, (len(string), length) |
---|
36 | elements.append(string) |
---|
37 | position = colon+1+length |
---|
38 | assert data[position] == b","[0], position |
---|
39 | position += 1 |
---|
40 | if len(elements) == numstrings: |
---|
41 | break |
---|
42 | if len(elements) < numstrings: |
---|
43 | raise ValueError("ran out of netstrings") |
---|
44 | if required_trailer is not None: |
---|
45 | if ((len(data) - position) != len(required_trailer)) or (data[position:] != required_trailer): |
---|
46 | raise ValueError("leftover data in netstrings") |
---|
47 | return (elements, position + len(required_trailer)) |
---|
48 | else: |
---|
49 | return (elements, position) |
---|