Skip to main content

Crate palim

Crate palim 

Source
Expand description

§Palim: reversible JSON changes for Rust

crates.io API documentation CI License: MIT

Palim tracks list moves and edits by stable IDs and saves reversible JSON changes for undo/redo or replay. It also generates RFC 6902 JSON Patch for other clients, reads and writes jsondiffpatch deltas, and compares configurations.

§Installation

Requires Rust 1.85 or newer:

cargo add palim serde_json

In Cargo.toml, use palim = "0.3" and serde_json = "1.0". Numbers use serde_json’s ordinary behavior by default. For arbitrary-precision integers/decimals and precise float wire round trips, opt in:

palim = { version = "0.3", features = ["exact-numbers"] }

This enables serde_json’s arbitrary_precision and float_roundtrip features for the shared dependency, affecting Value equality and float parsing elsewhere in your project. Enable it to retain Palim 0.2’s numeric capabilities. Without it, ordinary parsing can round or reject numbers before Palim sees them.

§Match a list by ID, then undo the change

use palim::{DiffPatcher, patch, unpatch};
use serde_json::json;
let engine = DiffPatcher::by_key("id");
let before = json!([{ "id": 1, "score": 10 }, { "id": 2, "score": 20 }]);
let after = json!([{ "id": 2, "score": 21 }, { "id": 1, "score": 10 }]);
let delta = engine.diff(&before, &after)?.ok_or("expected a change")?;
assert_eq!(patch(&before, &delta)?, after);
assert_eq!(unpatch(&after, &delta)?, before);

diff returns None when nothing changes. Serialize a complete Delta with serde_json to save it for later replay. Apply it to the correct baseline; Palim does not resolve concurrent edits. Missing IDs fall back to the complete item value, and repeated IDs are paired deterministically.

§Choose an API

I want to…UseWhat it produces
Save history or implement undo/redodiff or DiffPatcher::by_key("id").diff, then patch / unpatchNative Delta, including old values
Send a standard patch to a frontend or third partydiff_json_patch or Delta::to_json_patch, then apply_json_patchRFC 6902 Patch operations
Undo a standard patchinvert_json_patch, with the original baselineAn inverse RFC 6902 Patch
See which paths changedcompareCompareReport; a report, not a patch
Use JSON Merge Patchdiff_merge_patch / merge_patchRFC 7396 JSON; object-member null means deletion
Read a JS jsondiffpatch changeDeserialize a forward delta as Delta, then patch / unpatchNative interoperable delta

Delta and Patch are different formats. Native deltas retain values for undo; standard patches interoperate with RFC 6902 clients and need the baseline for inversion. For a full API inventory and details on filters, fuzzy text, limits and atomic application, read the API guide or function documentation.

§When to choose Palim

Your needA useful starting point
Undo/redo, replay, or jsondiffpatch-compatible deltasPalim’s reversible Delta
Large arrays with stable IDs, reorders and edits inside moved itemsPalim’s identity matching and move output
Standard patches with move/copy optimization, guards or inversionPalim’s RFC APIs
Ordinary positional RFC patches without those capabilitiesjson-patch offers a simpler API
Small configurations in an existing JavaScript applicationCompare the JS libraries in your own workload

Performance depends on the workload and output format. Dated measurements show Palim’s advantages on large reorders and reversible deltas, with slower cases on random shuffles and wide additions. These historical runs do not measure the ordinary-number default introduced in 0.3. See the benchmarks and measurement boundaries and library comparison.

§Runnable examples

ExampleDemonstrates
id_list_historyID-based list moves, edits, saved deltas, undo and redo
rfc_patch_transportSerialize RFC 6902 operations, apply them and generate an inverse
config_reportCompare configuration paths and print a report
jsondiffpatch_interopImport a forward JS delta and use Rust to apply and undo it
cargo run --example id_list_history --locked
cargo run --example rfc_patch_transport --locked
cargo run --example config_report --locked
cargo run --example jsondiffpatch_interop --locked

§More information

MIT for this implementation. Dependencies retain their respective licenses. Upstream-derived test fixtures are Apache-2.0; see tests/fixtures/NOTICE.md.

Structs§

ArrayMove
An identity-matched item whose source and target indices differ.
CompareOptions
Options for a comparison report, separate from reversible delta generation.
CompareReport
JSON comparison output. It is not an applicable or reversible patch.
Delta
A complete reversible delta, serialized using jsondiffpatch’s JSON protocol.
DiffOptions
Instance-local matching options.
DiffPatcher
A reusable, shareable diff instance without global configuration.
Difference
A changed, added or removed value. None denotes absence, not JSON null.
Error
A patch or diff failure, with a JSON Pointer identifying the affected value.
ForwardDelta
A delta with omitted old values. Its wire representation has no reversible marker; deserialize it as this type, never as Delta. It intentionally has no reverse method.
JsonPatchApplyOptions
Resource limits for standard patch application.
JsonPatchOptions
Options for producing RFC 6902 patches.
Patch
Representation of JSON Patch (list of patch operations)
TextPatchOptions
Bounds for opt-in approximate text application. Distances use UTF-16 units.

Enums§

PatchOperation
JSON Patch single patch operation

Functions§

apply_json_patch
Apply all six RFC 6902 operations without changing the source.
apply_json_patch_in_place
Update the caller’s document only after every operation succeeds.
apply_json_patch_owned
Consume the baseline, avoiding the initial whole-document clone.
apply_json_patch_with_options
Apply with copy and nesting limits; failures return no partial document.
apply_text_patch
Apply a DMP text patch with bounded approximate matching.
compare
Compare JSON with mathematical number equality by default (1 equals 1.0). Inputs remain unchanged. Exhausted budgets return an error, never partial output.
compose_merge_patches
Compose two RFC 7396 merge patches for every possible source document.
diff
Compare using default options. Unkeyed objects in arrays are matched by position.
diff_json_patch
Compare documents and return a standard JSON Patch.
diff_merge_patch
Generate an RFC 7396 merge patch transforming left into right.
invert_json_patch
Produce an inverse from the original operations and their complete baseline. Tests make no changes and therefore produce no inverse operation. A move may need remove/add/replace operations to restore a destination it overwrote.
invert_json_patch_guarded
Generate an inverse with tests for the values and containers it will touch. Guards are computed from the successfully patched baseline. They do not authenticate unrelated document fields, and container tests can be large.
merge_patch
Apply an RFC 7396 JSON Merge Patch without changing the source.
merge_patch_in_place
Apply an RFC 7396 merge patch atomically to a mutable source.
patch
Apply a complete delta with strict old-value, type, index and text context checks.
patch_fuzzy
Apply native deltas with approximate text matching; non-text changes stay strict.
patch_in_place
Atomically update a baseline after successful native application.
patch_owned
Consume a baseline instead of borrowing it.
reverse
Generate the inverse solely from the original delta; no re-diff is performed.
test_json_patch
Check a sequence of RFC 6902 test operations without cloning the document. Other operations are rejected in sequence. Source and expected values retain the standard 128-container depth limit and mathematical number equality.
unpatch
Restore a source document by applying the inverse delta to right.

Type Aliases§

ArrayItemMatcher
Pair array elements using caller-defined identity or similarity.
CompareNodeFilter
Return false to exclude a node, including root, array items and absent values.
CustomEqual
Return Some to decide equality of a node, or None to use normal comparison.
NodeFilter
Select any JSON node, including roots, missing values and array positions.
ObjectHash
Return an identity for an object/array item. Called once per item in each changed array.
PropertyFilter
Return false to exclude an object property from comparison.
UnorderedArrays
Select array paths whose order is immaterial. Repeated values retain their counts.