CodeSampleX

サンプル

flatbuffers 25.12.19: serialize and deserialize schemaless binary data using flatbuffers.flexbuffers

検証済みサンプル — pypi flatbuffers 25.12.19: serialize and deserialize schemaless binary data using flatbuffers.flexbuffers. python 3.12 · linux alpine/x64 · docker…

sha256:8ce22f6a1804ffe1bf53b5addb814dff919ba210773a0079a8d41e069f6faea2

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python uv

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

ケース

HOW
ゴール
serialize and deserialize schemaless binary data using flatbuffers.flexbuffers
パッケージ
シンボル
  • flatbuffers.flexbuffers
環境
python 3.12
作成日
2026-08-28T03:40:58Z

コントラクト

  1. flexbuffers.Dumps and flexbuffers.Loads perform round-trip serialization of nested dictionaries, lists, primitives, blobs, and None
  2. flexbuffers.GetRoot provides zero-copy schema-less reference access to root map with typed field inspection
  3. flexbuffers.Builder with Map context manager serializes keyed scalars, strings, blobs, and booleans
  4. flexbuffers.Builder with Vector and TypedVector context managers serializes heterogeneous and homogeneous element arrays
  5. flexbuffers.Builder element helpers VectorFromElements and TypedVectorFromElements serialize Python lists into vectors
  6. flexbuffers.Ref supports in-place binary mutation of integers, floats, booleans, and fixed-length strings via Mutate methods
  7. flexbuffers.Map raises KeyError when accessing a non-existent key
  8. flexbuffers.Builder.Clear resets builder internal state enabling buffer reuse

ファイル

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • test/contract.py
  • uv.lock

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: serialize and deserialize schemaless binary data using flatbuffers.flexbuffers
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/flatbuffers@25.12.19
Demonstrate these symbols/APIs:
  - flatbuffers.flexbuffers

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ac025f0b7956546b51d63a84a2cec2931f91018fac0ffe1e4347a423d077bd3c","contract":["flexbuffers.Dumps and flexbuffers.Loads perform round-trip serialization of nested dictionaries, lists, primitives, blobs, and None","flexbuffers.GetRoot provides zero-copy schema-less reference access to root map with typed field inspection","flexbuffers.Builder with Map context manager serializes keyed scalars, strings, blobs, and booleans","flexbuffers.Builder with Vector and TypedVector context managers serializes heterogeneous and homogeneous element arrays","flexbuffers.Builder element helpers VectorFromElements and TypedVectorFromElements serialize Python lists into vectors","flexbuffers.Ref supports in-place binary mutation of integers, floats, booleans, and fixed-length strings via Mutate methods","flexbuffers.Map raises KeyError when accessing a non-existent key","flexbuffers.Builder.Clear resets builder internal state enabling buffer reuse"],"goal":"serialize and deserialize schemaless binary data using flatbuffers.flexbuffers","kind":"HOW","packages":["pkg:pypi/flatbuffers@25.12.19"],"schemaVersion":1,"symbols":["flatbuffers.flexbuffers"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"uv","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/flatbuffers@25.12.19"],"schemaVersion":1,"subject":"pkg:pypi/flatbuffers@25.12.19","symbols":["flatbuffers.flexbuffers"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "sample-flatbuffers"
version = "0.1.0"
requires-python = ">=3.8"
dependencies = [
    "flatbuffers==25.12.19",
]
requirements.txt
flatbuffers==25.12.19
spec.json
{
  "schemaVersion": 1,
  "goal": "serialize and deserialize schemaless binary data using flatbuffers.flexbuffers",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/flatbuffers@25.12.19"
  ],
  "symbols": [
    "flatbuffers.flexbuffers"
  ]
}
test/contract.py
import flatbuffers
from flatbuffers import flexbuffers


def test_dumps_and_loads_nested():
    data = {
        "title": "CodeSampleX",
        "count": 42,
        "ratio": 3.14159,
        "is_active": True,
        "tags": ["zero", "copy", "schema-less"],
        "payload": b"\xca\xfe\xba\xbe",
        "nested": {"nested_key": "nested_value", "nested_int": 999},
        "none_val": None,
    }
    buf = flexbuffers.Dumps(data)
    assert isinstance(buf, (bytes, bytearray)), "Dumps must return bytes or bytearray"
    loaded = flexbuffers.Loads(buf)
    assert loaded["title"] == "CodeSampleX", f"Mismatched title: {loaded['title']}"
    assert loaded["count"] == 42, f"Mismatched count: {loaded['count']}"
    assert abs(loaded["ratio"] - 3.14159) < 1e-5, f"Mismatched ratio: {loaded['ratio']}"
    assert loaded["is_active"] is True, f"Mismatched is_active: {loaded['is_active']}"
    assert loaded["tags"] == ["zero", "copy", "schema-less"], f"Mismatched tags: {loaded['tags']}"
    assert loaded["payload"] == bytearray(b"\xca\xfe\xba\xbe"), f"Mismatched payload: {loaded['payload']}"
    assert loaded["nested"] == {"nested_key": "nested_value", "nested_int": 999}, f"Mismatched nested: {loaded['nested']}"
    assert loaded["none_val"] is None, f"Mismatched none_val: {loaded['none_val']}"


