OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Check byte ranges against a declared payload size with Python

Python

Identify ranges extending beyond a supplied payload size without reading a payload file.

Python code excerpt: Check byte ranges against a declared payload size with Python. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Identify ranges extending beyond a supplied payload size without reading a payload file. This is a local data check under the documented conventions; it does not execute tools or contact a service.

Before you start

  • Save the code as recipe.py and run python3.12 recipe.py with no arguments, including no help option. Supply one JSON object through stdin and finish the stream with EOF.
  • Example stdin: {"size":10,"ranges":[{"start":0,"length":10},{"start":9,"length":2}]}. Its output is {"range_count":2,"out_of_bounds":[2],"within_bounds":false}.
  • Input must be strict UTF-8 without a leading BOM and contain valid JSON. NaN, Infinity, -Infinity and floating-point overflow are rejected during parsing.
  • size must be an integer from 0 through 1000000000. ranges must be an array of at most 100 objects. Each start must be an integer from 0 through 1000000000, and each length an integer from 1 through 1000000000. Booleans and floating-point numbers are not accepted as integer fields.
  • Additional fields are ignored after JSON parsing. Duplicate JSON object names follow the json module's convention: the last value wins.
  • A range is treated as the half-open interval [start, start + length). It is out of bounds only when start + length exceeds size; equality is within bounds. Reported positions are one-based and retain input order. An empty ranges array is within bounds.
  • Successful processing, including bounds violations, exits 0 and emits exactly one JSON object followed by a newline, with no stderr. Invalid input, arguments or stdin read failures exit 2, emit no stdout and use the generic diagnostic error: invalid input.

Build and check

  1. Use Python 3.12. Save the code as recipe.py.
  2. Save the supplied JSON example as input.json, encoded as UTF-8 without a BOM.
  3. Run: python3 recipe.py < input.json
  4. Compare the output with the expected result; handle exit code 2 as invalid input.

Limits to understand

  • The CLI uses only json, sys and math. It reads stdin only and does not open input paths, write files, execute commands or contact a network.
  • It reads at most 65537 bytes and rejects inputs exceeding 65536 bytes. stdin can block while waiting for EOF or the read limit.
  • The raw input, decoded text and parsed JSON are held in memory. Parsing overhead depends on input structure; excessively deep nesting or Python integer-conversion limits can cause rejection.
  • This checks declared byte-range arithmetic only. It does not read a payload or verify actual file size, overlap, payload encoding or payload contents. Strict UTF-8 validation applies only to the JSON input.
  • Successful output reveals the number of ranges and which positions exceed the declared size; treat that output as potentially sensitive.
  • Output-write failures are outside the stated exit-code and diagnostic guarantees.

Run it

python3 recipe.py < input.json

Example input

{"size": 10, "ranges": [{"start": 0, "length": 5}, {"start": 9, "length": 2}]}

Expected output

{"range_count": 2, "out_of_bounds": [2], "within_bounds": false}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import json
import sys
import math


def reject_constant(_value):
    raise ValueError("invalid JSON number")


def finite_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise ValueError("invalid JSON number")
    return value


def valid_integer(value, minimum, maximum):
    return (
        isinstance(value, int)
        and not isinstance(value, bool)
        and minimum <= value <= maximum
    )


def process():
    raw = sys.stdin.buffer.read(65537)
    if len(raw) > 65536:
        raise ValueError("input too large")

    text = raw.decode("utf-8", errors="strict")
    if text.startswith("\ufeff"):
        raise ValueError("leading BOM")

    data = json.loads(
        text,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )
    if not isinstance(data, dict):
        raise ValueError("invalid structure")

    size = data.get("size")
    ranges = data.get("ranges")
    if not valid_integer(size, 0, 1000000000):
        raise ValueError("invalid size")
    if not isinstance(ranges, list) or len(ranges) > 100:
        raise ValueError("invalid ranges")

    out_of_bounds = []
    for position, item in enumerate(ranges, start=1):
        if not isinstance(item, dict):
            raise ValueError("invalid range")
        start = item.get("start")
        length = item.get("length")
        if not valid_integer(start, 0, 1000000000):
            raise ValueError("invalid start")
        if not valid_integer(length, 1, 1000000000):
            raise ValueError("invalid length")
        if start + length > size:
            out_of_bounds.append(position)

    return {
        "range_count": len(ranges),
        "out_of_bounds": out_of_bounds,
        "within_bounds": not out_of_bounds,
    }


def fail():
    sys.stderr.write("error: invalid input\n")
    sys.exit(2)


def main():
    if len(sys.argv) != 1:
        fail()
    try:
        result = process()
    except Exception:
        fail()

    sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\n")
    return 0


if __name__ == "__main__":
    sys.exit(main())
What to verify after running
  • The supplied example must match the documented JSON output.
  • Error cases must exit 2 with no stdout. Review sensitive successful output before sharing it.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-14.

    Six independent CLI fixtures and 10 curated supplementary checks passed in the pinned offline Python 3.12 container. This does not establish exhaustive correctness, production performance or compatibility with an external provider.