| 86 | |
| 87 | |
| 88 | def compress(chunk: JsonDict) -> JsonDict: |
| 89 | cache: dict[int, JsonDict] = {} |
| 90 | counter = 0 |
| 91 | |
| 92 | def helper(chunk: JsonDict) -> JsonDict: |
| 93 | nonlocal counter |
| 94 | if not isinstance(chunk, dict): |
| 95 | return chunk # type: ignore[unreachable] #TODO: is this actually unreachable, or are our types wrong? |
| 96 | |
| 97 | if len(chunk) <= 2: |
| 98 | return chunk |
| 99 | id = hash(str(chunk)) |
| 100 | |
| 101 | if id in cache: |
| 102 | return cache[id] |
| 103 | else: |
| 104 | cache[id] = {".id": counter} |
| 105 | chunk[".cache_id"] = counter |
| 106 | counter += 1 |
| 107 | |
| 108 | for name in sorted(chunk.keys()): |
| 109 | value = chunk[name] |
| 110 | if isinstance(value, list): |
| 111 | chunk[name] = [helper(child) for child in value] |
| 112 | elif isinstance(value, dict): |
| 113 | chunk[name] = helper(value) |
| 114 | |
| 115 | return chunk |
| 116 | |
| 117 | out = helper(chunk) |
| 118 | return out |
| 119 | |
| 120 | |
| 121 | def decompress(chunk: JsonDict) -> JsonDict: |