trlog 0.1.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- trlog/__init__.py +60 -0
- trlog/__main__.py +7 -0
- trlog/__version__.py +17 -0
- trlog/_aux.py +50 -0
- trlog/_bytesplit.py +243 -0
- trlog/_codec.py +179 -0
- trlog/_codec_bridge.py +319 -0
- trlog/_deps.py +169 -0
- trlog/_derived.py +315 -0
- trlog/_exceptions.py +33 -0
- trlog/_ext.py +102 -0
- trlog/_hierarchy.py +372 -0
- trlog/_index.py +237 -0
- trlog/_libpath.py +80 -0
- trlog/_metadata.py +178 -0
- trlog/_native.py +372 -0
- trlog/_reader.py +840 -0
- trlog/_string_table.py +115 -0
- trlog/_txn_data.py +893 -0
- trlog/_type_registry.py +457 -0
- trlog/_types.py +491 -0
- trlog/_vc_data.py +831 -0
- trlog/_writer.py +1146 -0
- trlog/cli.py +1841 -0
- trlog/codec.py +629 -0
- trlog/ext/__init__.py +5 -0
- trlog/ext/callreturn.py +458 -0
- trlog/query/__init__.py +33 -0
- trlog/query/_analysis.py +657 -0
- trlog/query/_cengine.py +702 -0
- trlog/query/_engine.py +1798 -0
- trlog/query/_export.py +300 -0
- trlog/query/_expr.py +1111 -0
- trlog/query/_format.py +323 -0
- trlog/query/_rows.py +162 -0
- trlog/query/_values.py +276 -0
- trlog/share/include/trl/trl.h +211 -0
- trlog/share/include/trl/trl_api.h +35 -0
- trlog/share/include/trl/trl_codec.h +188 -0
- trlog/share/include/trl/trl_qscan.h +174 -0
- trlog/share/include/trl/trl_query.h +114 -0
- trlog/share/include/trl/trl_rec.h +110 -0
- trlog/share/include/trlog_vpi.h +34 -0
- trlog/share/sv/trl_cursor.svh +144 -0
- trlog/share/sv/trl_db.svh +111 -0
- trlog/share/sv/trl_final.sv +13 -0
- trlog/share/sv/trl_macros.svh +31 -0
- trlog/share/sv/trl_pkg.sv +87 -0
- trlog/share/sv/trl_reader.svh +93 -0
- trlog/share/sv/trl_rstream.svh +22 -0
- trlog/share/sv/trl_schema.svh +40 -0
- trlog/share/sv/trl_stream.svh +175 -0
- trlog/share/sv/trl_sv_dpi.svh +96 -0
- trlog/share/sv/trl_txn.svh +98 -0
- trlog/share/sv/trl_type.svh +107 -0
- trlog/share/sv/trl_uvm_pkg.sv +332 -0
- trlog/trl.dll +0 -0
- trlog/trl.lib +0 -0
- trlog/trl_sv.dll +0 -0
- trlog/trl_sv.lib +0 -0
- trlog/trlog_vpi.dll +0 -0
- trlog/trlog_vpi.lib +0 -0
- trlog/weave/__init__.py +8 -0
- trlog/weave/_record.py +340 -0
- trlog-0.1.0.dist-info/METADATA +217 -0
- trlog-0.1.0.dist-info/RECORD +70 -0
- trlog-0.1.0.dist-info/WHEEL +5 -0
- trlog-0.1.0.dist-info/entry_points.txt +5 -0
- trlog-0.1.0.dist-info/licenses/LICENSE +201 -0
- trlog-0.1.0.dist-info/top_level.txt +1 -0
trlog/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""TRLOG — ZuSpec Trace binary format reader/writer."""
|
|
2
|
+
|
|
3
|
+
from .__version__ import _pkg_version as __version__
|
|
4
|
+
|
|
5
|
+
from ._types import (
|
|
6
|
+
BlockType, HierKind, ScopeType, VarDir, SignalEncoding,
|
|
7
|
+
FieldType, TxnRecordTag, LinkType, Radix, HierTag, AttrType,
|
|
8
|
+
FILE_MAGIC, BLOCK_HEADER_SIZE, FLAG_COMPRESSED, FLAG_COMPRESS_ALG,
|
|
9
|
+
FieldDef, SignalTypeEntry, TxnSchemaEntry, EnumValue, EnumTypeEntry,
|
|
10
|
+
StreamDeclEntry, HierarchyHeader, HScope, HVar, HStream, HAttr, TypedAttr,
|
|
11
|
+
VcChange, TxnAttr, TxnFull, TxnBegin, TxnAttrRecord, TxnEnd, TxnLink,
|
|
12
|
+
TxnMeta, WellKnownAttr,
|
|
13
|
+
)
|
|
14
|
+
from ._codec import (
|
|
15
|
+
encode_uvarint, decode_uvarint,
|
|
16
|
+
encode_svarint, decode_svarint,
|
|
17
|
+
encode_field, decode_field,
|
|
18
|
+
)
|
|
19
|
+
from ._native import TrlWriter, TrlReader
|
|
20
|
+
from ._libpath import get_libdirs, get_incdirs, get_svdirs
|
|
21
|
+
from ._reader import ScopeNode
|
|
22
|
+
from ._ext import ExtBlock
|
|
23
|
+
from ._deps import DependencyGraph, Materializer, DependencyError
|
|
24
|
+
from ._derived import Input, Const, compile_expr
|
|
25
|
+
from . import codec
|
|
26
|
+
from .codec import (
|
|
27
|
+
VcCodec, TxnCodec, Capability, Store,
|
|
28
|
+
vc_codec, txn_codec,
|
|
29
|
+
register_vc_codec, register_txn_codec,
|
|
30
|
+
lookup_vc_codec, lookup_txn_codec,
|
|
31
|
+
CORE_VALUECHANGE, CORE_RECORD, CORE_BYTESPLIT, CORE_DERIVED,
|
|
32
|
+
)
|
|
33
|
+
from ._exceptions import (
|
|
34
|
+
ZstError, ZstMagicError, ZstVersionError, ZstFormatError,
|
|
35
|
+
ZstCompressionError, ZstNoIndexError, ZstCorruptError,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"BlockType", "HierKind", "ScopeType", "VarDir", "SignalEncoding",
|
|
40
|
+
"FieldType", "TxnRecordTag", "LinkType", "Radix", "HierTag", "AttrType",
|
|
41
|
+
"FILE_MAGIC", "BLOCK_HEADER_SIZE", "FLAG_COMPRESSED", "FLAG_COMPRESS_ALG",
|
|
42
|
+
"FieldDef", "SignalTypeEntry", "TxnSchemaEntry", "EnumValue", "EnumTypeEntry",
|
|
43
|
+
"StreamDeclEntry", "HierarchyHeader", "HScope", "HVar", "HStream", "HAttr", "TypedAttr",
|
|
44
|
+
"VcChange", "TxnAttr", "TxnFull", "TxnBegin", "TxnAttrRecord", "TxnEnd", "TxnLink",
|
|
45
|
+
"TxnMeta", "WellKnownAttr",
|
|
46
|
+
"encode_uvarint", "decode_uvarint",
|
|
47
|
+
"encode_svarint", "decode_svarint",
|
|
48
|
+
"encode_field", "decode_field",
|
|
49
|
+
"TrlWriter", "TrlReader", "ScopeNode", "ExtBlock",
|
|
50
|
+
"DependencyGraph", "Materializer", "DependencyError",
|
|
51
|
+
"Input", "Const", "compile_expr",
|
|
52
|
+
"codec", "VcCodec", "TxnCodec", "Capability", "Store",
|
|
53
|
+
"vc_codec", "txn_codec",
|
|
54
|
+
"register_vc_codec", "register_txn_codec",
|
|
55
|
+
"lookup_vc_codec", "lookup_txn_codec",
|
|
56
|
+
"CORE_VALUECHANGE", "CORE_RECORD", "CORE_BYTESPLIT", "CORE_DERIVED",
|
|
57
|
+
"ZstError", "ZstMagicError", "ZstVersionError", "ZstFormatError",
|
|
58
|
+
"ZstCompressionError", "ZstNoIndexError", "ZstCorruptError",
|
|
59
|
+
"get_libdirs", "get_incdirs", "get_svdirs",
|
|
60
|
+
]
|
trlog/__main__.py
ADDED
trlog/__version__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# The single source of this package's version, in the same shape as
|
|
2
|
+
# dv-solve's and pssparser's __version__.py.
|
|
3
|
+
#
|
|
4
|
+
# BASE is the released version and is what a `v<BASE>` tag must match; the
|
|
5
|
+
# release job rejects a tag that disagrees with it, and stamps the same
|
|
6
|
+
# version into the npm package. SUFFIX is rewritten by CI for non-release
|
|
7
|
+
# builds so a development wheel can never collide with a release.
|
|
8
|
+
|
|
9
|
+
BASE = "0.1.0"
|
|
10
|
+
SUFFIX = ""
|
|
11
|
+
|
|
12
|
+
__version__ = (BASE, SUFFIX)
|
|
13
|
+
|
|
14
|
+
# Read by setup.py, which exec()s this file rather than importing trlog: the
|
|
15
|
+
# package is not importable while the ivpm_build backend computes build
|
|
16
|
+
# requirements, so a [tool.setuptools.dynamic] attr: entry would fail there.
|
|
17
|
+
_pkg_version = BASE + SUFFIX
|
trlog/_aux.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Opaque keyed (non-temporal) metadata blocks — BLK_AUX (impl-plan §2.4).
|
|
2
|
+
|
|
3
|
+
Opaque bulk metadata is *just a non-temporal stream*: the same self-delimiting
|
|
4
|
+
block framing and byte compression as value-change / transaction data, but
|
|
5
|
+
addressed by **key** instead of time and recorded in a parallel **key index**
|
|
6
|
+
("one block pool, two indexes", design §4.0). The payload bytes are produced by
|
|
7
|
+
a codec and are opaque to the core — a reader lacking the codec enumerates aux
|
|
8
|
+
blocks by ``(owner_stream_id, key)`` and skips them by length, exactly like any
|
|
9
|
+
unknown block (§2.8), with no new skip logic.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import zlib
|
|
15
|
+
|
|
16
|
+
from ._string_table import _make_block
|
|
17
|
+
from ._types import (
|
|
18
|
+
BlockType, FLAG_COMPRESSED, FLAG_COMPRESS_ALG,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AuxBlock:
|
|
23
|
+
"""Encode/decode one opaque keyed metadata block (``BLK_AUX``).
|
|
24
|
+
|
|
25
|
+
The block carries raw codec-produced bytes; the core only frames and
|
|
26
|
+
(optionally) byte-compresses them, identically to data blocks.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def encode(payload: bytes, compress: bool = False, use_zstd: bool = False) -> bytes:
|
|
31
|
+
flags = 0
|
|
32
|
+
data = bytes(payload)
|
|
33
|
+
if compress and data:
|
|
34
|
+
if use_zstd:
|
|
35
|
+
import zstandard as zstd # type: ignore
|
|
36
|
+
data = zstd.ZstdCompressor().compress(data)
|
|
37
|
+
flags |= FLAG_COMPRESSED | FLAG_COMPRESS_ALG
|
|
38
|
+
else:
|
|
39
|
+
data = zlib.compress(data)
|
|
40
|
+
flags |= FLAG_COMPRESSED
|
|
41
|
+
return _make_block(BlockType.BLK_AUX, flags, data)
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def decode(payload: bytes | memoryview, flags: int = 0) -> bytes:
|
|
45
|
+
if flags & FLAG_COMPRESSED:
|
|
46
|
+
if flags & FLAG_COMPRESS_ALG:
|
|
47
|
+
import zstandard as zstd # type: ignore
|
|
48
|
+
return zstd.ZstdDecompressor().decompress(bytes(payload))
|
|
49
|
+
return zlib.decompress(bytes(payload))
|
|
50
|
+
return bytes(payload)
|
trlog/_bytesplit.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Byte-plane split transform and the block format of ``core.bytesplit``.
|
|
2
|
+
|
|
3
|
+
The transform is the same as Parquet's BYTE_STREAM_SPLIT: given ``n`` values
|
|
4
|
+
of ``width`` bytes each, it stores all byte 0s together, then all byte 1s, and
|
|
5
|
+
so on. A byte compressor applied afterwards sees homogeneous planes; the
|
|
6
|
+
high-order bytes of slowly varying reals and wide counters are nearly
|
|
7
|
+
constant and compress to long runs. The transform is reversible.
|
|
8
|
+
|
|
9
|
+
:class:`BytesplitBlock` is the block accumulator and encoder used by
|
|
10
|
+
:class:`trlog.codec.CoreBytesplitCodec` (``org.fvutils.trlog.core.bytesplit``).
|
|
11
|
+
Its blocks set ``FLAG_STRUCT_CODEC`` and start the payload with the interned
|
|
12
|
+
codec id, so a reader dispatches them by id and a reader without the codec
|
|
13
|
+
skips them by the block length.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import struct
|
|
19
|
+
import zlib
|
|
20
|
+
from typing import Dict, List, Tuple
|
|
21
|
+
|
|
22
|
+
from ._codec import encode_uvarint, decode_uvarint
|
|
23
|
+
from ._string_table import _make_block
|
|
24
|
+
from ._types import (
|
|
25
|
+
BlockType, SignalEncoding, FLAG_STRUCT_CODEC,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Pure transform
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
def byte_split(raw: bytes, width: int) -> bytes:
|
|
34
|
+
"""Split ``raw`` into ``width`` byte planes.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
raw: ``n * width`` bytes: ``n`` values of ``width`` bytes each.
|
|
38
|
+
width: Bytes per value. 0 or 1 returns ``raw`` unchanged.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
Plane 0 (byte 0 of every value), then plane 1, and so on.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
ValueError: If ``len(raw)`` is not a multiple of ``width``.
|
|
45
|
+
"""
|
|
46
|
+
if width <= 1:
|
|
47
|
+
return bytes(raw)
|
|
48
|
+
if len(raw) % width != 0:
|
|
49
|
+
raise ValueError(f"byte_split: length {len(raw)} not a multiple of width {width}")
|
|
50
|
+
n = len(raw) // width
|
|
51
|
+
out = bytearray(len(raw))
|
|
52
|
+
for plane in range(width):
|
|
53
|
+
base = plane * n
|
|
54
|
+
src = plane
|
|
55
|
+
for i in range(n):
|
|
56
|
+
out[base + i] = raw[src]
|
|
57
|
+
src += width
|
|
58
|
+
return bytes(out)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def byte_unsplit(data: bytes, width: int) -> bytes:
|
|
62
|
+
"""Inverse of :func:`byte_split`.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
ValueError: If ``len(data)`` is not a multiple of ``width``.
|
|
66
|
+
"""
|
|
67
|
+
if width <= 1:
|
|
68
|
+
return bytes(data)
|
|
69
|
+
if len(data) % width != 0:
|
|
70
|
+
raise ValueError(f"byte_unsplit: length {len(data)} not a multiple of width {width}")
|
|
71
|
+
n = len(data) // width
|
|
72
|
+
out = bytearray(len(data))
|
|
73
|
+
for plane in range(width):
|
|
74
|
+
base = plane * n
|
|
75
|
+
dst = plane
|
|
76
|
+
for i in range(n):
|
|
77
|
+
out[dst] = data[base + i]
|
|
78
|
+
dst += width
|
|
79
|
+
return bytes(out)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---------------------------------------------------------------------------
|
|
83
|
+
# Value <-> fixed-width little-endian bytes
|
|
84
|
+
# ---------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
_KIND_UINT = 0
|
|
87
|
+
_KIND_REAL = 1
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _value_width(encoding: int, bit_width: int) -> Tuple[int, int]:
|
|
91
|
+
"""Return ``(kind, byte_width)`` for a signal type, or raise if bytesplit
|
|
92
|
+
cannot represent it (it only handles fixed-width numeric values)."""
|
|
93
|
+
if encoding == SignalEncoding.SE_REAL:
|
|
94
|
+
return _KIND_REAL, 8
|
|
95
|
+
if encoding in (SignalEncoding.SE_2STATE,):
|
|
96
|
+
bw = max(1, bit_width)
|
|
97
|
+
return _KIND_UINT, (bw + 7) // 8
|
|
98
|
+
raise ValueError(f"bytesplit does not support encoding {encoding!r}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _encode_value(kind: int, width: int, value) -> bytes:
|
|
102
|
+
if kind == _KIND_REAL:
|
|
103
|
+
return struct.pack("<d", float(value))
|
|
104
|
+
return int(value).to_bytes(width, "little")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _decode_value(kind: int, width: int, raw: bytes):
|
|
108
|
+
if kind == _KIND_REAL:
|
|
109
|
+
return struct.unpack("<d", raw)[0]
|
|
110
|
+
return int.from_bytes(raw, "little")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ---------------------------------------------------------------------------
|
|
114
|
+
# Self-contained bytesplit value-change block
|
|
115
|
+
# ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
class BytesplitBlock:
|
|
118
|
+
"""Accumulates value changes and encodes one ``core.bytesplit`` block.
|
|
119
|
+
|
|
120
|
+
Supports ``SE_REAL`` (8-byte IEEE double) and ``SE_2STATE`` signals
|
|
121
|
+
(``ceil(bit_width / 8)`` bytes, little-endian unsigned). Other encodings
|
|
122
|
+
raise ``ValueError`` at encode time.
|
|
123
|
+
|
|
124
|
+
Payload layout (after the 10-byte block header; block type
|
|
125
|
+
``BLK_VC_DATA``, flags ``FLAG_STRUCT_CODEC``)::
|
|
126
|
+
|
|
127
|
+
uvarint codec_id_str string-table id of the codec id
|
|
128
|
+
uvarint internal_flags bit 0: body is zlib-compressed
|
|
129
|
+
body:
|
|
130
|
+
uvarint start_time
|
|
131
|
+
uvarint var_count
|
|
132
|
+
var_count x:
|
|
133
|
+
uvarint var_id
|
|
134
|
+
u8 kind 0 = unsigned int, 1 = real
|
|
135
|
+
uvarint width bytes per value (the plane count)
|
|
136
|
+
uvarint count
|
|
137
|
+
count x uvarint time deltas (first from 0, then from
|
|
138
|
+
the previous change)
|
|
139
|
+
count*width bytes byte_split() of the little-endian values
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
start_time: Block start time.
|
|
143
|
+
sig_types: Map of var id to ``(SignalEncoding, bit_width)``.
|
|
144
|
+
compress: zlib-compress the body.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
_FLAG_ZLIB = 0x01
|
|
148
|
+
|
|
149
|
+
def __init__(self, start_time: int, sig_types: Dict[int, Tuple[int, int]],
|
|
150
|
+
compress: bool = True) -> None:
|
|
151
|
+
self.start_time = start_time
|
|
152
|
+
self.end_time = start_time
|
|
153
|
+
self._sig_types = sig_types
|
|
154
|
+
self._compress = compress
|
|
155
|
+
self._changes: Dict[int, List[Tuple[int, object]]] = {}
|
|
156
|
+
|
|
157
|
+
def add_change(self, var_id: int, time: int, value) -> None:
|
|
158
|
+
"""Append a change. Changes of one variable must be in time order."""
|
|
159
|
+
self._changes.setdefault(var_id, []).append((time, value))
|
|
160
|
+
if time > self.end_time:
|
|
161
|
+
self.end_time = time
|
|
162
|
+
|
|
163
|
+
def set_initial(self, var_id: int, value) -> None:
|
|
164
|
+
"""Record ``value`` at the block start time, before any other change."""
|
|
165
|
+
self._changes.setdefault(var_id, []).insert(0, (self.start_time, value))
|
|
166
|
+
|
|
167
|
+
def encode_block(self, codec_id_str: int) -> bytes:
|
|
168
|
+
"""Encode the accumulated changes.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
codec_id_str: String-table id of the codec id string.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
The complete block, header included.
|
|
175
|
+
"""
|
|
176
|
+
body = bytearray()
|
|
177
|
+
body += encode_uvarint(self.start_time)
|
|
178
|
+
body += encode_uvarint(len(self._changes))
|
|
179
|
+
for var_id in sorted(self._changes):
|
|
180
|
+
changes = self._changes[var_id]
|
|
181
|
+
enc, bw = self._sig_types[var_id]
|
|
182
|
+
kind, width = _value_width(int(enc), bw)
|
|
183
|
+
body += encode_uvarint(var_id)
|
|
184
|
+
body.append(kind)
|
|
185
|
+
body += encode_uvarint(width) # plane count param
|
|
186
|
+
body += encode_uvarint(len(changes))
|
|
187
|
+
prev_t = 0
|
|
188
|
+
raw = bytearray()
|
|
189
|
+
for t, v in changes:
|
|
190
|
+
body += encode_uvarint(t - prev_t) # time deltas (monotonic)
|
|
191
|
+
prev_t = t
|
|
192
|
+
raw += _encode_value(kind, width, v)
|
|
193
|
+
body += byte_split(bytes(raw), width)
|
|
194
|
+
|
|
195
|
+
internal_flags = 0
|
|
196
|
+
payload_body = bytes(body)
|
|
197
|
+
if self._compress and payload_body:
|
|
198
|
+
payload_body = zlib.compress(payload_body)
|
|
199
|
+
internal_flags |= self._FLAG_ZLIB
|
|
200
|
+
|
|
201
|
+
payload = bytearray()
|
|
202
|
+
payload += encode_uvarint(codec_id_str) # self-identifying prefix
|
|
203
|
+
payload += encode_uvarint(internal_flags)
|
|
204
|
+
payload += payload_body
|
|
205
|
+
return _make_block(BlockType.BLK_VC_DATA, FLAG_STRUCT_CODEC, bytes(payload))
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def decode_changes(payload: bytes, emit, vc_change_cls):
|
|
209
|
+
"""Decode a ``core.bytesplit`` payload and emit its changes.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
payload: The block payload without the 10-byte header. It still
|
|
213
|
+
starts with the codec-id prefix, which is skipped, not checked.
|
|
214
|
+
emit: Called once per change.
|
|
215
|
+
vc_change_cls: Class used to build each change, called as
|
|
216
|
+
``vc_change_cls(var_id=..., time=..., value=...)``.
|
|
217
|
+
"""
|
|
218
|
+
offset = 0
|
|
219
|
+
_codec_id_str, offset = decode_uvarint(payload, offset)
|
|
220
|
+
internal_flags, offset = decode_uvarint(payload, offset)
|
|
221
|
+
body = payload[offset:]
|
|
222
|
+
if internal_flags & BytesplitBlock._FLAG_ZLIB:
|
|
223
|
+
body = zlib.decompress(bytes(body))
|
|
224
|
+
body = bytes(body)
|
|
225
|
+
o = 0
|
|
226
|
+
start_time, o = decode_uvarint(body, o)
|
|
227
|
+
n_vars, o = decode_uvarint(body, o)
|
|
228
|
+
for _ in range(n_vars):
|
|
229
|
+
var_id, o = decode_uvarint(body, o)
|
|
230
|
+
kind = body[o]; o += 1
|
|
231
|
+
width, o = decode_uvarint(body, o)
|
|
232
|
+
count, o = decode_uvarint(body, o)
|
|
233
|
+
times = []
|
|
234
|
+
prev_t = 0
|
|
235
|
+
for _ in range(count):
|
|
236
|
+
d, o = decode_uvarint(body, o)
|
|
237
|
+
prev_t += d
|
|
238
|
+
times.append(prev_t)
|
|
239
|
+
split = body[o:o + count * width]; o += count * width
|
|
240
|
+
raw = byte_unsplit(split, width)
|
|
241
|
+
for i, t in enumerate(times):
|
|
242
|
+
v = _decode_value(kind, width, raw[i * width:(i + 1) * width])
|
|
243
|
+
emit(vc_change_cls(var_id=var_id, time=t, value=v))
|
trlog/_codec.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Stateless varint and field encode/decode functions.
|
|
2
|
+
|
|
3
|
+
All functions are pure (no I/O). They operate on ``bytes``, ``bytearray``,
|
|
4
|
+
or ``memoryview`` objects.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import struct
|
|
10
|
+
from typing import Any, Tuple, Union
|
|
11
|
+
|
|
12
|
+
from ._types import FieldType
|
|
13
|
+
|
|
14
|
+
Buffer = Union[bytes, bytearray, memoryview]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ---------------------------------------------------------------------------
|
|
18
|
+
# Unsigned LEB-128 varint
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
def encode_uvarint(n: int) -> bytes:
|
|
22
|
+
"""Encode a non-negative integer as an unsigned LEB-128 varint."""
|
|
23
|
+
if n < 0:
|
|
24
|
+
raise ValueError(f"encode_uvarint requires n >= 0, got {n}")
|
|
25
|
+
out = bytearray()
|
|
26
|
+
while True:
|
|
27
|
+
byte = n & 0x7F
|
|
28
|
+
n >>= 7
|
|
29
|
+
if n:
|
|
30
|
+
out.append(byte | 0x80)
|
|
31
|
+
else:
|
|
32
|
+
out.append(byte)
|
|
33
|
+
break
|
|
34
|
+
return bytes(out)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def decode_uvarint(buf: Buffer, offset: int = 0) -> Tuple[int, int]:
|
|
38
|
+
"""Decode an unsigned LEB-128 varint from *buf* starting at *offset*.
|
|
39
|
+
|
|
40
|
+
Returns ``(value, new_offset)``. Raises ``ValueError`` on truncated input.
|
|
41
|
+
"""
|
|
42
|
+
result = 0
|
|
43
|
+
shift = 0
|
|
44
|
+
while True:
|
|
45
|
+
if offset >= len(buf):
|
|
46
|
+
raise ValueError("Truncated uvarint: buffer ended unexpectedly")
|
|
47
|
+
byte = buf[offset]
|
|
48
|
+
offset += 1
|
|
49
|
+
result |= (byte & 0x7F) << shift
|
|
50
|
+
if not (byte & 0x80):
|
|
51
|
+
return result, offset
|
|
52
|
+
shift += 7
|
|
53
|
+
if shift >= 64:
|
|
54
|
+
raise ValueError("uvarint too large (> 64 bits)")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
# Signed zigzag-encoded varint
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
def encode_svarint(n: int) -> bytes:
|
|
62
|
+
"""Encode a signed integer as a zigzag-encoded unsigned LEB-128 varint."""
|
|
63
|
+
encoded = (n << 1) ^ (n >> 63)
|
|
64
|
+
return encode_uvarint(encoded & 0xFFFFFFFFFFFFFFFF)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def decode_svarint(buf: Buffer, offset: int = 0) -> Tuple[int, int]:
|
|
68
|
+
"""Decode a zigzag-encoded signed LEB-128 varint.
|
|
69
|
+
|
|
70
|
+
Returns ``(value, new_offset)``.
|
|
71
|
+
"""
|
|
72
|
+
n, offset = decode_uvarint(buf, offset)
|
|
73
|
+
value = (n >> 1) ^ -(n & 1)
|
|
74
|
+
return value, offset
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
# Field encode/decode per FieldType
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
_FMT = {
|
|
82
|
+
FieldType.FT_U8: ('<B', 1),
|
|
83
|
+
FieldType.FT_U16: ('<H', 2),
|
|
84
|
+
FieldType.FT_U32: ('<I', 4),
|
|
85
|
+
FieldType.FT_U64: ('<Q', 8),
|
|
86
|
+
FieldType.FT_I8: ('<b', 1),
|
|
87
|
+
FieldType.FT_I16: ('<h', 2),
|
|
88
|
+
FieldType.FT_I32: ('<i', 4),
|
|
89
|
+
FieldType.FT_I64: ('<q', 8),
|
|
90
|
+
FieldType.FT_F32: ('<f', 4),
|
|
91
|
+
FieldType.FT_F64: ('<d', 8),
|
|
92
|
+
FieldType.FT_BOOL: ('<B', 1),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def encode_field(ft: FieldType, value: Any) -> bytes:
|
|
97
|
+
"""Encode *value* as field type *ft* and return the wire bytes."""
|
|
98
|
+
if ft in _FMT:
|
|
99
|
+
fmt, _ = _FMT[ft]
|
|
100
|
+
if ft == FieldType.FT_BOOL:
|
|
101
|
+
value = 1 if value else 0
|
|
102
|
+
return struct.pack(fmt, value)
|
|
103
|
+
|
|
104
|
+
if ft == FieldType.FT_STRING:
|
|
105
|
+
encoded = value.encode('utf-8') if isinstance(value, str) else bytes(value)
|
|
106
|
+
return encode_uvarint(len(encoded)) + encoded
|
|
107
|
+
|
|
108
|
+
if ft == FieldType.FT_BITVEC:
|
|
109
|
+
# value is (bit_width, int_value) tuple
|
|
110
|
+
bit_width, int_value = value
|
|
111
|
+
nbytes = (bit_width + 7) // 8
|
|
112
|
+
raw = int_value.to_bytes(nbytes, 'big')
|
|
113
|
+
return encode_uvarint(bit_width) + raw
|
|
114
|
+
|
|
115
|
+
if ft == FieldType.FT_BYTES:
|
|
116
|
+
raw = bytes(value)
|
|
117
|
+
return encode_uvarint(len(raw)) + raw
|
|
118
|
+
|
|
119
|
+
if ft == FieldType.FT_TIME:
|
|
120
|
+
return struct.pack('<Q', value)
|
|
121
|
+
|
|
122
|
+
if ft == FieldType.FT_ENUM:
|
|
123
|
+
return encode_uvarint(value)
|
|
124
|
+
|
|
125
|
+
if ft == FieldType.FT_LOGICVEC:
|
|
126
|
+
# value is (bit_width, aval, bval); aval then bval, big-endian like FT_BITVEC
|
|
127
|
+
bit_width, aval, bval = value
|
|
128
|
+
nbytes = (bit_width + 7) // 8
|
|
129
|
+
return (encode_uvarint(bit_width) + aval.to_bytes(nbytes, 'big')
|
|
130
|
+
+ bval.to_bytes(nbytes, 'big'))
|
|
131
|
+
|
|
132
|
+
raise ValueError(f"Unknown FieldType: {ft!r}")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def decode_field(ft: FieldType, buf: Buffer, offset: int = 0) -> Tuple[Any, int]:
|
|
136
|
+
"""Decode a field of type *ft* from *buf* at *offset*.
|
|
137
|
+
|
|
138
|
+
Returns ``(value, new_offset)``.
|
|
139
|
+
"""
|
|
140
|
+
if ft in _FMT:
|
|
141
|
+
fmt, size = _FMT[ft]
|
|
142
|
+
value, = struct.unpack_from(fmt, buf, offset)
|
|
143
|
+
if ft == FieldType.FT_BOOL:
|
|
144
|
+
value = bool(value)
|
|
145
|
+
return value, offset + size
|
|
146
|
+
|
|
147
|
+
if ft == FieldType.FT_STRING:
|
|
148
|
+
length, offset = decode_uvarint(buf, offset)
|
|
149
|
+
raw = bytes(buf[offset:offset + length])
|
|
150
|
+
return raw.decode('utf-8'), offset + length
|
|
151
|
+
|
|
152
|
+
if ft == FieldType.FT_BITVEC:
|
|
153
|
+
bit_width, offset = decode_uvarint(buf, offset)
|
|
154
|
+
nbytes = (bit_width + 7) // 8
|
|
155
|
+
raw = bytes(buf[offset:offset + nbytes])
|
|
156
|
+
int_value = int.from_bytes(raw, 'big')
|
|
157
|
+
return (bit_width, int_value), offset + nbytes
|
|
158
|
+
|
|
159
|
+
if ft == FieldType.FT_BYTES:
|
|
160
|
+
length, offset = decode_uvarint(buf, offset)
|
|
161
|
+
raw = bytes(buf[offset:offset + length])
|
|
162
|
+
return raw, offset + length
|
|
163
|
+
|
|
164
|
+
if ft == FieldType.FT_TIME:
|
|
165
|
+
value, = struct.unpack_from('<Q', buf, offset)
|
|
166
|
+
return value, offset + 8
|
|
167
|
+
|
|
168
|
+
if ft == FieldType.FT_ENUM:
|
|
169
|
+
return decode_uvarint(buf, offset)
|
|
170
|
+
|
|
171
|
+
if ft == FieldType.FT_LOGICVEC:
|
|
172
|
+
bit_width, offset = decode_uvarint(buf, offset)
|
|
173
|
+
nbytes = (bit_width + 7) // 8
|
|
174
|
+
aval = int.from_bytes(bytes(buf[offset:offset + nbytes]), 'big')
|
|
175
|
+
offset += nbytes
|
|
176
|
+
bval = int.from_bytes(bytes(buf[offset:offset + nbytes]), 'big')
|
|
177
|
+
return (bit_width, aval, bval), offset + nbytes
|
|
178
|
+
|
|
179
|
+
raise ValueError(f"Unknown FieldType: {ft!r}")
|