Dump value as a tnetstring, to a deque instance, last chunks first. This function generates the tnetstring representation of the given value, pushing chunks of the output onto the given deque instance. It pushes the last chunk first, then recursively generates more chunks. Wh
(q: collections.deque, size: int, value: TSerializable)
| 68 | |
| 69 | |
| 70 | def _rdumpq(q: collections.deque, size: int, value: TSerializable) -> int: |
| 71 | """ |
| 72 | Dump value as a tnetstring, to a deque instance, last chunks first. |
| 73 | |
| 74 | This function generates the tnetstring representation of the given value, |
| 75 | pushing chunks of the output onto the given deque instance. It pushes |
| 76 | the last chunk first, then recursively generates more chunks. |
| 77 | |
| 78 | When passed in the current size of the string in the queue, it will return |
| 79 | the new size of the string in the queue. |
| 80 | |
| 81 | Operating last-chunk-first makes it easy to calculate the size written |
| 82 | for recursive structures without having to build their representation as |
| 83 | a string. This is measurably faster than generating the intermediate |
| 84 | strings, especially on deeply nested structures. |
| 85 | """ |
| 86 | write = q.appendleft |
| 87 | if value is None: |
| 88 | write(b"0:~") |
| 89 | return size + 3 |
| 90 | elif value is True: |
| 91 | write(b"4:true!") |
| 92 | return size + 7 |
| 93 | elif value is False: |
| 94 | write(b"5:false!") |
| 95 | return size + 8 |
| 96 | elif isinstance(value, int): |
| 97 | data = str(value).encode() |
| 98 | ldata = len(data) |
| 99 | span = str(ldata).encode() |
| 100 | write(b"%s:%s#" % (span, data)) |
| 101 | return size + 2 + len(span) + ldata |
| 102 | elif isinstance(value, float): |
| 103 | # Use repr() for float rather than str(). |
| 104 | # It round-trips more accurately. |
| 105 | # Probably unnecessary in later python versions that |
| 106 | # use David Gay's ftoa routines. |
| 107 | data = repr(value).encode() |
| 108 | ldata = len(data) |
| 109 | span = str(ldata).encode() |
| 110 | write(b"%s:%s^" % (span, data)) |
| 111 | return size + 2 + len(span) + ldata |
| 112 | elif isinstance(value, bytes): |
| 113 | data = value |
| 114 | ldata = len(data) |
| 115 | span = str(ldata).encode() |
| 116 | write(b",") |
| 117 | write(data) |
| 118 | write(b":") |
| 119 | write(span) |
| 120 | return size + 2 + len(span) + ldata |
| 121 | elif isinstance(value, str): |
| 122 | data = value.encode("utf8") |
| 123 | ldata = len(data) |
| 124 | span = str(ldata).encode() |
| 125 | write(b";") |
| 126 | write(data) |
| 127 | write(b":") |