ycpp 0.1.0__cp312-cp312-win_amd64.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.cp312-win_amd64.lib +0 -0
  20. ycpp/_ycpp.cp312-win_amd64.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-a4c2229bdc2a2a630acdc095b4d86008.dll +0 -0
  142. ycpp.libs/msvcp140_1-226498d4bfcb4f07974757b596ebec45.dll +0 -0
ycpp/_transaction.py ADDED
@@ -0,0 +1,287 @@
1
+ from __future__ import annotations
2
+
3
+ import threading
4
+ import weakref
5
+
6
+ from anyio import create_task_group, to_thread
7
+
8
+
9
+ def hash_origin(origin) -> int:
10
+ try:
11
+ return hash(origin)
12
+ except TypeError:
13
+ raise TypeError("Origin must be hashable")
14
+
15
+
16
+ class _LockAcquisition:
17
+ """Takes a lock in a worker thread, and hands it back if the awaiting task is abandoned.
18
+
19
+ anyio's ``abandon_on_cancel`` discards the worker's result: the thread may still win the lock
20
+ after the task was cancelled, and nothing would ever release it. Both sides agree on the outcome
21
+ under ``_state``, so whichever arrives second releases.
22
+ """
23
+
24
+ def __init__(self, lock, timeout) -> None:
25
+ self._lock = lock
26
+ self._timeout = timeout
27
+ self._state = threading.Lock()
28
+ self._acquired = False
29
+ self._abandoned = False
30
+
31
+ def acquire(self) -> bool:
32
+ acquired = self._lock.acquire(timeout=self._timeout)
33
+ with self._state:
34
+ if acquired and self._abandoned:
35
+ self._lock.release()
36
+ return False
37
+ self._acquired = acquired
38
+ return acquired
39
+
40
+ def abandon(self) -> None:
41
+ with self._state:
42
+ self._abandoned = True
43
+ if self._acquired:
44
+ self._acquired = False
45
+ self._lock.release()
46
+
47
+
48
+ class Transaction:
49
+ """A group of writes that becomes one native transaction: one update and one event batch.
50
+
51
+ Nested blocks join the transaction the outermost one opened, so an observer sees the whole
52
+ group through one event, as it does in pycrdt.
53
+ """
54
+
55
+ def __init__(self, doc: "Doc", origin=None, *, timeout=None) -> None:
56
+ self._doc = doc
57
+ self._origin = origin
58
+ self._leases = 0
59
+ self._open = False
60
+ self._closing = False
61
+ self._owner = None
62
+ self._token = None
63
+ self._locked = False
64
+ self._async_locked = False
65
+ self._opened_async = False
66
+ self._task_group = None
67
+ self._timeout = -1 if timeout is None else timeout
68
+ if origin is not None:
69
+ doc._origins[hash_origin(origin)] = origin
70
+
71
+ @classmethod
72
+ def _from_native(cls, doc: "Doc", origin) -> "Transaction":
73
+ """The transaction an event carries: the Python origin the write named, already resolved."""
74
+ transaction = cls.__new__(cls)
75
+ transaction._doc = doc
76
+ transaction._origin = origin
77
+ transaction._leases = 1
78
+ transaction._open = True
79
+ transaction._closing = False
80
+ transaction._owner = None
81
+ transaction._token = None
82
+ transaction._locked = False
83
+ transaction._async_locked = False
84
+ transaction._opened_async = False
85
+ transaction._task_group = None
86
+ transaction._timeout = -1
87
+ return transaction
88
+
89
+ @property
90
+ def origin(self):
91
+ if not self._open and not self._closing:
92
+ raise RuntimeError("No current transaction")
93
+ return self._origin
94
+
95
+ def __enter__(self, _acquire_transaction: bool = True) -> "Transaction":
96
+ ident = threading.get_ident()
97
+ if self._owner is not None and self._owner != ident:
98
+ raise RuntimeError("Transaction opened on another thread")
99
+ self._owner = ident
100
+ # pycrdt increments before acquiring, so a failed acquire leaves the lease in place too.
101
+ self._leases += 1
102
+ if self._open:
103
+ return self
104
+ doc = self._doc
105
+ if doc._allow_multithreading and _acquire_transaction:
106
+ if not doc._txn_lock.acquire(timeout=self._timeout):
107
+ raise TimeoutError("Could not acquire transaction")
108
+ self._locked = True
109
+ try:
110
+ self._token = doc._begin_transaction(self._origin)
111
+ except BaseException:
112
+ self._open = False
113
+ self._owner = None
114
+ self._release_locks()
115
+ raise
116
+ self._open = True
117
+ doc._stack().append(weakref.ref(self))
118
+ return self
119
+
120
+ def __exit__(self, exc_type, exc_value, traceback) -> bool:
121
+ # Only the thread that opened the block may close it: an unbalanced exit must not commit
122
+ # another thread's transaction, nor release a lock it does not hold.
123
+ if self._owner is None or self._owner != threading.get_ident():
124
+ return False
125
+ if self._leases == 0:
126
+ return False
127
+ self._leases -= 1
128
+ if self._leases > 0 or self._closing or not self._open:
129
+ return False
130
+ self._closing = True
131
+ doc = self._doc
132
+ try:
133
+ try:
134
+ self._commit()
135
+ if self._origin is not None:
136
+ doc._origins.pop(hash(self._origin), None)
137
+ finally:
138
+ self._open = False
139
+ self._owner = None
140
+ self._remove_from_stack()
141
+ doc._doc.set_local_origin(None)
142
+ self._release_locks()
143
+ finally:
144
+ self._closing = False
145
+ doc._raise_observer_errors()
146
+ return False
147
+
148
+ def __del__(self):
149
+ # A block left without its exit would otherwise keep the native transaction open for ever:
150
+ # no event fires and the document looks frozen.
151
+ token = getattr(self, "_token", None)
152
+ if token is None:
153
+ return
154
+ self._token = None
155
+ try:
156
+ self._doc._end_transaction(token)
157
+ except Exception:
158
+ pass
159
+ try:
160
+ self._release_locks()
161
+ except Exception:
162
+ pass
163
+
164
+ def _commit(self) -> None:
165
+ token, self._token = self._token, None
166
+ if token is not None:
167
+ self._doc._end_transaction(token)
168
+
169
+ def _remove_from_stack(self) -> None:
170
+ stack = self._doc._stack()
171
+ stack[:] = [ref for ref in stack if ref() not in (None, self)]
172
+
173
+ def _release_locks(self) -> None:
174
+ doc = self._doc
175
+ if self._locked:
176
+ self._locked = False
177
+ doc._txn_lock.release()
178
+ if self._async_locked:
179
+ self._async_locked = False
180
+ doc._txn_async_lock.release()
181
+
182
+ async def __aenter__(self, _acquire_transaction: bool = True) -> "Transaction":
183
+ doc = self._doc
184
+ if self._leases == 0:
185
+ if not doc._allow_multithreading and not self._open:
186
+ # The async lock is taken before the task group: it is the lock that makes two
187
+ # overlapping async transactions wait instead of both opening on the document.
188
+ await doc._txn_async_lock.acquire()
189
+ self._async_locked = True
190
+ try:
191
+ group = await create_task_group().__aenter__()
192
+ except BaseException:
193
+ await self._abandon_async()
194
+ raise
195
+ self._task_group = doc._task_group = group
196
+ self._opened_async = True
197
+ elif doc._task_group is None:
198
+ raise RuntimeError("Already in a non-async transaction")
199
+ try:
200
+ return self.__enter__(_acquire_transaction)
201
+ except BaseException:
202
+ await self._abandon_async()
203
+ raise
204
+
205
+ async def __aexit__(self, exc_type, exc_value, traceback) -> bool:
206
+ result = self.__exit__(exc_type, exc_value, traceback)
207
+ if self._opened_async and self._leases == 0:
208
+ self._opened_async = False
209
+ return await self._exit_task_group(exc_type, exc_value, traceback)
210
+ return result
211
+
212
+ async def _exit_task_group(self, exc_type, exc_value, traceback) -> bool:
213
+ # The group each transaction opened is its own: a transaction that waited on the async lock
214
+ # may already have replaced doc._task_group by the time this one exits.
215
+ group, self._task_group = self._task_group, None
216
+ if self._doc._task_group is group:
217
+ self._doc._task_group = None
218
+ if group is None:
219
+ return False
220
+ return await group.__aexit__(exc_type, exc_value, traceback)
221
+
222
+ async def _abandon_async(self) -> None:
223
+ if self._async_locked:
224
+ self._async_locked = False
225
+ self._doc._txn_async_lock.release()
226
+ self._opened_async = False
227
+ await self._exit_task_group(None, None, None)
228
+
229
+ def drop(self) -> None:
230
+ pass
231
+
232
+ def __repr__(self) -> str:
233
+ return f"Transaction(origin={self._origin!r})"
234
+
235
+
236
+ class NewTransaction(Transaction):
237
+ """A transaction that waits for the open one instead of joining it; see Doc.new_transaction."""
238
+
239
+ async def __aenter__(self) -> "Transaction":
240
+ doc = self._doc
241
+ acquisition = None
242
+ if doc._allow_multithreading:
243
+ acquisition = _LockAcquisition(doc._txn_lock, self._timeout)
244
+ try:
245
+ acquired = await to_thread.run_sync(
246
+ acquisition.acquire, abandon_on_cancel=True
247
+ )
248
+ except BaseException:
249
+ acquisition.abandon()
250
+ raise
251
+ if not acquired:
252
+ raise TimeoutError("Could not acquire transaction")
253
+ self._locked = True
254
+ try:
255
+ return await super().__aenter__(_acquire_transaction=False)
256
+ except BaseException:
257
+ try:
258
+ self._commit()
259
+ finally:
260
+ self._release_locks()
261
+ await self._abandon_async()
262
+ raise
263
+
264
+ async def __aexit__(self, exc_type, exc_value, traceback) -> bool:
265
+ return await super().__aexit__(exc_type, exc_value, traceback)
266
+
267
+
268
+ class ReadTransaction(Transaction):
269
+ """The read-only view of a transaction an observer callback runs in."""
270
+
271
+ def __init__(self, doc: "Doc", origin=None) -> None:
272
+ super().__init__(doc, origin)
273
+ self._open = True
274
+
275
+ def __enter__(self, _acquire_transaction: bool = True) -> "ReadTransaction":
276
+ self._leases += 1
277
+ return self
278
+
279
+ def __exit__(self, exc_type, exc_value, traceback) -> bool:
280
+ self._leases -= 1
281
+ if self._leases <= 0:
282
+ self._leases = 0
283
+ self._open = False
284
+ return False
285
+
286
+ def _commit(self) -> None:
287
+ pass
ycpp/_typed.py ADDED
@@ -0,0 +1,122 @@
1
+ """Typed containers: pycrdt's typed layer over Doc, Array and Map (python/tests/pycrdt_suite/test_typed.py)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import UnionType
6
+ from typing import Any, Generic, TypeVar, Union, get_args, get_origin, get_type_hints
7
+
8
+ from ._array import Array
9
+ from ._doc import Doc
10
+ from ._map import Map
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ class Typed:
16
+ """Maps attribute access onto a shared container: the annotations name the fields."""
17
+
18
+ _: Any
19
+
20
+ def __init__(self) -> None:
21
+ self.__dict__["annotations"] = {
22
+ name: kind
23
+ for name, kind in get_type_hints(type(self).mro()[0]).items()
24
+ if name != "_"
25
+ }
26
+
27
+ def __getattr__(self, key: str) -> Any:
28
+ annotations = self.__dict__["annotations"]
29
+ if key not in annotations:
30
+ raise AttributeError(f'"{type(self).mro()[0]}" has no attribute "{key}"')
31
+ expected_type = annotations[key]
32
+ if hasattr(expected_type, "mro") and Typed in expected_type.mro():
33
+ return expected_type(self._[key])
34
+ return self._[key]
35
+
36
+ def __setattr__(self, key: str, value: Any) -> None:
37
+ if key == "_":
38
+ self.__dict__["_"] = value
39
+ return
40
+ annotations = self.__dict__["annotations"]
41
+ if key not in annotations:
42
+ raise AttributeError(f'"{type(self).mro()[0]}" has no attribute "{key}"')
43
+ expected_type = annotations[key]
44
+ origin = get_origin(expected_type)
45
+ if origin in (Union, UnionType):
46
+ expected_types = get_args(expected_type)
47
+ elif origin is not None:
48
+ expected_type = origin
49
+ expected_types = (expected_type,)
50
+ else:
51
+ expected_types = (expected_type,)
52
+ if type(value) not in expected_types:
53
+ raise TypeError(
54
+ f'Incompatible types in assignment (expression has type "{expected_type}", '
55
+ f'variable has type "{type(value)}")'
56
+ )
57
+ self._[key] = value._ if isinstance(value, Typed) else value
58
+
59
+
60
+ class TypedArray(Typed, Generic[T]):
61
+ """An Array whose items are wrapped as the `type` annotation says."""
62
+
63
+ type: T
64
+ _: Array
65
+
66
+ def __init__(self, array: TypedArray | Array | None = None) -> None:
67
+ super().__init__()
68
+ if isinstance(array, TypedArray):
69
+ array = array._
70
+ elif array is None:
71
+ array = Array()
72
+ self._ = array
73
+ self.__dict__["type"] = self.__dict__["annotations"]["type"]
74
+
75
+ def __getitem__(self, key):
76
+ return self.__dict__["type"](self._[key])
77
+
78
+ def __setitem__(self, key, value) -> None:
79
+ self._[key] = value._ if isinstance(value, Typed) else value
80
+
81
+ def append(self, value) -> None:
82
+ self._.append(value._ if isinstance(value, Typed) else value)
83
+
84
+ def extend(self, values) -> None:
85
+ self._.extend(
86
+ [value._ if isinstance(value, Typed) else value for value in values]
87
+ )
88
+
89
+ def __len__(self) -> int:
90
+ return len(self._)
91
+
92
+
93
+ class TypedMap(Typed):
94
+ """A Map whose keys are the annotations of the subclass."""
95
+
96
+ _: Map
97
+
98
+ def __init__(self, map: TypedMap | Map | None = None) -> None:
99
+ super().__init__()
100
+ if isinstance(map, TypedMap):
101
+ map = map._
102
+ elif map is None:
103
+ map = Map()
104
+ self._ = map
105
+
106
+
107
+ class TypedDoc(Typed):
108
+ """A Doc whose root types are the annotations of the subclass, created on construction."""
109
+
110
+ _: Doc
111
+
112
+ def __init__(self, doc: TypedDoc | Doc | None = None) -> None:
113
+ super().__init__()
114
+ if isinstance(doc, TypedDoc):
115
+ doc = doc._
116
+ elif doc is None:
117
+ doc = Doc()
118
+ assert isinstance(doc, Doc)
119
+ self._ = doc
120
+ for name, kind in self.__dict__["annotations"].items():
121
+ root = kind()
122
+ doc[name] = root._ if isinstance(root, Typed) else root
ycpp/_undo.py ADDED
@@ -0,0 +1,201 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+
5
+ from . import _ycpp
6
+
7
+ # A manager's own token is a negative counter; a document's origin tokens start at 1, so the two
8
+ # cannot collide.
9
+ _manager_origins = itertools.count(1)
10
+
11
+ # Stack item metadata is a Python object, so it lives here, keyed by the native item's uid: a copy of
12
+ # an item a manager keeps still names the same metadata.
13
+ _METAS: dict = {}
14
+
15
+
16
+ class IdSet:
17
+ """The ids one stack item replaces or restores, in their encoded form (pycrdt's IdSet)."""
18
+
19
+ __slots__ = ("_set",)
20
+
21
+ def __init__(self, _set=None) -> None:
22
+ self._set = _ycpp.IdSet() if _set is None else _set
23
+
24
+ def encode(self) -> bytes:
25
+ return self._set.encode()
26
+
27
+ @classmethod
28
+ def decode(cls, data: bytes) -> "IdSet":
29
+ return cls(_ycpp.IdSet.decode(data))
30
+
31
+ def __repr__(self) -> str:
32
+ return f"IdSet({self.encode()!r})"
33
+
34
+
35
+ class StackItem:
36
+ """One undo step: what it deletes to undo, and what it must put back.
37
+
38
+ pycrdt keeps a step's metadata as one arbitrary Python object; it is kept here, keyed by the key
39
+ the native item carries, so an item read back from a manager still reports it.
40
+ """
41
+
42
+ __slots__ = ("_item", "_key", "_meta")
43
+
44
+ def __init__(self, doc, deletions, insertions, meta=None) -> None:
45
+ self._item = _ycpp.StackItem(_raw_id_set(deletions), _raw_id_set(insertions))
46
+ self._key = self._item.uid()
47
+ self._meta = None
48
+ self.meta = meta
49
+
50
+ @classmethod
51
+ def _wrap(cls, item: _ycpp.StackItem) -> "StackItem":
52
+ wrapped = cls.__new__(cls)
53
+ wrapped._item = item
54
+ wrapped._key = item.uid()
55
+ wrapped._meta = _METAS.get(wrapped._key)
56
+ return wrapped
57
+
58
+ @property
59
+ def meta(self):
60
+ return self._meta
61
+
62
+ @meta.setter
63
+ def meta(self, value) -> None:
64
+ self._meta = value
65
+ _METAS[self._key] = value
66
+
67
+ @property
68
+ def deletions(self) -> IdSet:
69
+ return IdSet(self._item.deletions())
70
+
71
+ @property
72
+ def insertions(self) -> IdSet:
73
+ return IdSet(self._item.insertions())
74
+
75
+ @classmethod
76
+ def __class_getitem__(cls, item):
77
+ return cls
78
+
79
+ @staticmethod
80
+ def merge(left: "StackItem", right: "StackItem", handler=None) -> "StackItem":
81
+ """Fold two steps into one; without a handler the left item's metadata wins."""
82
+ merged = StackItem._wrap(_ycpp.StackItem.merge(left._item, right._item))
83
+ merged.meta = (
84
+ handler(left.meta, right.meta) if handler is not None else left.meta
85
+ )
86
+ return merged
87
+
88
+
89
+ def _raw_id_set(value):
90
+ return value._set if isinstance(value, IdSet) else value
91
+
92
+
93
+ class UndoManager:
94
+ """Records the edits its scopes make, and puts them back on undo (pycrdt's UndoManager).
95
+
96
+ ``timestamp`` is called to date a stack item, with the document locked: it must not touch this
97
+ document, and reaching into another document can deadlock two documents that do so at the same
98
+ time. Read a clock and return the value.
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ *,
104
+ doc=None,
105
+ scopes=(),
106
+ capture_timeout_millis: int = 500,
107
+ timestamp=None,
108
+ undo_stack=None,
109
+ redo_stack=None,
110
+ ) -> None:
111
+ scopes = list(scopes)
112
+ self._doc = doc if doc is not None else (scopes[0].doc if scopes else None)
113
+ self._origin = -next(_manager_origins)
114
+ # Origins a caller asked to track, by token; empty means "track every origin".
115
+ self._origins: set[int] = set()
116
+ self._tracked_refs: list = []
117
+ self._native_origins = {None}
118
+ self._capture_timeout = capture_timeout_millis
119
+ self._timestamp = timestamp
120
+ self._handle = None
121
+ if self._doc is not None:
122
+ self._handle = _ycpp.UndoManager(
123
+ self._doc._doc,
124
+ capture_timeout_millis,
125
+ timestamp,
126
+ [item._item for item in (undo_stack or ())],
127
+ [item._item for item in (redo_stack or ())],
128
+ )
129
+ self._handle.set_origin(self._origin)
130
+ for scope in scopes:
131
+ self._check_scope(scope)
132
+ self._handle.add_scope(scope._ref)
133
+
134
+ def _check_scope(self, scope) -> None:
135
+ if scope.doc is not self._doc:
136
+ raise ValueError("scope must belong to the manager's document")
137
+
138
+ def _ensure(self) -> _ycpp.UndoManager:
139
+ if self._handle is None:
140
+ if self._doc is None:
141
+ raise RuntimeError("the undo manager has no document")
142
+ self._handle = _ycpp.UndoManager(
143
+ self._doc._doc, self._capture_timeout, self._timestamp, [], []
144
+ )
145
+ self._handle.set_origin(self._origin)
146
+ self._sync_origins()
147
+ return self._handle
148
+
149
+ @property
150
+ def origin(self) -> int:
151
+ return self._origin
152
+
153
+ def expand_scope(self, scope) -> None:
154
+ self._check_scope(scope)
155
+ self._ensure().expand_scope(scope._ref)
156
+
157
+ def include_origin(self, origin) -> None:
158
+ token = self._doc._origin_token(origin)
159
+ self._origins.add(token)
160
+ self._tracked_refs.append(origin)
161
+ self._sync_origins()
162
+
163
+ def exclude_origin(self, origin) -> None:
164
+ self._origins.discard(self._doc._origin_token(origin))
165
+ self._sync_origins()
166
+
167
+ def _sync_origins(self) -> None:
168
+ handle = self._handle
169
+ if handle is None:
170
+ return
171
+ # No origin asked for means every origin is tracked, which is the null origin alone: a
172
+ # transaction a peer applies carries no origin on this side.
173
+ wanted = set(self._origins) if self._origins else {None}
174
+ for token in self._native_origins - wanted:
175
+ handle.remove_tracked_origin(token)
176
+ for token in wanted - self._native_origins:
177
+ handle.add_tracked_origin(token)
178
+ self._native_origins = wanted
179
+
180
+ def can_undo(self) -> bool:
181
+ return self._ensure().can_undo()
182
+
183
+ def can_redo(self) -> bool:
184
+ return self._ensure().can_redo()
185
+
186
+ def undo(self) -> bool:
187
+ return self._ensure().undo()
188
+
189
+ def redo(self) -> bool:
190
+ return self._ensure().redo()
191
+
192
+ def clear(self) -> None:
193
+ self._ensure().clear()
194
+
195
+ @property
196
+ def undo_stack(self) -> list:
197
+ return [StackItem._wrap(item) for item in self._ensure().undo_stack()]
198
+
199
+ @property
200
+ def redo_stack(self) -> list:
201
+ return [StackItem._wrap(item) for item in self._ensure().redo_stack()]
ycpp/_update.py ADDED
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from . import _ycpp
4
+
5
+
6
+ def get_state(update: bytes) -> bytes:
7
+ """The state vector an update covers."""
8
+ return _ycpp.get_state(update)
9
+
10
+
11
+ def get_update(update: bytes, state: bytes) -> bytes:
12
+ """The part of one update a peer at `state` is missing."""
13
+ return _ycpp.get_update(update, state)
14
+
15
+
16
+ def merge_updates(*updates: bytes) -> bytes:
17
+ """One update holding the structs and deletions of every argument."""
18
+ return _ycpp.merge_updates(list(updates))