Skip to main content

StructLayoutToolkitCalc

A safe, deterministic expression evaluator for computing bit‑accurate offsets, sizes, and field values within StructLayoutToolkit.

Overview

sltcalc provides a safe and deterministic expression evaluator used across StructLayoutToolkit to compute bit‑accurate offsets, sizes, and derived field values. It parses expressions into Python’s AST and evaluates a restricted subset of operations, ensuring predictable behavior without accessing Python globals or executing arbitrary code. The evaluator supports arithmetic, bitwise operations, conditional expressions, and user‑defined variables supplied through an isolated environment. This module enables dynamic field definitions, computed offsets, variable‑length structures, and protocol‑specific formulas while maintaining strict safety and structural consistency.

Usage

Basic

from sltcalc import SltEval

evaluator = SltEval()
result = evaluator.eval("1 + 2 * 3")
print(result)  # 7

With variables

from sltcalc import SltEval

env = {
    "offset": 8,
    "width": 3,
    "flag": True,
}

evaluator = SltEval(env)

print(evaluator.eval("offset + width * 2"))       # 14
print(evaluator.eval("1 if flag else 0"))         # 1
print(evaluator.eval("99 if offset >= 8 else -1"))  # 99

Error behavior

from sltcalc import SltEval

evaluator = SltEval()

# NameError: undefined variable
evaluator.eval("unknown + 1")

# ValueError: unsafe function
evaluator.eval("sum(1, 2)")

Supported expressions

SltEval evaluates a restricted subset of Python expression AST nodes.

Literals

  • Numeric constants (for example: 0, 42, 3.5)
  • Boolean constants (True, False)
  • List literals (for example: [1, 2, 3])
  • Tuple literals (for example: (1, 2, 3))
  • Dict literals (for example: {"a": 1, "b": 2})

Variables

  • Variable lookup from the evaluator environment (SltEval(env))
  • Attribute access on environment values (for example: obj.value)

Binary operators

  • Arithmetic: +, -, *, /, //, %, **
  • Bitwise: &, |, ^, <<, >>

Unary operators

  • Unary plus: +x
  • Unary minus: -x
  • Boolean negation: not x

Boolean operators

  • and
  • or

Comparisons

  • ==, !=, <, <=, >, >=, is, is not, in, not in
  • Chained comparisons are supported (for example: 1 < 2 < 3)

Conditional expression

  • Ternary expression: a if condition else b

Attribute and subscript access

  • Index/key access (for example: arr[0], mapping["key"])
  • Slicing (for example: arr[1:4], arr[:3], arr[::2], arr[::-1])
  • Slice bounds and steps may be omitted; negative indices and steps follow Python sequence semantics
  • Attribute access is supported (for example: obj.value)
  • Nested access is supported (for example: access key "items" and then index 0)

Function calls

  • Built-in allowlist: abs(...), all(...), any(...), len(...), bytes(...), bytearray(...), min(...), max(...), round(...), sorted(...), sum(...)
  • Callables passed through environment are allowed (for example: SltEval({"triple": triple}) then triple(4))
  • Byte strings and byte arrays can be compared using standard comparison operators.

Not supported

  • Set literals in expressions
  • Non-name call targets (for example: (lambda x: x)(1))

Unsupported constructs raise ValueError with an Unsupported expression message.

Testing

Run the complete test suite:

uv run pytest -q

Generate a branch coverage report in the terminal:

uv run pytest --cov=sltcalc --cov-branch --cov-report=term-missing -q

Generate a browsable HTML coverage report in htmlcov/:

uv run pytest --cov=sltcalc --cov-branch --cov-report=html -q

Open htmlcov/index.html in a browser to inspect uncovered lines and branches.

Metadata

Release files for sltcalc 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sltcalc 1.2.0
File Size Uploaded
sltcalc-1.2.0.tar.gz 21.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sltcalc 1.2.0
File Interpreter ABI Platform
sltcalc-1.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 26.6 kB

Release files / sltcalc-1.2.0.tar.gz

Download URL sltcalc-1.2.0.tar.gz
Size 21.3 kB
Tags Source
SHA-256 checksum
How to use checksums
f8517709ff9f46c542dfb886af7cd246a75f82ee2b2ddea535cb10152ac23fe7
BLAKE2b-256 checksum
How to use checksums
2dc0208bc7471d53ad8703a7166a9fccd93371cd96d16662358a1a509c7237dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / sltcalc-1.2.0-py3-none-any.whl

Download URL sltcalc-1.2.0-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
316316baf0c79421931f33484c4aa753228184f9e74446b420745e3a60973782
BLAKE2b-256 checksum
How to use checksums
8e55a3ba64a52a42ddedbc37aa4d1fdb9ce57a62d6f9f1a2bbc3e482ad776709
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page