moonbsdiff

    BSDIFF40 binary diff and patch library with bounded resources and a native CLI

    Download zip
    Version
    0.5.0
    License
    BSD-2-Clause
    Last updated
    36 minutes ago
    Downloads
    37

    #MoonBSDiff

    #快速验收

    这个演示用同一组文件比较三种更新方案。可以走一跳时下载 2048 字节完整文件,允许两跳时下载 368 字节补丁,两份补丁已经在本地时下载 0 字节。最后按离线计划交付 restored.bin。

    在仓库根目录运行。需要 Python 3.10+、本仓库的样本和 0.5.0 CLI。可用发行包,也可用配置好的 MoonBit 和原生 C 编译器构建,Windows 使用 MSVC。公开的 v0.4.0 缺少演示使用的命令。

    moon update python scripts/build_cli.py --release

    Windows:

    python scripts/run_update_demo.py --cli _build/bin/windows/moonbsdiff.exe

    Linux:

    python scripts/run_update_demo.py --cli _build/bin/linux/moonbsdiff

    已解包 0.5.0 CLI 时可跳过构建,直接把 --cli 指向解包后的程序。看到 UPDATE DEMO PASS 即表示恢复文件与独立目标逐字节相同。文件保留在脚本打印的临时目录。预期大小、SHA-256 和样本来源见项目验收说明。

    0.5.0 release — update planning, offline recovery and the cross-target manifest package. See the installation guide and release evidence for package, CLI and source identities.

    Historical 0.4.0 release: release scope, distribution identities and remaining limits. Mooncakes 0.4.0 and both Windows/Linux CLI archives are published from source e39e66f1270c0f4e37cb14fcfc5739edc46d1798. See the linked evidence for package, CI and public-asset hashes; Linux local registry consumption remains blocked by connection resets, while Windows registry consumption passed all three targets. The 0.3.0 source work is included in 0.4.0, without a separate 0.3.0 release. Historical 0.1.0 and 0.2.0 package/tag/assets remain unchanged.

    File-based application: explicit native patch --stream now reads, decodes and writes bounded segments before safe no-replace delivery. See the file application design and validation. Version 0.5.0 accepts patch --stream --manifest update.json OLD PATCH OUTPUT. It stages verified input copies on disk and checks the restored hash before publication. Use patch --stream --progress text OLD PATCH OUTPUT (or json) for stderr progress. Ctrl+C requests cooperative cancellation (Windows also Ctrl+Break): confirmed pre-commit cancellation exits 130, with no publication of this call's output. Bytes restored are not overall completion; block internals are not immediately interruptible. See the event and cancellation contract.

    Included 0.3.0 source policies: measured explicit 256 KiB and 1 MiB generation/application configurations are available. Each scale passed sparse/periodic/random native-release cases and a public CLI random replay. The 64 KiB generation default is unchanged; independent work, control, raw-data and patch caps may still reject inputs within a size cap. Those measurements predate the 0.4.0 release; historical CLI 0.2.0 downloads remain unchanged.

    Version 0.4.0 also offers DiffIndex for one old version and multiple targets: build the suffix index once, then generate with fresh per-target budgets. The opaque object retains immutable old bytes and its private index; single-use diff remains unchanged. No speed factor or concurrent use guarantee is claimed. Run moon run examples/index-reuse --target js for the small public-API example.

    Generation preferences now select bzip2 levels 1..9 through DiffOptions, ordinary/indexed option-aware APIs, or diff --compression-level. Default calls remain level 9 and Limits remain resource policy. This option is included in 0.4.0 and absent from historical CLI 0.2.0.

    MoonBSDiff is a MoonBit reference port of BSDiff 4.3 for binary diffs and patches. The current stage implements structured errors, Limits::validate, internal BSDIFF40 integer/envelope parsing, and a private bounded bzip2 adapter. Public diff and apply APIs now generate and restore strict BSDIFF40 patches. See the Windows/Linux CLI download instructions and 0.5.0 publication identities; see CLI build and file contracts. Compression uses moonzip 0.3.5 at level 9; strict bounded decoding uses its attributed, adapted sources under internal/bzip2/.

    The Limits fields for old, new, patch and output buffer sizes are byte counts in 1..2147483647, bounded for Int indexing. max_decompressed_bytes is an aggregate byte count, max_control_instructions counts instructions, and max_sort_work / max_match_work count algorithm-defined work units; each is a positive Int64. Sorting visits accumulate across index rounds; matching/generation visits accumulate across scan, raw encoding, compression-wrapper copies and final assembly; see generation resources. Limits::for_apply() supplies conservative application defaults: old/new/output 1 MiB each, patch 64 KiB, total decompression 2 MiB and 16384 instructions. Sorting/matching fields are unused positive placeholders, not generation defaults; use the separate measured Limits::for_diff() policy for generation. Validation means only that a configuration is legal, not that a complete patch operation has runtime resource protection. The private decoder now enforces per-call and shared decompression budgets. No cross-field relationships are imposed.

    Errors provide a kind, stage, and optional block, offset, field, value and limit. Missing details are None. See the generated interface for exact types.

    The verified local baseline is moon 0.1.20261102 and moonc 0.10.19+bee578715; the PATH default 0.10.13 is older and was not used for final validation. moon.mod declares moonzip 0.3.5; moon tree reports the resolved transitive versions in sources. No version lockfile was generated: .mooncakes/.moon-lock is an empty synchronization file, not a dependency lock. The resolved tree is a snapshot and should be rechecked; the transitive versions are not reproducibly locked by this repository. Version 0.1.0 is published as BigSaltyMan/moonbsdiff; publication evidence distinguishes uploaded source, package and later documentation. The source repository is BigSaltyMan/moonBSDiff.

    From a configured native toolchain, run:

    moon info moon fmt moon fmt --check moon check --target native --deny-warn moon build --target native moon test --target native --deny-warn python scripts/check_format_vectors.py python scripts/check_compression.py python scripts/check_apply.py git diff --check

    The CI workflow runs source checks and compares the generated interface; results must be matched to their checkout SHA. Dependency probe explains historical and repeatable bzip2 tests and their limits. The project tests cover configuration, error data, integer encoding and envelope boundaries; the fixed 31-input interoperability inventory now has actual bidirectional acceptance: native 31 pairs per direction, JS/Wasm-GC 19 each. Generation now enforces cumulative logical quotas and bounded encoder emissions; these are not whole-process CPU or peak-memory guarantees. See compatibility evidence and replay. See compression contracts and verification. See format details. Licenses and upstream.

    Fixed BSDiff 4.3 reference tools and 13 offline upstream fixtures provide the fixed upstream patches used by the apply tests. Run python scripts/generate_reference.py for offline integrity verification. The upstream self-check is separate from the apply results above.

    #Apply in memory

    This example is executed in apply_test.mbt. It uses three complete empty bzip2 streams.

    test "apply-memory-example" {
    let stream = b"BZh9\x17\x72\x45\x38\x50\x90\x00\x00\x00\x00"
    let patch = b"BSDIFF40" +
    b"\x0e\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
    stream +
    stream +
    stream
    let limits : @moonbsdiff.Limits = {
    max_old_bytes: 1024L,
    max_new_bytes: 1024L,
    max_patch_bytes: 1024L,
    max_output_bytes: 1024L,
    max_decompressed_bytes: 4096L,
    max_control_instructions: 128L,
    max_sort_work: 1L,
    max_match_work: 1L,
    }
    assert_eq(@moonbsdiff.apply(b"", patch, limits), Ok(b""))
    }

    BSDIFF40 does not identify the old file. A wrong old file is not guaranteed to cause an error; verify expected old/output hashes externally. See apply behavior and limits. See application-stage acceptance and measurements for default selection, actual tested scales and unmeasured peak memory.

    Use the public default configuration in memory:

    let limits = @moonbsdiff.Limits::for_apply()
    // old_bytes and patch_bytes are supplied by the caller.
    let result = @moonbsdiff.apply(old_bytes, patch_bytes, limits)

    Explicit caller-selected Limits continue to work. The three targets each passed the final 73-test application-stage collection; the independent upstream case count remains 13.

    An internal binary suffix-array index is now implemented using prefix doubling and counting sort, including the empty suffix and unsigned binary-byte ordering. It has no public API; it supports the generator described below; the native CLI is described below. Application defaults are unchanged and must not be used as generation defaults.

    Internal suffix matching and segment planning now provide longest-match queries, offset scoring, forward/backward selection and overlap adjustment. Matching scans reuse the existing suffix index and can produce old-data reuse with nonzero residuals. These components remain private and now feed residual encoding and patch assembly through public diff. The native CLI is described below.

    #Generate and apply in memory

    The following test is executed in diff_test.mbt. These explicit limits are illustrative for this small input, not measured generation defaults. Limits::for_apply() has sorting/matching placeholders and must not be treated as a generation default.

    test "diff-memory-example" {
    let limits : @moonbsdiff.Limits = {
    max_old_bytes: 4096L,
    max_new_bytes: 4096L,
    max_patch_bytes: 8192L,
    max_output_bytes: 4096L,
    max_decompressed_bytes: 16384L,
    max_control_instructions: 256L,
    max_sort_work: 1000000L,
    max_match_work: 1000000L,
    }
    let old = b"MoonBSDiff example version 1"
    let new = b"MoonBSDiff example version 2!"
    let patch = match @moonbsdiff.diff(old, new, limits) {
    Ok(b) => b
    Err(_) => abort("diff failed")
    }
    assert_eq(@moonbsdiff.apply(old, patch, limits), Ok(new))
    }

    Generation behavior and verification describes the initial native generator result and resource boundaries. Bidirectional compatibility now records 31 independent input pairs (13 fixed upstream plus 18 deterministic random-edit pairs), with actual upstream generation -> MoonBSDiff apply and MoonBSDiff diff -> upstream bspatch: native 31 per direction, JS/Wasm-GC 19 per direction. Every executed restoration matched the original new bytes. Run python scripts/run_conformance.py for offline inventory checks, and explicitly add --run for the external matrix with verified reference tools. CI runs offline inventory/comparator checks and a separate real-reference job; consult the matching SHA for current results. BSDIFF40 does not authenticate the old file; verify expected hashes externally.

    #Generation defaults and development status

    Limits::for_diff() supplies old/new/output 64 KiB each, patch 128 KiB, total raw blocks 256 KiB, 4096 controls and 8388608 units each for sorting and matching / generation. Explicit Limits continue to work. Measurement and boundary evidence explains the 16 measured samples, cumulative accounting, fixed Writer workspace, copying and unmeasured peak memory. Independent caps may reject a size-compliant pair. Application defaults are unchanged and may need a larger patch cap to apply incompressible generated patches. The public default entry is exercised in diff_resources_test.mbt:

    let limits = @moonbsdiff.Limits::for_diff()
    let result = @moonbsdiff.diff(old_bytes, new_bytes, limits)

    The repository development plan preserves the source plan dated 2026-11-04 and records the completed 16-stage first-release scope. The native CLI is implemented, and 0.1.0 package audit, publication and independent registry consumption are recorded separately. No tag or GitHub Release was created.

    #Native CLI

    With the pinned MoonBit toolchain, Python 3 and a native C compiler configured (on Windows, use an MSVC developer shell), run from repository root:

    python scripts/build_cli.py

    No Mooncakes installation is required to run the built executable. The build copies it to _build/bin/windows/moonbsdiff.exe or _build/bin/linux/moonbsdiff. Python is a build/test tool, not a runtime dependency of the CLI.

    & .\_build\bin\windows\moonbsdiff.exe --help & .\_build\bin\windows\moonbsdiff.exe --version & .\_build\bin\windows\moonbsdiff.exe diff "old file.bin" "new file.bin" "update.patch" & .\_build\bin\windows\moonbsdiff.exe patch "old file.bin" "update.patch" "restored file.bin"

    ./_build/bin/linux/moonbsdiff diff 'old file.bin' 'new file.bin' 'update.patch' ./_build/bin/linux/moonbsdiff patch 'old file.bin' 'update.patch' 'restored file.bin'

    CLI 0.2.0 additions (absent from published Mooncakes 0.1.0):

    ./_build/bin/linux/moonbsdiff diff --max-old-bytes 256KiB --show-limits ./_build/bin/linux/moonbsdiff patch --show-limits

    Eight explicit byte/count/work caps can override the unchanged defaults. Options precede paths, -- permits leading-hyphen paths, and display mode accepts no files and performs no IO. Byte units are case-sensitive B/KiB/MiB; count/work values have no units. Patch rejects sort/match options. The reader and core use the same validated configuration; raising one cap leaves every other cap intact. See the full CLI option table. This does not expand measured size or memory/CPU guarantees.

    Patch inspection

    ./_build/bin/linux/moonbsdiff inspect testdata/upstream/replace/patch.bin ./_build/bin/linux/moonbsdiff inspect --json --max-patch-bytes 256KiB testdata/upstream/replace/patch.bin

    Use inspect or inspect_header to read the declared size and compressed ranges. Use inspect --deep or the new library inspect_deep(Bytes, Limits) to check stream integrity and control instructions and read the decoded counts. The library API accepts a Bytes buffer on native, JS and Wasm-GC. It is available from this source change onward. Use verify --stream --manifest with the old file and a trusted manifest to confirm the recovered content. See the API example and CLI output schema.

    Optional external manifest (CLI 0.2.0):

    ./_build/bin/linux/moonbsdiff diff --manifest update.json old.bin new.bin update.patch

    The separate SHA-256 manifest binds the exact buffers used by diff and the returned patch, with string byte counts and actual tool metadata. The patch remains BSDIFF40. Outputs are checked for conflicts and delivered patch first, manifest second, without replacement; partial failure keeps the patch and reports manifest incomplete. This is not an atomic pair, a signature or publisher authentication. Expected manifests must come from a trusted channel. Verify and checked restoration are available below. Published 0.1.0 is unchanged.

    Content verification and checked restoration (CLI 0.2.0):

    ./_build/bin/linux/moonbsdiff verify --manifest update.json old.bin update.patch ./_build/bin/linux/moonbsdiff patch --manifest update.json old.bin update.patch restored.bin

    Verify requires a manifest, bounds its read to 16 KiB, rejects malformed schema/ duplicate/unknown keys, checks old/patch identities, actually applies in memory, and checks restored size/hash without writing a final file. Checked patch reuses that pipeline and delivers only after success. Input hashing and apply share the same buffers. Manifest policy defines limits, strict decimal-string sizes, metadata handling and failure stages. Hashes establish supplied-content consistency, not publisher authenticity; trusted expected manifests are still required.

    Generate and verify patch bundles from MoonBit (0.5.0)

    Import BigSaltyMan/moonbsdiff/manifest as @manifest, the root package as @moonbsdiff. The source API works on native, JS and Wasm-GC. The published 0.4.0 package predates this entry point.

    fn publish_update(old : Bytes, new : Bytes) -> Result[@manifest.PatchBundle, @moonbsdiff.BsdiffError] {
    @manifest.diff(old, new, @moonbsdiff.Limits::for_diff())
    }

    fn restore_bundle(old : Bytes, patch : Bytes, trusted_manifest : Bytes) -> Result[Bytes, @manifest.ManifestError] {
    @manifest.apply(old, patch, trusted_manifest, @moonbsdiff.Limits::for_apply())
    }

    Send bundle.patch and bundle.manifest as separate byte buffers. The client passes the patch and the manifest from a trusted channel to restore_bundle. Complete example and error handling

    Choose between patches and a full download (0.5.0)

    When the release offers the full target, use plan_update with a trusted prepared target and candidates. Import the manifest package as shown above.

    fn choose_download(
    installed : Bytes,
    target : @manifest.PreparedManifest,
    candidates : Array[@manifest.PreparedManifest],
    max_steps : Int64,
    ) -> Result[@manifest.UpdatePlan, @manifest.PlanError] {
    @manifest.plan_update(
    @manifest.ContentIdentity::of_bytes(installed),
    target.new,
    candidates,
    max_steps=max_steps,
    )
    }

    moonbsdiff manifest plan --allow-full --max-steps 1 --target-manifest v2-to-v3.json -- installed.bin v1-to-v2.json v2-to-v3.json v1-to-v3.json

    In the fixed example, the one-hop patch costs 2532 bytes, so the command chooses the 2048-byte full file. With --max-steps 2, it chooses two patches totaling 368 bytes. If the strategy is full-file, download the target from the release and verify it during delivery.

    moonbsdiff install-full --target-manifest v2-to-v3.json -- downloaded-v3.bin restored.bin

    Paths containing Chinese characters or spaces must be quoted similarly. Our order is patch OLD PATCH OUTPUT; upstream is bspatch OLD NEW PATCH. Exit codes are 0 success, 2 arguments/configuration, 1 operation failure; errors go to stderr. Existing outputs, including links/aliases of inputs, are refused. A target created during delivery is also preserved. Linux prefers O_TMPFILE+/proc; a guarded local-ext compatibility path is now verified with /proc unavailable. Unsupported filesystems or unsafe parent permissions still fail closed. There is no overwrite option or durability promise. CLI details explain bounded reads, handle-based cleanup, actual platform tests, source/version provenance and filesystem scope.

    Without overrides, generation uses for_diff unchanged. CLI patch keeps for_apply's old/output, decode and instruction caps but raises only its patch cap from 64 KiB to 128 KiB, matching the generator; a real 66279-byte patch roundtrip is tested. The library factories are unchanged. BSDIFF40 does not authenticate the old file or result; verify expected hashes externally. Version output is generated from moon.mod.

    CI coverage and evidence are detailed in compatibility. Linux explicitly checks/builds native, JS and Wasm-GC; test selections retain their full/compact scopes. Windows/Linux native CLI jobs reuse the file contracts. A separate real-reference job builds the locked C tools once and executes the unchanged 31-input bidirectional matrix. scripts/check_acceptance.py rejects zero tests, failed children and stale/incomplete reference evidence. Actual CI results belong to its checkout SHA; historical reports are not current passes. These are source checks, not registry-consumer or release acceptance.

    #Linux compatibility delivery (CLI 0.2.0)

    When anonymous creation is unsupported or /proc references are absent, delivery can use an exclusive 0700 private directory and 0600 file on a guarded local ext filesystem, then anchored non-replacing linkat. Windows is unchanged. Real WSL2 ext4 testing with hidden /proc and ordinary UID 1000 passed manifest generation, checked patch and verify. This does not add general DrvFS/9p, FAT, network-FS, malicious-same-UID/root, or power-loss guarantees. Uncertain temporary identity can leave an explicitly reported object for inspection; no caller output path is deleted as rollback. Design, threat model and evidence explain the strict selection and permission conditions. Published 0.1.0 retains its old requirements; Mooncakes 0.2.0 has not been published.

    #Executable examples

    From this source checkout (registry library installation is shown below):

    moon run cmd/example --target js python scripts/run_examples.py

    The first command runs the pure memory example. The second runs both new examples, builds two repository-owned Wasm-GC versions, uses the official CLI to generate/apply a patch, and checks full bytes and fixed independently compiled hashes. Requires pinned MoonBit, Node, Python 3 and a native C compiler; Windows uses an MSVC developer shell. Every run has a fresh ignored _build/examples/run-<nonce> directory and prints sizes, hashes and EXAMPLES PASS. A failure exits nonzero. Wasm update instructions include CLI reuse and exact flags. These are demonstrations, not a benchmark, registry-consumer result or package release. Small-data patches can be larger.

    #Benchmark and first-release scope

    Five fixed native-release process benchmarks record raw timings, input hashes, patch sizes and a same-input BSDiff 4.3 comparison. These include startup and file IO; core API time and reliable peak memory were not measured. Validate the retained record offline with python scripts/benchmark.py --verify. The 0.1.0 feature scope is frozen; see CHANGELOG and the development plan. Completed package audit, final-source CI, Mooncakes publication and independent consumer results are in the 0.1.0 publication record. No prebuilt CLI download is provided.

    #Release acceptance

    0.1.0 release preparation and exact source/package/CI identity rules are in acceptance. The candidate is audited from git archive, not a mutable working directory. Actual publication and registry installation are recorded in release 0.1.0; candidate use is separately labeled. There is no prebuilt CLI download or GitHub Release in this step.

    #Install the published library

    In an existing MoonBit module using the verified compiler baseline:

    moon add BigSaltyMan/moonbsdiff@0.1.0

    Add "BigSaltyMan/moonbsdiff" to the package's import block, then use the public API shown above. Fresh-cache external Windows consumption passed native, JS and Wasm-GC with full-byte restoration checks. Local Linux registry bootstrap encountered a network failure; Linux source/CLI and three-target candidate checks passed separately in CI. See the release record for exact source/package identities and the distinction from the later docs commit.

    BsdiffError

    pub(all) struct BsdiffError {
    kind : ErrorKind
    stage : ErrorStage
    block : String?
    offset : Int64?
    field : String?
    value : Int64?
    limit : Int64?
    } derive(Eq,
    Debug
    )

    Structured failure. Missing location or limit details are None.

    BsdiffError::equal

    fn BsdiffError::equal(BsdiffError, BsdiffError) -> Bool

    BsdiffError::not_equal

    fn BsdiffError::not_equal(x : BsdiffError, y : BsdiffError) -> Bool

    DeepPatchInfo

    pub struct DeepPatchInfo {
    header : PatchInfo
    control_count : Int64
    diff_bytes : Int64
    extra_bytes : Int64
    expanded_bytes : Int64
    }

    Verified structure and decoded byte counts for a single BSDIFF40 patch.

    DiffIndex

    pub struct DiffIndex {
    // private fields
    }

    Reusable old bytes and suffix positions. Safe Bytes APIs are immutable; neither the suffix array nor mutable budgets are exposed or cached publicly.

    DiffIndex::build

    fn DiffIndex::build(old_bytes : Bytes, limits : Limits) -> Result[DiffIndex, BsdiffError]

    Validate old size and build once with one cumulative sorting quota. Other Limits fields must be valid, but no target/output is generated here.

    DiffIndex::diff

    fn DiffIndex::diff(self : DiffIndex, new_bytes : Bytes, limits : Limits) -> Result[Bytes, BsdiffError]

    Generate with fresh per-target quotas; no sorting occurs or is charged. Revalidate all limits, including bound old size, on every call.

    DiffIndex::diff_with_options

    fn DiffIndex::diff_with_options(self : DiffIndex, new_bytes : Bytes, limits : Limits, options : DiffOptions) -> Result[Bytes, BsdiffError]

    Reuse the index with validated per-target generation preferences.

    DiffOptions

    pub(all) struct DiffOptions {
    compression_level : Int
    }

    Generation preferences, independent of resource Limits. Only bzip2 level is configurable; the default is 9 and all three streams use the same level.

    DiffOptions::default

    fn DiffOptions::default() -> DiffOptions

    DiffOptions::validate

    fn DiffOptions::validate(self : DiffOptions) -> Result[Unit, BsdiffError]

    Reject before sorting or encoding; the dependency's clamping is not policy.

    ErrorKind

    pub(all) enum ErrorKind {
    InvalidConfiguration
    UnsupportedFormat
    TruncatedData
    InvalidField
    IntegerOverflow
    DecompressionFailed
    OutputOutOfBounds
    ResourceLimitExceeded
    } derive(Eq,
    Debug
    )

    ErrorKind::equal

    fn ErrorKind::equal(ErrorKind, ErrorKind) -> Bool

    ErrorKind::not_equal

    fn ErrorKind::not_equal(x : ErrorKind, y : ErrorKind) -> Bool

    ErrorStage

    pub(all) enum ErrorStage {
    Configuration
    Header
    Control
    Diff
    Extra
    Output
    Sorting
    Matching
    } derive(Eq,
    Debug
    )

    ErrorStage::equal

    fn ErrorStage::equal(ErrorStage, ErrorStage) -> Bool

    ErrorStage::not_equal

    fn ErrorStage::not_equal(x : ErrorStage, y : ErrorStage) -> Bool

    Limits

    pub(all) struct Limits {
    max_old_bytes : Int64
    max_new_bytes : Int64
    max_patch_bytes : Int64
    max_output_bytes : Int64
    max_decompressed_bytes : Int64
    max_control_instructions : Int64
    max_sort_work : Int64
    max_match_work : Int64
    } derive(Eq,
    Debug
    )

    Individual buffer byte limits are positive and at most 2147483647 (Int indices). Total decompressed bytes are a positive Int64 aggregate. Counts and work units are positive Int64 values. No zero means unlimited.

    Limits::equal

    fn Limits::equal(Limits, Limits) -> Bool

    Limits::for_apply

    fn Limits::for_apply() -> Limits

    Conservative application defaults; see docs/apply-acceptance.md for measurements. Sorting/matching fields are unused by apply and are not generator defaults.

    Limits::for_diff

    fn Limits::for_diff() -> Limits

    Small in-memory generation policy, measured through 64 KiB inputs. Independent caps can reject otherwise size-compliant inputs. See docs/generation-resources.md; work quotas exclude bzip2's internal CPU work.

    Limits::not_equal

    fn Limits::not_equal(x : Limits, y : Limits) -> Bool

    Limits::to_repr

    Limits::validate

    fn Limits::validate(self : Limits) -> Result[Unit, BsdiffError]

    Validate configuration only; runtime checks belong to the operation adapters.

    PatchInfo

    pub struct PatchInfo {
    patch_bytes : Int64
    new_bytes : Int64
    control_start : Int64
    control_length : Int64
    diff_start : Int64
    diff_length : Int64
    extra_start : Int64
    extra_length : Int64
    }

    Read-only envelope metadata; it makes no claim about compressed/control data.

    apply

    fn apply(old_bytes : Bytes, patch_bytes : Bytes, limits : Limits) -> Result[Bytes, BsdiffError]

    Apply one strict BSDIFF40 patch using explicit resource limits. The caller is responsible for verifying old/output file identities.

    diff

    fn diff(old_bytes : Bytes, new_bytes : Bytes, limits : Limits) -> Result[Bytes, BsdiffError]

    Generate a standard BSDIFF40 patch; every invocation owns fresh budgets.

    diff_with_options

    fn diff_with_options(old_bytes : Bytes, new_bytes : Bytes, limits : Limits, options : DiffOptions) -> Result[Bytes, BsdiffError]

    Generate with validated preferences; quotas remain in Limits.

    inspect_deep

    fn inspect_deep(patch : Bytes, limits : Limits) -> Result[DeepPatchInfo, BsdiffError]

    Check all three compressed streams and their control-directed consumption. Uses explicit limits and bounded decoder pulls, with no old or restored data. Success establishes patch structure; content and file identity need separate checks.

    inspect_header

    fn inspect_header(data : Bytes, max_patch_bytes : Int64) -> Result[PatchInfo, BsdiffError]

    Check BSDIFF40 header/ranges only. The positive Int-indexable patch cap is independent of apply defaults. Never decompresses or allocates restored bytes.

    inspect_header_prefix

    fn inspect_header_prefix(data : Bytes, patch_bytes : Int64, max_patch_bytes : Int64) -> Result[PatchInfo, BsdiffError]

    Envelope check using a header prefix and separately measured file size. Reads only the first 32 bytes; does not allocate or decompress target data.