def test_get_root_and_type_inspection():
    data = {
        "metric": 100,
        "rate": 0.5,
        "flag": True,
        "label": "perf",
        "bytes": b"\x01\x02",
    }
    buf = flexbuffers.Dumps(data)
    root = flexbuffers.GetRoot(buf)
    assert root.IsMap, "Expected root to be Map"
    m = root.AsMap
    assert len(m) == 5, f"Expected 5 keys in map, got {len(m)}"
    assert m["metric"].IsInt and m["metric"].AsInt == 100
    assert m["rate"].IsFloat and abs(m["rate"].AsFloat - 0.5) < 1e-5
    assert m["flag"].IsBool and m["flag"].AsBool is True
    assert m["label"].IsString and m["label"].AsString == "perf"
    assert m["bytes"].IsBlob and m["bytes"].AsBlob == bytearray(b"\x01\x02")


def test_builder_map_context_manager():
    b = flexbuffers.Builder()
    with b.Map():
        b.Int("user_id", 1001)
        b.Float("score", 98.5)
        b.String("username", "developer")
        b.Bool("verified", True)
        b.Blob("avatar", b"\xff\xd8\xff\xe0")
    buf = b.Finish()
    root = flexbuffers.GetRoot(buf).AsMap
    assert root["user_id"].AsInt == 1001
    assert abs(root["score"].AsFloat - 98.5) < 1e-5
    assert root["username"].AsString == "developer"
    assert root["verified"].AsBool is True
    assert root["avatar"].AsBlob == bytearray(b"\xff\xd8\xff\xe0")


def test_builder_vector_and_typed_vector():
    b = flexbuffers.Builder()
    with b.Map():
        with b.Vector("mixed_vec"):
            b.Int(10)
            b.String("twenty")
            b.Bool(True)
        with b.TypedVector("typed_ints"):
            b.Int(100)
            b.Int(200)
            b.Int(300)
    buf = b.Finish()
    root = flexbuffers.GetRoot(buf).AsMap
    vec = root["mixed_vec"].AsVector
    assert len(vec) == 3, f"Expected 3 elements in mixed_vec, got {len(vec)}"
    assert vec[0].AsInt == 10
    assert vec[1].AsString == "twenty"
    assert vec[2].AsBool is True

    tvec = root["typed_ints"].AsTypedVector
    assert len(tvec) == 3, f"Expected 3 elements in typed_ints, got {len(tvec)}"
    assert [tvec[i].AsInt for i in range(len(tvec))] == [100, 200, 300]


def test_builder_elements_helpers():
    b = flexbuffers.Builder()
    with b.Map():
        b.VectorFromElements("elements_vec", [1, "two", 3.0])
        b.TypedVectorFromElements("elements_typed_vec", [10, 20, 30, 40])
    buf = b.Finish()
    root = flexbuffers.GetRoot(buf).AsMap
    assert root["elements_vec"].IsVector
    assert len(root["elements_vec"].AsVector) == 3
    assert root["elements_typed_vec"].IsTypedVector
    assert [x.AsInt for x in root["elements_typed_vec"].AsTypedVector] == [10, 20, 30, 40]


def test_in_place_mutation():
    b = flexbuffers.Builder()
    with b.Map():
        b.Int("num", 100)
        b.Float("val", 1.25)
        b.Bool("state", False)
        b.String("text", "initial")
    buf = bytearray(b.Finish())
    m = flexbuffers.GetRoot(buf).AsMap
    assert m["num"].MutateInt(200), "MutateInt failed"
    assert m["num"].AsInt == 200, f"Expected 200, got {m['num'].AsInt}"
    assert m["val"].MutateFloat(3.75), "MutateFloat failed"
    assert abs(m["val"].AsFloat - 3.75) < 1e-5, f"Expected 3.75, got {m['val'].AsFloat}"
    assert m["state"].MutateBool(True), "MutateBool failed"
    assert m["state"].AsBool is True, "Expected True"
    assert m["text"].MutateString("updated"), "MutateString failed"
    assert m["text"].AsString == "updated", f"Expected updated, got {m['text'].AsString}"
    # MutateString fails when new value exceeds allocated length
    assert not m["text"].MutateString("too long string that exceeds capacity")


def test_map_nonexistent_key_error():
    b = flexbuffers.Builder()
    with b.Map():
        b.Int("existing", 1)
    buf = b.Finish()
    m = flexbuffers.GetRoot(buf).AsMap
    try:
        _ = m["missing_key"]
        assert False, "Accessing non-existent key should raise KeyError"
    except KeyError:
        pass


def test_builder_clear_and_reuse():
    b = flexbuffers.Builder()
    with b.Map():
        b.Int("first", 1)
    buf1 = b.Finish()
    assert len(buf1) > 0, "Buffer should not be empty"
    b.Clear()
    with b.Map():
        b.String("second", "reused")
    buf2 = b.Finish()
    root2 = flexbuffers.GetRoot(buf2).AsMap
    assert root2["second"].AsString == "reused", f"Expected reused, got {root2['second'].AsString}"


if __name__ == "__main__":
    test_dumps_and_loads_nested()
    test_get_root_and_type_inspection()
    test_builder_map_context_manager()
    test_builder_vector_and_typed_vector()
    test_builder_elements_helpers()
    test_in_place_mutation()
    test_map_nonexistent_key_error()
    test_builder_clear_and_reuse()
    print("All contract assertions passed successfully.")
uv.lock
version = 1
revision = 3
requires-python = ">=3.8"

[[package]]
name = "flatbuffers"
version = "25.12.19"
source = { registry = "https://pypi.org/simple" }
wheels = [
    { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" },
]

[[package]]
name = "sample-flatbuffers"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
    { name = "flatbuffers" },
]

[package.metadata]
requires-dist = [{ name = "flatbuffers", specifier = "==25.12.19" }]

オリジンシーダー

匿名