67 lines
2.0 KiB
Python
67 lines
2.0 KiB
Python
"""Lossless changes between consecutive JSON positions."""
|
|
from copy import deepcopy
|
|
|
|
CHECKPOINT = 64
|
|
|
|
|
|
def changes(old, new, path=()):
|
|
if old == new:
|
|
return
|
|
if isinstance(old, dict) and isinstance(new, dict) and old.keys() == new.keys():
|
|
for key in new:
|
|
yield from changes(old[key], new[key], (*path, key))
|
|
elif isinstance(old, list) and isinstance(new, list):
|
|
if len(old) == len(new) and all(isinstance(v, (list, dict)) for v in old):
|
|
for i, item in enumerate(new):
|
|
yield from changes(old[i], item, (*path, i))
|
|
return
|
|
left = 0
|
|
end = min(len(old), len(new))
|
|
while left < end and old[left] == new[left]:
|
|
left += 1
|
|
right = 0
|
|
while right < end - left and old[-1-right] == new[-1-right]:
|
|
right += 1
|
|
yield [list(path), left, len(old)-right-left, new[left:len(new)-right]]
|
|
else:
|
|
yield [list(path), new]
|
|
|
|
|
|
def apply(state, delta):
|
|
for operation in delta:
|
|
path = operation[0]
|
|
target = state
|
|
if len(operation) == 2:
|
|
for key in path[:-1]:
|
|
target = target[key]
|
|
target[path[-1]] = deepcopy(operation[1])
|
|
else:
|
|
_, offset, count, items = operation
|
|
for key in path:
|
|
target = target[key]
|
|
target[offset:offset+count] = deepcopy(items)
|
|
return state
|
|
|
|
|
|
def compact(events):
|
|
previous = None
|
|
for event in events:
|
|
current = event["state"]
|
|
row = {key:value for key,value in event.items() if key != "state"}
|
|
if previous is None:
|
|
row["state"] = current
|
|
else:
|
|
row["delta"] = list(changes(previous, current))
|
|
yield row
|
|
previous = current
|
|
|
|
|
|
def frames(events):
|
|
state = None
|
|
for event in events:
|
|
if "state" in event:
|
|
state = deepcopy(event["state"])
|
|
else:
|
|
apply(state, event["delta"])
|
|
yield {**{k:v for k,v in event.items() if k != "delta"}, "state":deepcopy(state)}
|