Skip to main content

claw_patch/
codec.rs

1use claw_core::types::PatchOp;
2
3use crate::PatchError;
4
5/// A content-aware patch implementation.
6///
7/// Codecs define how to diff, apply, invert, commute, and three-way merge a
8/// specific content family. Implementations should return typed errors instead
9/// of panicking on malformed patch operations or invalid input bytes.
10pub trait Codec: Send + Sync {
11    /// Stable codec identifier stored on patch objects.
12    fn id(&self) -> &str;
13
14    /// Build patch operations that transform `old` bytes into `new` bytes.
15    fn diff(&self, old: &[u8], new: &[u8]) -> Result<Vec<PatchOp>, PatchError>;
16
17    /// Apply patch operations to `base` bytes.
18    fn apply(&self, base: &[u8], ops: &[PatchOp]) -> Result<Vec<u8>, PatchError>;
19
20    /// Return operations that undo the provided operations.
21    fn invert(&self, ops: &[PatchOp]) -> Result<Vec<PatchOp>, PatchError>;
22
23    /// Reorder non-conflicting operations so left and right can be applied in either order.
24    fn commute(
25        &self,
26        left: &[PatchOp],
27        right: &[PatchOp],
28    ) -> Result<(Vec<PatchOp>, Vec<PatchOp>), PatchError>;
29
30    /// Merge independently edited byte streams against a common base.
31    fn merge3(&self, base: &[u8], left: &[u8], right: &[u8]) -> Result<Vec<u8>, PatchError>;
32}