ycpp 0.1.0__cp315-cp315t-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. ycpp/__init__.py +110 -0
  2. ycpp/_array.py +318 -0
  3. ycpp/_awareness.py +268 -0
  4. ycpp/_doc.py +718 -0
  5. ycpp/_event.py +188 -0
  6. ycpp/_id_map.py +620 -0
  7. ycpp/_map.py +267 -0
  8. ycpp/_provider.py +180 -0
  9. ycpp/_snapshot.py +28 -0
  10. ycpp/_sticky_index.py +59 -0
  11. ycpp/_stream.py +91 -0
  12. ycpp/_sync.py +192 -0
  13. ycpp/_text.py +239 -0
  14. ycpp/_transaction.py +287 -0
  15. ycpp/_typed.py +122 -0
  16. ycpp/_undo.py +201 -0
  17. ycpp/_update.py +18 -0
  18. ycpp/_xml.py +452 -0
  19. ycpp/_ycpp.cp315t-win_arm64.lib +0 -0
  20. ycpp/_ycpp.cp315t-win_arm64.pyd +0 -0
  21. ycpp-0.1.0.data/headers/fast_float/ascii_number.h +766 -0
  22. ycpp-0.1.0.data/headers/fast_float/bigint.h +638 -0
  23. ycpp-0.1.0.data/headers/fast_float/constexpr_feature_detect.h +53 -0
  24. ycpp-0.1.0.data/headers/fast_float/decimal_to_binary.h +212 -0
  25. ycpp-0.1.0.data/headers/fast_float/digit_comparison.h +455 -0
  26. ycpp-0.1.0.data/headers/fast_float/fast_float.h +91 -0
  27. ycpp-0.1.0.data/headers/fast_float/fast_table.h +708 -0
  28. ycpp-0.1.0.data/headers/fast_float/float_common.h +1432 -0
  29. ycpp-0.1.0.data/headers/fast_float/parse_number.h +488 -0
  30. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_arithmetic.hpp +267 -0
  31. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_bit.hpp +230 -0
  32. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_cast.hpp +43 -0
  33. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_complex.hpp +112 -0
  34. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_details.hpp +386 -0
  35. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_logical.hpp +240 -0
  36. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_math.hpp +2601 -0
  37. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_memory.hpp +1006 -0
  38. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_rounding.hpp +72 -0
  39. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_swizzle.hpp +260 -0
  40. ycpp-0.1.0.data/headers/xsimd/arch/common/xsimd_common_trigo.hpp +996 -0
  41. ycpp-0.1.0.data/headers/xsimd/arch/utils/shifts.hpp +82 -0
  42. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx.hpp +2111 -0
  43. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx2.hpp +1591 -0
  44. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512bw.hpp +724 -0
  45. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512cd.hpp +28 -0
  46. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512dq.hpp +270 -0
  47. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512er.hpp +17 -0
  48. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512f.hpp +2919 -0
  49. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512ifma.hpp +17 -0
  50. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512pf.hpp +17 -0
  51. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512vbmi.hpp +76 -0
  52. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512vbmi2.hpp +130 -0
  53. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512vnni_avx512bw.hpp +17 -0
  54. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avx512vnni_avx512vbmi2.hpp +17 -0
  55. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_avxvnni.hpp +17 -0
  56. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_common.hpp +26 -0
  57. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_common_fwd.hpp +127 -0
  58. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_constants.hpp +393 -0
  59. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_emulated.hpp +787 -0
  60. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_fma3_avx.hpp +93 -0
  61. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_fma3_avx2.hpp +46 -0
  62. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_fma3_sse.hpp +97 -0
  63. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_fma4.hpp +92 -0
  64. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_i8mm_neon64.hpp +17 -0
  65. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_isa.hpp +146 -0
  66. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_neon.hpp +3580 -0
  67. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_neon64.hpp +1614 -0
  68. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_rvv.hpp +1515 -0
  69. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_scalar.hpp +1210 -0
  70. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_sse2.hpp +2333 -0
  71. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_sse3.hpp +66 -0
  72. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_sse4_1.hpp +510 -0
  73. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_sse4_2.hpp +44 -0
  74. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_ssse3.hpp +186 -0
  75. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_sve.hpp +1186 -0
  76. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_vsx.hpp +916 -0
  77. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_vxe.hpp +787 -0
  78. ycpp-0.1.0.data/headers/xsimd/arch/xsimd_wasm.hpp +1819 -0
  79. ycpp-0.1.0.data/headers/xsimd/config/xsimd_arch.hpp +242 -0
  80. ycpp-0.1.0.data/headers/xsimd/config/xsimd_config.hpp +620 -0
  81. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features.hpp +50 -0
  82. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features_arm.hpp +132 -0
  83. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features_ppc.hpp +54 -0
  84. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features_riscv.hpp +95 -0
  85. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features_s390x.hpp +56 -0
  86. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpu_features_x86.hpp +1044 -0
  87. ycpp-0.1.0.data/headers/xsimd/config/xsimd_cpuid.hpp +144 -0
  88. ycpp-0.1.0.data/headers/xsimd/config/xsimd_getauxval.hpp +159 -0
  89. ycpp-0.1.0.data/headers/xsimd/config/xsimd_macros.hpp +76 -0
  90. ycpp-0.1.0.data/headers/xsimd/math/xsimd_rem_pio2.hpp +707 -0
  91. ycpp-0.1.0.data/headers/xsimd/memory/xsimd_aligned_allocator.hpp +349 -0
  92. ycpp-0.1.0.data/headers/xsimd/memory/xsimd_alignment.hpp +102 -0
  93. ycpp-0.1.0.data/headers/xsimd/types/xsimd_all_registers.hpp +57 -0
  94. ycpp-0.1.0.data/headers/xsimd/types/xsimd_api.hpp +3106 -0
  95. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx2_register.hpp +44 -0
  96. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512bw_register.hpp +51 -0
  97. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512cd_register.hpp +51 -0
  98. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512dq_register.hpp +51 -0
  99. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512er_register.hpp +51 -0
  100. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512f_register.hpp +77 -0
  101. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512ifma_register.hpp +51 -0
  102. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512pf_register.hpp +51 -0
  103. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512vbmi2_register.hpp +51 -0
  104. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512vbmi_register.hpp +51 -0
  105. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512vnni_avx512bw_register.hpp +54 -0
  106. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx512vnni_avx512vbmi2_register.hpp +53 -0
  107. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avx_register.hpp +64 -0
  108. ycpp-0.1.0.data/headers/xsimd/types/xsimd_avxvnni_register.hpp +44 -0
  109. ycpp-0.1.0.data/headers/xsimd/types/xsimd_batch.hpp +1665 -0
  110. ycpp-0.1.0.data/headers/xsimd/types/xsimd_batch_constant.hpp +571 -0
  111. ycpp-0.1.0.data/headers/xsimd/types/xsimd_batch_fwd.hpp +41 -0
  112. ycpp-0.1.0.data/headers/xsimd/types/xsimd_common_arch.hpp +49 -0
  113. ycpp-0.1.0.data/headers/xsimd/types/xsimd_emulated_register.hpp +80 -0
  114. ycpp-0.1.0.data/headers/xsimd/types/xsimd_fma3_avx2_register.hpp +50 -0
  115. ycpp-0.1.0.data/headers/xsimd/types/xsimd_fma3_avx_register.hpp +50 -0
  116. ycpp-0.1.0.data/headers/xsimd/types/xsimd_fma3_sse_register.hpp +50 -0
  117. ycpp-0.1.0.data/headers/xsimd/types/xsimd_fma4_register.hpp +50 -0
  118. ycpp-0.1.0.data/headers/xsimd/types/xsimd_i8mm_neon64_register.hpp +55 -0
  119. ycpp-0.1.0.data/headers/xsimd/types/xsimd_neon64_register.hpp +55 -0
  120. ycpp-0.1.0.data/headers/xsimd/types/xsimd_neon_register.hpp +130 -0
  121. ycpp-0.1.0.data/headers/xsimd/types/xsimd_register.hpp +96 -0
  122. ycpp-0.1.0.data/headers/xsimd/types/xsimd_rvv_register.hpp +491 -0
  123. ycpp-0.1.0.data/headers/xsimd/types/xsimd_sse2_register.hpp +59 -0
  124. ycpp-0.1.0.data/headers/xsimd/types/xsimd_sse3_register.hpp +49 -0
  125. ycpp-0.1.0.data/headers/xsimd/types/xsimd_sse4_1_register.hpp +48 -0
  126. ycpp-0.1.0.data/headers/xsimd/types/xsimd_sse4_2_register.hpp +48 -0
  127. ycpp-0.1.0.data/headers/xsimd/types/xsimd_ssse3_register.hpp +48 -0
  128. ycpp-0.1.0.data/headers/xsimd/types/xsimd_sve_register.hpp +216 -0
  129. ycpp-0.1.0.data/headers/xsimd/types/xsimd_traits.hpp +408 -0
  130. ycpp-0.1.0.data/headers/xsimd/types/xsimd_utils.hpp +462 -0
  131. ycpp-0.1.0.data/headers/xsimd/types/xsimd_vsx_register.hpp +77 -0
  132. ycpp-0.1.0.data/headers/xsimd/types/xsimd_vxe_register.hpp +86 -0
  133. ycpp-0.1.0.data/headers/xsimd/types/xsimd_wasm_register.hpp +59 -0
  134. ycpp-0.1.0.data/headers/xsimd/utils/bits.hpp +122 -0
  135. ycpp-0.1.0.data/headers/xsimd/utils/xsimd_type_traits.hpp +145 -0
  136. ycpp-0.1.0.data/headers/xsimd/xsimd.hpp +43 -0
  137. ycpp-0.1.0.dist-info/DELVEWHEEL +2 -0
  138. ycpp-0.1.0.dist-info/METADATA +15 -0
  139. ycpp-0.1.0.dist-info/RECORD +142 -0
  140. ycpp-0.1.0.dist-info/WHEEL +4 -0
  141. ycpp.libs/msvcp140-9cb625fcbc2fbbd6fca1aee8b24b0ebe.dll +0 -0
  142. ycpp.libs/msvcp140_1-84ac1bc84e09d193dd6ad98c84c0fd94.dll +0 -0
