Options
All
  • Public
  • Public/Protected
  • All
Menu

Class DeltaVisitor

Incrementally parse the binary delta to calculate a structural delta.

The result reports all differences, but is not necessarily minimal. In particular there are occasional 'false positive' REMOVE/INSERT pairs.

The Algorithm

We re-constitute the match and insert visitor callbacks into a sequence of delete, insert, and match edits. The binary delta format guarantees there will not be consecutive callbacks of the same type, and that match callbacks are presented in order with no overlaps. Delete and match edits will be contiguous with no gap between the end of one edit and the start of the next.

The processing uses two SpanParsers, one for the old token stream and one for the new token streams. We move forward along each parser driven by the binary delta edits, skipping old values covered by a match, adding a REMOVE change for each old value covered by a delete, and adding an INSERT change for each new value covered by an insert.

The SpanParsers calculate the appropriate JSON pointers to return for a span. A span finishes at the end of the first token found after the target offset, with these exceptions:

If a split is found in a field name, the span continues until the

first pointer is found in the value, potentially consuming one or more structure start tokens. The reporting of a change that affects a field does not distinguish between the field name and its value, except if the value is a structure and the change only affects part of the structure.

End structure tokens are eagerly consumed. This has two benefits.

First, it collapses empty structures to the appropriate parent pointer. Second, the closing tokens of non-empty structures are associated with the last pointer, which simplifies boundary detection.

The implementation relies on the SpanParser not consuming start structure tokens eagerly at a split unless instructed to do so (see SpanParser.spanToNext). This provides a tighter alignment between the detected binary differences and the token parsers, allowing a simpler pairing of tokens between the two streams. I'm not certain there aren't additional edge cases introduced by the eager consumption of structure tokens for field names.

The two token streams are treated symmetrically. Each SpanParser is only moved in a forward direction; there is no backtracking. We maintain the current byte position in each binary value as DeltaVisitor.oldOffset and DeltaVisitor.newOffset. After each edit is processed, oldParser.nextByte() >= oldOffset and newParser.nextByte() >= newOffset.

The fun happens at the edges, specifically where a token covers one or more binary edits. We call such a misaligned edge a 'split'.

Splits

The appropriate processing of a split depends on the type of edit in which it is found. For all edit types, we detect and process trailing edge splits; i.e. splits detected at the end of a span because the end of the last parsed token is after the end edge. It turns out we must also consider leading edge splits for match edits.

insert edits

We insert everything in the span. If a trailing edge split is detected, we do one of two things.

  • If the old stream parser is at a split, there is nothing to do. The split will have been considered and processed for an earlier edit.
  • If the old stream parser is at oldOffset (i.e. is not at a split token), we consume and add a REMOVE change for the next pointer in the old stream. The old stream is otherwise unaffected by the insert edit, so oldOffset is the start of the next delete or match edit. Consuming the token might move it further into other delete or match edits. In all cases, correct handling of the insert split requires adding a REMOVE change for the first pointer found.

Further split detection is required to detect differences that only affect the CBOR structure. If the parser structure depth is different at the end of the span than it was at start, the last token is treated in the same manner as a trailing edge split. Otherwise comparing 'b' with ['a', 'b', 'c'] incorrectly generates INSERT /0,INSERT /2 rather than INSERT /0,REMOVE /1,INSERT /1,INSERT /2.

delete edits

The processing of splits for delete edits is the inverse of that for insert edits. (Swap INSERT and REMOVE, old stream and new stream).

match edits

When processing match edits we move both parsers. Either or both can have a trailing edge split. If both are split, the corresponding pointers are used for the REMOVE/INSERT pair. If neither are split, or if only one is split, we do nothing. As far as I can tell, there can only be a single split if the match ends with a start structure token ({ or [), so differences in the structure content will be detected by later edits.

I haven't fully convinced myself that it is correct to do nothing in all single split cases, but it appears to work. I've experimented with a variant where a single split matches the next pointer eagerly consumed from the opposite stream, similar to the approach taken for insert/delete. This produces less satisfactory matching between structures. E.g. for [] with ['a' 'b'] it produces REMOVE /0,INSERT /0/0,INSERT/0/1 where the current implementation produces INSERT/0/0,INSERT/0/1. It may be worth revisiting this in conjunction with the post-processing fix to collapse complete spans into the parent.

Consideration of parser depth is unnecessary for match trailing edge splits. A difference in structure depth must correspond to a binary difference covering structure delimiters, which will be handled by insert or delete processing.

There is a further complication to deal with for matches. A token in one stream can match the end and start of two tokens in the other stream. We deal with that by checking for a leading edge split. If the new stream parser is at the expected offset, and the old stream parser isn't, we've found a token spanning across two matches in the old stream. The previous insert edit will have inserted the first pointer for the new stream. We add the next found in the new stream in the match span (if any). Similar processing is performed if the old stream parser is at the expected offset, but the new stream parser is not.

Heuristic clean up

The basic approach of using the binary delta to identify splits and matching the splits to the appropriate tokens produces a reasonable but imperfect result. Further processing is performed to improve the output.

False positives (redundant REMOVE/INSERT pairs) occur reasonably frequently in the raw results. These are identified and removed by comparing each potential REMOVE with the previous INSERT, and each potential INSERT with the previous REMOVE. If the associated values are equal, and the pointers are compatible, both changes are dropped.

The raw results might contain pointers to the entire contents of a structure. These are replaced with a single pointer to the structure.

Hierarchy

  • DeltaVisitor

Index

Constructors

constructor

  • Construct a DeltaVisitor

    Parameters

    • oldValue: BufferSlice

      the old value

    • newValue: BufferSlice

      the new value

    • inserted: JSONPointerMap

      the parts of the second JSON value not found in the first JSON value. This map should be empty. It will be filled by the DeltaVisitor.

    • removed: JSONPointerMap

      the parts of the first JSON value not found in the second JSON value. This map should be empty. It will be filled by the DeltaVisitor.

    • partOf: (value: any, start: number, length: number) => JSON

      a function to return a JSON object from a part of a BufferSlice.

        • (value: any, start: number, length: number): JSON
        • Parameters

          • value: any
          • start: number
          • length: number

          Returns JSON

    • copyPartOf: (value: any, start: number, length: number) => JSON

      a function to return a JSON object from a copy of part of a BufferSlice.

        • (value: any, start: number, length: number): JSON
        • Parameters

          • value: any
          • start: number
          • length: number

          Returns JSON

    Returns DeltaVisitor

Properties

Private copyPartOf

copyPartOf: (value: any, start: number, length: number) => JSON

Return a JSON object from a part of a BufferSlice. The buffer is copied before being passed to the JSON constructor.

param

the buffer slice to construct the JSON from

param

the offset in the buffer slice

param

the number of bytes to use from the buffer slice

returns

a JSON object constructed from the part of the buffer slice

Type declaration

    • (value: any, start: number, length: number): JSON
    • Parameters

      • value: any
      • start: number
      • length: number

      Returns JSON

Private inserted

inserted: JSONPointerMap

The parts of the second JSON value not found in the first JSON value.

Private Readonly insertedSplitStructures

insertedSplitStructures: JSONPointerMap = new JSONPointerMap()

The split structures that are part of the new JSON value not found in the old JSON value

Private newOffset

newOffset: number = 0

The newParser position where the next match or insert will start, which is the cumulative length of the match and insert edits. May be less than or greater than oldOffset. After each edit is processed, newParser.nextByte() >= newOffset.

Private Readonly newParser

newParser: SpanParser

The span parser traversing the new value

Private Readonly newValue

newValue: BufferSlice

The new value

Private oldOffset

oldOffset: number = 0

The end of the last match edit. After each edit is processed, oldParser.nextByte() >= oldOffset.

Private Readonly oldParser

oldParser: SpanParser

The span parser traversing the old value

Private Readonly oldValue

oldValue: BufferSlice

The old value

Private partOf

partOf: (value: any, start: number, length: number) => JSON

Return a JSON object from a part of a BufferSlice.

param

the buffer slice to construct the JSON from

param

the offset in the buffer slice

param

the number of bytes to use from the buffer slice

returns

a JSON object constructed from the part of the buffer slice

Type declaration

    • (value: any, start: number, length: number): JSON
    • Parameters

      • value: any
      • start: number
      • length: number

      Returns JSON

Private pendingInsert

pendingInsert: JSONPointer | null = null

A JSON pointer that is part of the new value but hasn't yet been found in the old value.

Private pendingInsertValue

pendingInsertValue: any

The value associated with the pendingInsert pointer.

Private pendingRemove

pendingRemove: JSONPointer | null = null

A JSON pointer that is part of the old value but hasn't yet been found in the new value.

Private pendingRemoveValue

pendingRemoveValue: any

The value associated with the pendingRemove pointer.

Private removed

The parts of the first JSON value not found in the second JSON value.

Private Readonly removedSplitStructures

removedSplitStructures: JSONPointerMap = new JSONPointerMap()

The split structures that are part of the old JSON value not found in the new JSON value

Methods

addInsert

  • addInsert(nextPointer: JSONPointer | null, nextValue?: any): void
  • Add an JSON pointer that is pending an insert. Any previous pending insert is confirmed and placed into the inserted map.

    Parameters

    • nextPointer: JSONPointer | null

      the next pointer pending an insert

    • Optional nextValue: any

      the data associated with the insert

    Returns void

addRemove

  • addRemove(nextPointer: JSONPointer | null, nextValue: any): void
  • Add an JSON pointer that is pending a remove. Any previous pending remove is confirmed and placed into the removed map.

    Parameters

    • nextPointer: JSONPointer | null

      the next pointer pending a remove

    • nextValue: any

      the data associated with the remove

    Returns void

Private checkInvariants

  • checkInvariants(): void
  • Check if an invalid state has occurred

    throws

    an InvalidDataError if either buffer contains invalid binary data

    Returns void

end

  • end(): void
  • Called by the BinaryDelta when the end of the buffer has been found.

    throws

    an InvalidDataError if either buffer contains invalid binary data

    Returns void

Private handleDelete

  • handleDelete(start: number, length: number): void
  • Handle deleted binary data

    throws

    an InvalidDataError if either buffer contains invalid binary data

    Parameters

    • start: number

      the starting position of the deleted data in the old buffer

    • length: number

      the number of deleted bytes

    Returns void

Private handleMatch

  • handleMatch(start: number, length: number): void
  • Handle a match of binary data

    throws

    an InvalidDataError if either buffer contains invalid binary data

    Parameters

    • start: number

      the starting position in the old buffer

    • length: number

      the number of matching bytes

    Returns void

insert

  • insert(bytes: Uint8Array): boolean
  • Called by the BinaryDelta when a inserted binary data has been found.

    Parameters

    • bytes: Uint8Array

      the inserted data

    Returns boolean

    true

match

  • match(start: number, length: number): boolean
  • Called by the BinaryDelta when a match of binary data has been found.

    throws

    an InvalidDataError if either buffer contains invalid binary data

    Parameters

    • start: number

      the starting position in the old buffer

    • length: number

      the number of matching bytes

    Returns boolean

    true

noChange

  • noChange(): void
  • No change

    Returns void

Private replaceFullInsertedStructures

  • replaceFullInsertedStructures(): void
  • Heuristic post-processing: replace split structures for which inserted includes every entry with a single pointer.

    Returns void

Private replaceFullRemovedStructures

  • replaceFullRemovedStructures(): void
  • Heuristic post-processing: replace split structures for which removed includes every entry with a single pointer.

    Returns void

Object literals

Private inserter

inserter: object

A consumer for the span parser that inserts values

accept

  • accept(pointer: JSONPointer, start: number, length: number): void
  • Accept a JSON pointer found in the new value

    Parameters

    • pointer: JSONPointer

      the JSON pointer of the inserted value

    • start: number

      the starting position in the newValue buffer

    • length: number

      the number of bytes in the newValue buffer

    Returns void

splitStructureEnd

  • splitStructureEnd(pointer: JSONPointer, count: number, start: number, length: number): void
  • Signal the end of a split structure

    Parameters

    • pointer: JSONPointer

      the JSON pointer of the inserted value

    • count: number

      the number of tokens in the split structure

    • start: number

      the starting position in the newValue buffer

    • length: number

      the number of bytes in the newValue buffer

    Returns void

Private remover

remover: object

A consumer for the span parser that removes values

accept

  • accept(pointer: JSONPointer, start: number, length: number): void
  • Accept a JSON pointer found in the old value

    Parameters

    • pointer: JSONPointer

      the JSON pointer of the removed value

    • start: number

      the starting position in the oldValue buffer

    • length: number

      the number of bytes in the oldValue buffer

    Returns void

splitStructureEnd

  • splitStructureEnd(pointer: JSONPointer, count: number, start: number, length: number): void
  • Signal the end of a split structure

    Parameters

    • pointer: JSONPointer

      the JSON pointer of the inserted value

    • count: number

      the number of tokens in the split structure

    • start: number

      the starting position in the newValue buffer

    • length: number

      the number of bytes in the newValue buffer

    Returns void

Copyright © 2025 DiffusionData Ltd. All Rights Reserved.