ycpp/_id_map.py ADDED
@@ -0,0 +1,620 @@
1
+ """Attributed id ranges (pycrdt's IdMap, ContentAttribute and AttrRange).
2
+
3
+ An id map is what a delete set becomes once each range carries metadata: Yjs uses it to record who
4
+ deleted what. The coverage is kept per client as sorted, non-overlapping ranges.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import struct
12
+
13
+ from . import _ycpp
14
+ from ._sync import write_var_uint
15
+ from ._undo import IdSet
16
+
17
+ # Integers inside the JS safe range come back from Yjs as floats, larger ones as ints.
18
+ _SAFE_INT = 2**53
19
+
20
+ # The bytes of yrs' IdMap codec, as pycrdt 0.14.13 (yrs 0.28.1) writes them.
21
+ _TAG_UNDEFINED = 127
22
+ _TAG_NULL = 126
23
+ _TAG_INTEGER = 125
24
+ _TAG_FLOAT32 = 124
25
+ _TAG_FLOAT64 = 123
26
+ _TAG_BIGINT = 122
27
+ _TAG_FALSE = 121
28
+ _TAG_TRUE = 120
29
+ _TAG_STRING = 119
30
+ _TAG_MAP = 118
31
+ _TAG_ARRAY = 117
32
+
33
+ # The C++ Any decoder's max_any_depth: nesting past it is malformed input, not data to buffer.
34
+ _MAX_DEPTH = 32
35
+ # lib0 counts in JavaScript numbers: nothing beyond the safe integer range is a valid count.
36
+ _MAX_SAFE_INTEGER = 2**53 - 1
37
+
38
+
39
+ def _js_number(value: int) -> int | float:
40
+ return float(value) if -_SAFE_INT < value < _SAFE_INT else value
41
+
42
+
43
+ def _canonical_number(value):
44
+ """The number as Rust's Number compares it: an int that is exactly a double is that double."""
45
+ if isinstance(value, bool) or not isinstance(value, int):
46
+ return value
47
+ try:
48
+ number = float(value)
49
+ except OverflowError:
50
+ return value
51
+ return number if math.isfinite(number) and int(number) == value else value
52
+
53
+
54
+ def _canonical(value):
55
+ if isinstance(value, list):
56
+ return [_canonical(item) for item in value]
57
+ if isinstance(value, dict):
58
+ return {key: _canonical(item) for key, item in value.items()}
59
+ return _canonical_number(value)
60
+
61
+
62
+ def _write_string(out: bytearray, text: str) -> None:
63
+ data = text.encode()
64
+ out.extend(write_var_uint(len(data)))
65
+ out.extend(data)
66
+
67
+
68
+ def _write_float(out: bytearray, value: float) -> None:
69
+ try:
70
+ packed = struct.pack(">f", value)
71
+ except OverflowError:
72
+ packed = b""
73
+ if packed and struct.unpack(">f", packed)[0] == value:
74
+ out.append(_TAG_FLOAT32)
75
+ out.extend(packed)
76
+ else:
77
+ out.append(_TAG_FLOAT64)
78
+ out.extend(struct.pack(">d", value))
79
+
80
+
81
+ def _write_integer(out: bytearray, value: int) -> None:
82
+ if not -(2**63) <= value < 2**63:
83
+ raise ValueError("attribute integer out of the 64-bit range")
84
+ try:
85
+ number = float(value)
86
+ except OverflowError:
87
+ number = math.inf
88
+ if math.isfinite(number) and int(number) == value:
89
+ _write_float(out, number)
90
+ else:
91
+ out.append(_TAG_BIGINT)
92
+ out.extend(struct.pack(">q", value))
93
+
94
+
95
+ def _write_value(out: bytearray, value) -> None:
96
+ if value is None:
97
+ out.append(_TAG_NULL)
98
+ elif value is True:
99
+ out.append(_TAG_TRUE)
100
+ elif value is False:
101
+ out.append(_TAG_FALSE)
102
+ elif isinstance(value, str):
103
+ out.append(_TAG_STRING)
104
+ _write_string(out, value)
105
+ elif isinstance(value, int):
106
+ _write_integer(out, value)
107
+ elif isinstance(value, float):
108
+ _write_float(out, value)
109
+ elif isinstance(value, list):
110
+ out.append(_TAG_ARRAY)
111
+ out.extend(write_var_uint(len(value)))
112
+ for item in value:
113
+ _write_value(out, item)
114
+ elif isinstance(value, dict):
115
+ out.append(_TAG_MAP)
116
+ out.extend(write_var_uint(len(value)))
117
+ for key, item in value.items():
118
+ _write_string(out, key)
119
+ _write_value(out, item)
120
+ else:
121
+ raise TypeError(f"unsupported attribute value type: {type(value)!r}")
122
+
123
+
124
+ class _Reader:
125
+ """A bounded reader over an encoded IdMap: malformed bytes raise ValueError."""
126
+
127
+ def __init__(self, data: bytes) -> None:
128
+ self.data = data
129
+ self.position = 0
130
+
131
+ def byte(self) -> int:
132
+ if self.position >= len(self.data):
133
+ raise ValueError("malformed IdMap")
134
+ value = self.data[self.position]
135
+ self.position += 1
136
+ return value
137
+
138
+ def var_uint(self) -> int:
139
+ value = 0
140
+ for index in range(8):
141
+ byte = self.byte()
142
+ value |= (byte & 127) << (7 * index)
143
+ if byte < 128:
144
+ if value > _MAX_SAFE_INTEGER:
145
+ raise ValueError("malformed IdMap")
146
+ return value
147
+ raise ValueError("malformed IdMap")
148
+
149
+ def string(self) -> str:
150
+ length = self.var_uint()
151
+ end = self.position + length
152
+ if end > len(self.data):
153
+ raise ValueError("malformed IdMap")
154
+ text = self.data[self.position : end].decode()
155
+ self.position = end
156
+ return text
157
+
158
+ def var_int(self) -> int:
159
+ byte = self.byte()
160
+ negative = bool(byte & 0x40)
161
+ value = byte & 0x3F
162
+ shift = 6
163
+ count = 1
164
+ while byte & 0x80:
165
+ if count == 8:
166
+ raise ValueError("malformed IdMap")
167
+ byte = self.byte()
168
+ value |= (byte & 0x7F) << shift
169
+ shift += 7
170
+ count += 1
171
+ if value > _MAX_SAFE_INTEGER:
172
+ raise ValueError("malformed IdMap")
173
+ return -value if negative else value
174
+
175
+ def value(self, depth: int = 0):
176
+ if depth > _MAX_DEPTH:
177
+ raise ValueError("malformed IdMap")
178
+ tag = self.byte()
179
+ if tag == _TAG_UNDEFINED or tag == _TAG_NULL:
180
+ return None
181
+ if tag == _TAG_TRUE:
182
+ return True
183
+ if tag == _TAG_FALSE:
184
+ return False
185
+ if tag == _TAG_STRING:
186
+ return self.string()
187
+ if tag == _TAG_FLOAT32:
188
+ return struct.unpack(">f", self.take(4))[0]
189
+ if tag == _TAG_FLOAT64:
190
+ return struct.unpack(">d", self.take(8))[0]
191
+ if tag == _TAG_BIGINT:
192
+ return struct.unpack(">q", self.take(8))[0]
193
+ if tag == _TAG_INTEGER:
194
+ return _js_number(self.var_int())
195
+ if tag == _TAG_ARRAY:
196
+ return [self.value(depth + 1) for _ in range(self.var_uint())]
197
+ if tag == _TAG_MAP:
198
+ return {
199
+ self.string(): self.value(depth + 1) for _ in range(self.var_uint())
200
+ }
201
+ raise ValueError("malformed IdMap")
202
+
203
+ def take(self, length: int) -> bytes:
204
+ end = self.position + length
205
+ if end > len(self.data):
206
+ raise ValueError("malformed IdMap")
207
+ data = self.data[self.position : end]
208
+ self.position = end
209
+ return data
210
+
211
+
212
+ def _normalize(value):
213
+ if value is None or isinstance(value, (str, bool)):
214
+ return value
215
+ if isinstance(value, int):
216
+ return _js_number(value)
217
+ if isinstance(value, float):
218
+ if not math.isfinite(value):
219
+ raise ValueError("attribute values must be finite numbers")
220
+ return value
221
+ if isinstance(value, (list, tuple)):
222
+ return [_normalize(item) for item in value]
223
+ if isinstance(value, dict):
224
+ return {_string_key(key): _normalize(item) for key, item in value.items()}
225
+ raise TypeError(f"unsupported attribute value type: {type(value)!r}")
226
+
227
+
228
+ def _string_key(key) -> str:
229
+ if not isinstance(key, str):
230
+ raise TypeError(f"attribute value keys must be strings, got {type(key)!r}")
231
+ return key
232
+
233
+
234
+ class ContentAttribute:
235
+ """One metadata entry: a name and a JSON-compatible value."""
236
+
237
+ __slots__ = ("_name", "_value", "_key")
238
+
239
+ def __init__(self, name: str, value) -> None:
240
+ if not isinstance(name, str):
241
+ raise TypeError(f"attribute name must be a string, got {type(name)!r}")
242
+ self._name = name
243
+ self._value = _normalize(value)
244
+ # Sorted keys make dict comparison independent of insertion order, and numbers compare like
245
+ # Rust's Number, where an integer that a double represents exactly equals that double.
246
+ self._key = (
247
+ name,
248
+ json.dumps(_canonical(self._value), sort_keys=True, separators=(",", ":")),
249
+ )
250
+
251
+ @property
252
+ def name(self) -> str:
253
+ return self._name
254
+
255
+ @property
256
+ def value(self):
257
+ return self._value
258
+
259
+ def __eq__(self, other) -> bool:
260
+ if not isinstance(other, ContentAttribute):
261
+ return NotImplemented
262
+ return self._key == other._key
263
+
264
+ def __hash__(self) -> int:
265
+ return hash(self._key)
266
+
267
+ def __repr__(self) -> str:
268
+ return f"ContentAttribute({self._name!r}, {self._value!r})"
269
+
270
+
271
+ class AttrRange:
272
+ """A clock range [start, end) and the attributes covering it."""
273
+
274
+ __slots__ = ("_start", "_end", "_attributes")
275
+
276
+ def __init__(self, start: int, end: int, attributes) -> None:
277
+ self._start = start
278
+ self._end = end
279
+ self._attributes = list(attributes)
280
+
281
+ @property
282
+ def start(self) -> int:
283
+ return self._start
284
+
285
+ @property
286
+ def end(self) -> int:
287
+ return self._end
288
+
289
+ @property
290
+ def attributes(self) -> list[ContentAttribute]:
291
+ return self._attributes
292
+
293
+ def __eq__(self, other) -> bool:
294
+ if not isinstance(other, AttrRange):
295
+ return NotImplemented
296
+ return (self._start, self._end, self._attributes) == (
297
+ other._start,
298
+ other._end,
299
+ other._attributes,
300
+ )
301
+
302
+ def __repr__(self) -> str:
303
+ return f"AttrRange({self._start}, {self._end}, {self._attributes!r})"
304
+
305
+
306
+ # Ranges are (start, length, attributes) triples, sorted by start.
307
+
308
+
309
+ def _subtract(ranges, clock: int, length: int):
310
+ end = clock + length
311
+ kept = []
312
+ for start, span, attributes in ranges:
313
+ stop = start + span
314
+ if stop <= clock or start >= end:
315
+ kept.append((start, span, attributes))
316
+ continue
317
+ if start < clock:
318
+ kept.append((start, clock - start, attributes))
319
+ if stop > end:
320
+ kept.append((end, stop - end, attributes))
321
+ return kept
322
+
323
+
324
+ def _normalized(ranges):
325
+ merged = []
326
+ for start, span, attributes in sorted(ranges):
327
+ if merged:
328
+ last_start, last_span, last_attributes = merged[-1]
329
+ if last_attributes == attributes and last_start + last_span == start:
330
+ merged[-1] = (last_start, last_span + span, last_attributes)
331
+ continue
332
+ merged.append((start, span, attributes))
333
+ return merged
334
+
335
+
336
+ def _intersection(ranges, other):
337
+ kept = []
338
+ for start, span, attributes in ranges:
339
+ end = start + span
340
+ for other_start, other_span, _ in other:
341
+ low = max(start, other_start)
342
+ high = min(end, other_start + other_span)
343
+ if low < high:
344
+ kept.append((low, high - low, attributes))
345
+ return _normalized(kept)
346
+
347
+
348
+ def _set(clients: dict, client: int, clock: int, length: int, attributes) -> None:
349
+ if length <= 0 or not attributes:
350
+ return
351
+ ranges = _subtract(clients.get(client, ()), clock, length)
352
+ ranges.append((clock, length, tuple(attributes)))
353
+ clients[client] = _normalized(ranges)
354
+
355
+
356
+ class IdMap:
357
+ """Ranges of ids, each covered by a list of ContentAttribute."""
358
+
359
+ __slots__ = ("_clients",)
360
+
361
+ def __init__(self, _clients=None) -> None:
362
+ self._clients = {} if _clients is None else _clients
363
+
364
+ def is_empty(self) -> bool:
365
+ return not self._clients
366
+
367
+ def __bool__(self) -> bool:
368
+ return not self.is_empty()
369
+
370
+ def contains(self, client: int, clock: int) -> bool:
371
+ return any(
372
+ start <= clock < start + span
373
+ for start, span, _ in self._clients.get(client, ())
374
+ )
375
+
376
+ def insert(self, client: int, clock: int, length: int, attributes) -> None:
377
+ _set(self._clients, client, clock, length, attributes)
378
+
379
+ def remove(self, client: int, clock: int, length: int) -> None:
380
+ if client not in self._clients:
381
+ return
382
+ kept = _subtract(self._clients[client], clock, length)
383
+ if kept:
384
+ self._clients[client] = kept
385
+ else:
386
+ del self._clients[client]
387
+
388
+ def attributions(self, client: int, clock: int, length: int) -> list[AttrRange]:
389
+ end = clock + length
390
+ ranges = []
391
+ position = clock
392
+ for start, span, attributes in self._clients.get(client, ()):
393
+ stop = start + span
394
+ if stop <= position or start >= end:
395
+ continue
396
+ low = max(start, position)
397
+ high = min(stop, end)
398
+ if low > position:
399
+ ranges.append(AttrRange(position, low, []))
400
+ ranges.append(AttrRange(low, high, attributes))
401
+ position = high
402
+ if position < end:
403
+ ranges.append(AttrRange(position, end, []))
404
+ return ranges
405
+
406
+ def entries(self) -> list[tuple[int, AttrRange]]:
407
+ return [
408
+ (client, AttrRange(start, start + span, attributes))
409
+ for client, ranges in sorted(self._clients.items())
410
+ for start, span, attributes in ranges
411
+ ]
412
+
413
+ def __iter__(self):
414
+ return iter(self.entries())
415
+
416
+ def merge_with(self, other: IdMap) -> None:
417
+ for client, ranges in list(other._clients.items()):
418
+ for start, span, attributes in list(ranges):
419
+ _set(self._clients, client, start, span, attributes)
420
+
421
+ @classmethod
422
+ def merge_many(cls, maps) -> IdMap:
423
+ merged = cls()
424
+ for id_map in maps:
425
+ merged.merge_with(id_map)
426
+ return merged
427
+
428
+ def intersect_with(self, other: IdMap) -> None:
429
+ if not isinstance(other, IdMap):
430
+ raise TypeError(f"cannot intersect an IdMap with {type(other)!r}")
431
+ self._clients = {
432
+ client: _intersection(ranges, other._clients.get(client, ()))
433
+ for client, ranges in self._clients.items()
434
+ if client in other._clients
435
+ }
436
+ self._clients = {
437
+ client: ranges for client, ranges in self._clients.items() if ranges
438
+ }
439
+
440
+ def diff_with(self, other) -> None:
441
+ if isinstance(other, IdMap):
442
+ coverage = other._clients
443
+ elif isinstance(other, IdSet):
444
+ coverage = _clients_from_id_set(other)
445
+ else:
446
+ raise TypeError(f"cannot subtract {type(other)!r} from an IdMap")
447
+ for client, ranges in coverage.items():
448
+ for start, span, _ in ranges:
449
+ self.remove(client, start, span)
450
+
451
+ def filter(self, predicate) -> IdMap:
452
+ kept = IdMap()
453
+ for client, ranges in self._clients.items():
454
+ for start, span, attributes in ranges:
455
+ if predicate(list(attributes)):
456
+ kept.insert(client, start, span, attributes)
457
+ return kept
458
+
459
+ def as_id_set(self) -> IdSet:
460
+ id_set = IdSet()
461
+ for client, ranges in self._clients.items():
462
+ for start, span, _ in ranges:
463
+ id_set._set.add(client, start, span)
464
+ return id_set
465
+
466
+ @classmethod
467
+ def from_set(cls, id_set: IdSet, attributes) -> IdMap:
468
+ id_map = cls()
469
+ attributes = list(attributes)
470
+ for client, ranges in _clients_from_id_set(id_set).items():
471
+ for start, span, _ in ranges:
472
+ id_map.insert(client, start, span, attributes)
473
+ return id_map
474
+
475
+ def encode(self) -> bytes:
476
+ """Encodes the map as yrs' IdMap codec, byte-compatible with pycrdt/Yjs.
477
+
478
+ Clients are sorted and their ids delta-encoded; attribute values and names are interned as
479
+ dense ids in first-seen order, as yrs does.
480
+ """
481
+ out = bytearray()
482
+ out.extend(write_var_uint(len(self._clients)))
483
+ attributions: list[ContentAttribute] = []
484
+ names: list[str] = []
485
+ previous_client = 0
486
+ for client, ranges in sorted(self._clients.items()):
487
+ out.extend(write_var_uint(client - previous_client))
488
+ previous_client = client
489
+ out.extend(write_var_uint(len(ranges)))
490
+ for start, span, attributes in ranges:
491
+ out.extend(write_var_uint(start))
492
+ out.extend(write_var_uint(span))
493
+ out.extend(write_var_uint(len(attributes)))
494
+ for attribute in attributes:
495
+ try:
496
+ attribute_id = attributions.index(attribute)
497
+ except ValueError:
498
+ attribute_id = len(attributions)
499
+ attributions.append(attribute)
500
+ out.extend(write_var_uint(attribute_id))
501
+ try:
502
+ name_id = names.index(attribute.name)
503
+ except ValueError:
504
+ name_id = len(names)
505
+ names.append(attribute.name)
506
+ out.extend(write_var_uint(name_id))
507
+ _write_string(out, attribute.name)
508
+ else:
509
+ out.extend(write_var_uint(name_id))
510
+ _write_value(out, attribute.value)
511
+ else:
512
+ out.extend(write_var_uint(attribute_id))
513
+ return bytes(out)
514
+
515
+ @classmethod
516
+ def decode(cls, data: bytes) -> IdMap:
517
+ """Decodes yrs' IdMap codec, as pycrdt/Yjs encodes it."""
518
+ reader = _Reader(data)
519
+ try:
520
+ clients: dict = {}
521
+ client = 0
522
+ attributions: list[ContentAttribute] = []
523
+ names: list[str] = []
524
+ for _ in range(reader.var_uint()):
525
+ client += reader.var_uint()
526
+ range_count = reader.var_uint()
527
+ if range_count == 0:
528
+ clients.setdefault(client, [])
529
+ continue
530
+ for _ in range(range_count):
531
+ start = reader.var_uint()
532
+ span = reader.var_uint()
533
+ attributes = []
534
+ for _ in range(reader.var_uint()):
535
+ attribute_id = reader.var_uint()
536
+ if attribute_id < len(attributions):
537
+ attributes.append(attributions[attribute_id])
538
+ continue
539
+ if attribute_id != len(attributions):
540
+ raise ValueError("malformed IdMap")
541
+ name_id = reader.var_uint()
542
+ if name_id < len(names):
543
+ name = names[name_id]
544
+ elif name_id == len(names):
545
+ name = reader.string()
546
+ names.append(name)
547
+ else:
548
+ raise ValueError("malformed IdMap")
549
+ attribute = ContentAttribute(name, reader.value())
550
+ attributions.append(attribute)
551
+ attributes.append(attribute)
552
+ _set(clients, client, start, span, attributes)
553
+ return cls(clients)
554
+ except (
555
+ struct.error,
556
+ UnicodeDecodeError,
557
+ RecursionError,
558
+ TypeError,
559
+ IndexError,
560
+ ) as error:
561
+ raise ValueError("malformed IdMap") from error
562
+
563
+ def __eq__(self, other) -> bool:
564
+ if not isinstance(other, IdMap):
565
+ return NotImplemented
566
+ return self._clients == other._clients
567
+
568
+ def __or__(self, other) -> IdMap:
569
+ if not isinstance(other, IdMap):
570
+ return NotImplemented
571
+ union = IdMap()
572
+ union.merge_with(self)
573
+ union.merge_with(other)
574
+ return union
575
+
576
+ def __ior__(self, other) -> IdMap:
577
+ if not isinstance(other, IdMap):
578
+ return NotImplemented
579
+ self.merge_with(other)
580
+ return self
581
+
582
+ def __and__(self, other) -> IdMap:
583
+ if not isinstance(other, IdMap):
584
+ return NotImplemented
585
+ intersection = IdMap()
586
+ intersection.merge_with(self)
587
+ intersection.intersect_with(other)
588
+ return intersection
589
+
590
+ def __iand__(self, other) -> IdMap:
591
+ if not isinstance(other, IdMap):
592
+ return NotImplemented
593
+ self.intersect_with(other)
594
+ return self
595
+
596
+ def __sub__(self, other) -> IdMap:
597
+ if not isinstance(other, (IdMap, IdSet)):
598
+ return NotImplemented
599
+ difference = IdMap()
600
+ difference.merge_with(self)
601
+ difference.diff_with(other)
602
+ return difference
603
+
604
+ def __isub__(self, other) -> IdMap:
605
+ if not isinstance(other, (IdMap, IdSet)):
606
+ return NotImplemented
607
+ self.diff_with(other)
608
+ return self
609
+
610
+ def __repr__(self) -> str:
611
+ return f"IdMap({self.entries()!r})"
612
+
613
+
614
+ def _clients_from_id_set(id_set: IdSet) -> dict:
615
+ clients: dict = {}
616
+ for client, clock, length in id_set._set.ranges():
617
+ # A native delete set is a plain coverage: no attributes on its ranges.
618
+ if length:
619
+ clients.setdefault(client, []).append((clock, length, ()))
620
+ return {client: _normalized(ranges) for client, ranges in clients.items()}