ycpp 0.1.3__cp312-abi3-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.lib +0 -0
  20. ycpp/_ycpp.pyd +0 -0
  21. ycpp-0.1.3.data/headers/fast_float/ascii_number.h +766 -0
  22. ycpp-0.1.3.data/headers/fast_float/bigint.h +638 -0
  23. ycpp-0.1.3.data/headers/fast_float/constexpr_feature_detect.h +53 -0
  24. ycpp-0.1.3.data/headers/fast_float/decimal_to_binary.h +212 -0
  25. ycpp-0.1.3.data/headers/fast_float/digit_comparison.h +455 -0
  26. ycpp-0.1.3.data/headers/fast_float/fast_float.h +91 -0
  27. ycpp-0.1.3.data/headers/fast_float/fast_table.h +708 -0
  28. ycpp-0.1.3.data/headers/fast_float/float_common.h +1432 -0
  29. ycpp-0.1.3.data/headers/fast_float/parse_number.h +488 -0
  30. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_arithmetic.hpp +267 -0
  31. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_bit.hpp +230 -0
  32. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_cast.hpp +43 -0
  33. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_complex.hpp +112 -0
  34. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_details.hpp +386 -0
  35. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_logical.hpp +240 -0
  36. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_math.hpp +2601 -0
  37. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_memory.hpp +1006 -0
  38. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_rounding.hpp +72 -0
  39. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_swizzle.hpp +260 -0
  40. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_trigo.hpp +996 -0
  41. ycpp-0.1.3.data/headers/xsimd/arch/utils/shifts.hpp +82 -0
  42. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx.hpp +2111 -0
  43. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx2.hpp +1591 -0
  44. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512bw.hpp +724 -0
  45. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512cd.hpp +28 -0
  46. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512dq.hpp +270 -0
  47. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512er.hpp +17 -0
  48. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512f.hpp +2919 -0
  49. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512ifma.hpp +17 -0
  50. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512pf.hpp +17 -0
  51. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vbmi.hpp +76 -0
  52. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vbmi2.hpp +130 -0
  53. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vnni_avx512bw.hpp +17 -0
  54. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vnni_avx512vbmi2.hpp +17 -0
  55. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avxvnni.hpp +17 -0
  56. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_common.hpp +26 -0
  57. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_common_fwd.hpp +127 -0
  58. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_constants.hpp +393 -0
  59. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_emulated.hpp +787 -0
  60. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_avx.hpp +93 -0
  61. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_avx2.hpp +46 -0
  62. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_sse.hpp +97 -0
  63. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma4.hpp +92 -0
  64. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_i8mm_neon64.hpp +17 -0
  65. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_isa.hpp +146 -0
  66. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_neon.hpp +3580 -0
  67. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_neon64.hpp +1614 -0
  68. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_rvv.hpp +1515 -0
  69. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_scalar.hpp +1210 -0
  70. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse2.hpp +2333 -0
  71. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse3.hpp +66 -0
  72. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse4_1.hpp +510 -0
  73. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse4_2.hpp +44 -0
  74. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_ssse3.hpp +186 -0
  75. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sve.hpp +1186 -0
  76. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_vsx.hpp +916 -0
  77. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_vxe.hpp +787 -0
  78. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_wasm.hpp +1819 -0
  79. ycpp-0.1.3.data/headers/xsimd/config/xsimd_arch.hpp +242 -0
  80. ycpp-0.1.3.data/headers/xsimd/config/xsimd_config.hpp +620 -0
  81. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features.hpp +50 -0
  82. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_arm.hpp +132 -0
  83. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_ppc.hpp +54 -0
  84. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_riscv.hpp +95 -0
  85. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_s390x.hpp +56 -0
  86. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_x86.hpp +1044 -0
  87. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpuid.hpp +144 -0
  88. ycpp-0.1.3.data/headers/xsimd/config/xsimd_getauxval.hpp +159 -0
  89. ycpp-0.1.3.data/headers/xsimd/config/xsimd_macros.hpp +76 -0
  90. ycpp-0.1.3.data/headers/xsimd/math/xsimd_rem_pio2.hpp +707 -0
  91. ycpp-0.1.3.data/headers/xsimd/memory/xsimd_aligned_allocator.hpp +349 -0
  92. ycpp-0.1.3.data/headers/xsimd/memory/xsimd_alignment.hpp +102 -0
  93. ycpp-0.1.3.data/headers/xsimd/types/xsimd_all_registers.hpp +57 -0
  94. ycpp-0.1.3.data/headers/xsimd/types/xsimd_api.hpp +3106 -0
  95. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx2_register.hpp +44 -0
  96. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512bw_register.hpp +51 -0
  97. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512cd_register.hpp +51 -0
  98. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512dq_register.hpp +51 -0
  99. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512er_register.hpp +51 -0
  100. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512f_register.hpp +77 -0
  101. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512ifma_register.hpp +51 -0
  102. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512pf_register.hpp +51 -0
  103. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vbmi2_register.hpp +51 -0
  104. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vbmi_register.hpp +51 -0
  105. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vnni_avx512bw_register.hpp +54 -0
  106. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vnni_avx512vbmi2_register.hpp +53 -0
  107. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx_register.hpp +64 -0
  108. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avxvnni_register.hpp +44 -0
  109. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch.hpp +1665 -0
  110. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch_constant.hpp +571 -0
  111. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch_fwd.hpp +41 -0
  112. ycpp-0.1.3.data/headers/xsimd/types/xsimd_common_arch.hpp +49 -0
  113. ycpp-0.1.3.data/headers/xsimd/types/xsimd_emulated_register.hpp +80 -0
  114. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_avx2_register.hpp +50 -0
  115. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_avx_register.hpp +50 -0
  116. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_sse_register.hpp +50 -0
  117. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma4_register.hpp +50 -0
  118. ycpp-0.1.3.data/headers/xsimd/types/xsimd_i8mm_neon64_register.hpp +55 -0
  119. ycpp-0.1.3.data/headers/xsimd/types/xsimd_neon64_register.hpp +55 -0
  120. ycpp-0.1.3.data/headers/xsimd/types/xsimd_neon_register.hpp +130 -0
  121. ycpp-0.1.3.data/headers/xsimd/types/xsimd_register.hpp +96 -0
  122. ycpp-0.1.3.data/headers/xsimd/types/xsimd_rvv_register.hpp +491 -0
  123. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse2_register.hpp +59 -0
  124. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse3_register.hpp +49 -0
  125. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse4_1_register.hpp +48 -0
  126. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse4_2_register.hpp +48 -0
  127. ycpp-0.1.3.data/headers/xsimd/types/xsimd_ssse3_register.hpp +48 -0
  128. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sve_register.hpp +216 -0
  129. ycpp-0.1.3.data/headers/xsimd/types/xsimd_traits.hpp +408 -0
  130. ycpp-0.1.3.data/headers/xsimd/types/xsimd_utils.hpp +462 -0
  131. ycpp-0.1.3.data/headers/xsimd/types/xsimd_vsx_register.hpp +77 -0
  132. ycpp-0.1.3.data/headers/xsimd/types/xsimd_vxe_register.hpp +86 -0
  133. ycpp-0.1.3.data/headers/xsimd/types/xsimd_wasm_register.hpp +59 -0
  134. ycpp-0.1.3.data/headers/xsimd/utils/bits.hpp +122 -0
  135. ycpp-0.1.3.data/headers/xsimd/utils/xsimd_type_traits.hpp +145 -0
  136. ycpp-0.1.3.data/headers/xsimd/xsimd.hpp +43 -0
  137. ycpp-0.1.3.dist-info/DELVEWHEEL +2 -0
  138. ycpp-0.1.3.dist-info/METADATA +15 -0
  139. ycpp-0.1.3.dist-info/RECORD +142 -0
  140. ycpp-0.1.3.dist-info/WHEEL +4 -0
  141. ycpp.libs/msvcp140-9cb625fcbc2fbbd6fca1aee8b24b0ebe.dll +0 -0
  142. ycpp.libs/msvcp140_1-84ac1bc84e09d193dd6ad98c84c0fd94.dll +0 -0
ycpp/__init__.py ADDED
@@ -0,0 +1,110 @@
1
+ """""" # start delvewheel patch
2
+ def _delvewheel_patch_1_13_2():
3
+ import os
4
+ if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'ycpp.libs'))):
5
+ os.add_dll_directory(libs_dir)
6
+
7
+
8
+ _delvewheel_patch_1_13_2()
9
+ del _delvewheel_patch_1_13_2
10
+ # end delvewheel patch
11
+
12
+ from ._array import Array
13
+ from ._awareness import Awareness, is_awareness_disconnect_message
14
+ from ._doc import Doc
15
+ from ._event import (
16
+ ArrayEvent,
17
+ MapEvent,
18
+ SubdocsEvent,
19
+ Subscription,
20
+ TextEvent,
21
+ TransactionEvent,
22
+ )
23
+ from ._map import Map
24
+ from ._provider import Channel, Provider
25
+ from ._snapshot import Snapshot
26
+ from ._sticky_index import Assoc, StickyIndex
27
+ from ._stream import UnsubscribableStream
28
+ from ._sync import (
29
+ Decoder,
30
+ Encoder,
31
+ YMessageType,
32
+ YSyncMessageType,
33
+ create_awareness_message,
34
+ create_message,
35
+ create_sync_message,
36
+ create_sync_step1_message,
37
+ create_sync_step2_message,
38
+ create_update_message,
39
+ handle_sync_message,
40
+ read_message,
41
+ write_message,
42
+ write_var_uint,
43
+ )
44
+ from ._id_map import AttrRange, ContentAttribute, IdMap
45
+ from ._text import Text
46
+ from ._transaction import NewTransaction, ReadTransaction, Transaction
47
+ from ._typed import Typed, TypedArray, TypedDoc, TypedMap
48
+ from ._undo import IdSet, StackItem, UndoManager
49
+ from ._update import get_state, get_update, merge_updates
50
+ from ._xml import XmlElement, XmlEvent, XmlFragment, XmlText
51
+
52
+ # pycrdt calls the encoded delete set a DeleteSet in older releases and an IdSet in newer ones.
53
+ DeleteSet = IdSet
54
+
55
+ __all__ = [
56
+ "Array",
57
+ "ArrayEvent",
58
+ "Assoc",
59
+ "AttrRange",
60
+ "Awareness",
61
+ "Channel",
62
+ "ContentAttribute",
63
+ "Decoder",
64
+ "DeleteSet",
65
+ "Doc",
66
+ "Encoder",
67
+ "IdMap",
68
+ "IdSet",
69
+ "Map",
70
+ "MapEvent",
71
+ "NewTransaction",
72
+ "Provider",
73
+ "ReadTransaction",
74
+ "Snapshot",
75
+ "StackItem",
76
+ "StickyIndex",
77
+ "SubdocsEvent",
78
+ "Subscription",
79
+ "Text",
80
+ "TextEvent",
81
+ "Transaction",
82
+ "TransactionEvent",
83
+ "Typed",
84
+ "TypedArray",
85
+ "TypedDoc",
86
+ "TypedMap",
87
+ "UndoManager",
88
+ "UnsubscribableStream",
89
+ "XmlElement",
90
+ "XmlEvent",
91
+ "XmlFragment",
92
+ "XmlText",
93
+ "YMessageType",
94
+ "YSyncMessageType",
95
+ "create_awareness_message",
96
+ "create_message",
97
+ "create_sync_message",
98
+ "create_sync_step1_message",
99
+ "create_sync_step2_message",
100
+ "create_update_message",
101
+ "handle_sync_message",
102
+ "is_awareness_disconnect_message",
103
+ "read_message",
104
+ "write_message",
105
+ "write_var_uint",
106
+ "get_state",
107
+ "get_update",
108
+ "merge_updates",
109
+ ]
110
+ __version__ = "0.1.0"
ycpp/_array.py ADDED
@@ -0,0 +1,318 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Generic, TypeVar
4
+
5
+ from . import _ycpp
6
+ from ._event import Subscription, arg_count
7
+ from ._map import _ARRAY, _DOC, _MAP, _MISSING, _TEXT, _VALUE, Map, _subdoc_class
8
+ from ._sticky_index import Assoc, StickyIndex
9
+ from ._stream import EventStreams
10
+ from ._text import Text
11
+ from ._xml import XmlFragment, _is_fragment
12
+
13
+ T = TypeVar("T")
14
+
15
+
16
+ def _nested(value) -> bool:
17
+ return isinstance(value, (Map, Text, Array))
18
+
19
+
20
+ def _container(value) -> bool:
21
+ """A value the list stores as one element of its own, not as a plain value."""
22
+ return _nested(value) or _is_fragment(value) or isinstance(value, _subdoc_class())
23
+
24
+
25
+ def _replay(doc, ref, item, index: int) -> bool:
26
+ """Insert one preliminary container or subdocument; False when the item is a plain value."""
27
+ if isinstance(item, Map):
28
+ item._integrate(doc, ref.insert_map(index))
29
+ elif isinstance(item, Text):
30
+ item._integrate(doc, ref.insert_text(index))
31
+ elif isinstance(item, Array):
32
+ item._integrate(doc, ref.insert_array(index))
33
+ elif _is_fragment(item):
34
+ item._integrate(doc, ref.insert_xml_fragment(index))
35
+ item._init()
36
+ elif isinstance(item, _subdoc_class()):
37
+ ref.insert_doc(index, item._doc)
38
+ else:
39
+ return False
40
+ return True
41
+
42
+
43
+ class Array(EventStreams, Generic[T]):
44
+ """A shared list, shaped like pycrdt's Array."""
45
+
46
+ def __init__(self, init=None, *, _doc=None, _integrated=None) -> None:
47
+ self._doc = _doc
48
+ self._prelim = None if _integrated is not None else init
49
+ self._ref = _integrated
50
+ self._subscriptions = []
51
+ self._init_event_streams()
52
+
53
+ def _integrate(self, doc, ref) -> None:
54
+ prelim, self._prelim = self._prelim, None
55
+ self._doc = doc
56
+ self._ref = ref
57
+ if not prelim:
58
+ return
59
+ with doc.transaction():
60
+ for position, item in enumerate(prelim):
61
+ if not _replay(doc, ref, item, position):
62
+ ref.insert(position, [item])
63
+
64
+ @property
65
+ def doc(self):
66
+ if self._doc is None:
67
+ raise RuntimeError("Not integrated in a document yet")
68
+ return self._doc
69
+
70
+ @property
71
+ def integrated(self):
72
+ if self._ref is None:
73
+ raise RuntimeError("Not integrated in a document yet")
74
+ return self._ref
75
+
76
+ @property
77
+ def is_prelim(self) -> bool:
78
+ return self._prelim is not None
79
+
80
+ @property
81
+ def is_integrated(self) -> bool:
82
+ return self._ref is not None
83
+
84
+ @property
85
+ def prelim(self):
86
+ return self._prelim
87
+
88
+ @property
89
+ def type_name(self) -> str:
90
+ return "array"
91
+
92
+ def _value_at(self, index: int):
93
+ """The element at ``index``: a plain value, or a live wrapper for a nested type."""
94
+ fragment = self.integrated.child_xml_fragment(index)
95
+ if fragment.connected():
96
+ return XmlFragment(_doc=self._doc, _integrated=fragment)
97
+ kind, value = self.integrated.lookup(index)
98
+ if kind == _VALUE:
99
+ return value
100
+ if kind == _MISSING:
101
+ return None
102
+ if kind == _MAP:
103
+ return Map(_doc=self._doc, _integrated=value)
104
+ if kind == _TEXT:
105
+ return Text(_doc=self._doc, _integrated=value)
106
+ if kind == _DOC:
107
+ return _subdoc_class()._wrapped(value)
108
+ return Array(_doc=self._doc, _integrated=value)
109
+
110
+ def _child(self, index: int):
111
+ value = self._value_at(index)
112
+ return value if isinstance(value, (Map, Text, Array)) else None
113
+
114
+ def to_py(self):
115
+ if self._ref is None:
116
+ return self._prelim
117
+ values = []
118
+ for index in range(len(self._ref)):
119
+ value = self._value_at(index)
120
+ values.append(
121
+ value.to_py() if isinstance(value, (Map, Text, Array)) else value
122
+ )
123
+ return values
124
+
125
+ def insert(self, index: int, value) -> None:
126
+ """Insert one item, like pycrdt: `insert(i, [1, 2])` stores a list as one element."""
127
+ doc = self.doc
128
+ try:
129
+ if _container(value):
130
+ doc_ref = self._ref
131
+ if _nested(value) and value.is_integrated:
132
+ raise ValueError(
133
+ "cannot insert a container that is already in a document"
134
+ )
135
+ _replay(doc, doc_ref, value, min(index, len(self)))
136
+ else:
137
+ self._ref.insert_one(index, value)
138
+ finally:
139
+ doc._raise_observer_errors()
140
+
141
+ def append(self, value) -> None:
142
+ if _container(value):
143
+ self.insert(len(self), value)
144
+ return
145
+ doc = self.doc
146
+ try:
147
+ self._ref.append_one(value)
148
+ finally:
149
+ doc._raise_observer_errors()
150
+
151
+ def clear(self) -> None:
152
+ del self[:]
153
+
154
+ def extend(self, values) -> None:
155
+ doc = self.doc
156
+ items = list(values)
157
+ try:
158
+ if not items:
159
+ return
160
+ if any(_container(item) for item in items):
161
+ for offset, item in enumerate(items):
162
+ self.insert(len(self) + offset, item)
163
+ else:
164
+ self._ref.insert(len(self), items)
165
+ finally:
166
+ doc._raise_observer_errors()
167
+
168
+ def __iadd__(self, values):
169
+ self.extend(values)
170
+ return self
171
+
172
+ def __add__(self, values):
173
+ if not isinstance(values, list):
174
+ return NotImplemented
175
+ self.extend(values)
176
+ return self
177
+
178
+ def __radd__(self, values):
179
+ if not isinstance(values, list):
180
+ return NotImplemented
181
+ for offset, item in enumerate(values):
182
+ self._insert_at(offset, item)
183
+ return self
184
+
185
+ def pop(self, index: int = -1):
186
+ doc = self.doc
187
+ try:
188
+ index = self._check_index(index)
189
+ value = self[index]
190
+ if isinstance(value, (Map, Text, Array)):
191
+ value = value.to_py()
192
+ del self[index]
193
+ return value
194
+ finally:
195
+ doc._raise_observer_errors()
196
+
197
+ def _check_index(self, index: int) -> int:
198
+ if not isinstance(index, int):
199
+ raise RuntimeError("Index must be of type integer")
200
+ length = len(self)
201
+ if index < 0:
202
+ index += length
203
+ if index < 0 or index >= length:
204
+ raise IndexError("Array index out of range")
205
+ return index
206
+
207
+ def _insert_at(self, position: int, item) -> None:
208
+ if not _replay(self.doc, self._ref, item, position):
209
+ self._ref.insert_one(position, item)
210
+
211
+ def __len__(self) -> int:
212
+ return len(self.integrated)
213
+
214
+ def __getitem__(self, index):
215
+ length = len(self)
216
+ if isinstance(index, slice):
217
+ start, stop, step = index.indices(length)
218
+ return [self._value_at(position) for position in range(start, stop, step)]
219
+ if not isinstance(index, int):
220
+ raise RuntimeError("Index must be of type integer")
221
+ return self._value_at(self._check_index(index))
222
+
223
+ def __setitem__(self, index, value) -> None:
224
+ doc = self.doc
225
+ try:
226
+ if isinstance(index, int):
227
+ position = self._check_index(index)
228
+ self._ref.erase(position, 1)
229
+ self._insert_at(position, value)
230
+ elif isinstance(index, slice):
231
+ if index.step is not None:
232
+ raise RuntimeError("Step not supported")
233
+ if index.start != index.stop:
234
+ raise RuntimeError("Start and stop must be equal")
235
+ if index.start > len(self) or index.start < 0:
236
+ raise RuntimeError("Index out of range")
237
+ for offset, item in enumerate(value):
238
+ self._insert_at(index.start + offset, item)
239
+ else:
240
+ raise RuntimeError("Index must be of type integer")
241
+ finally:
242
+ doc._raise_observer_errors()
243
+
244
+ def _replace(self, start: int, stop: int, values) -> None:
245
+ if stop > start:
246
+ self._ref.erase(start, stop - start)
247
+ for offset, item in enumerate(values):
248
+ self._insert_at(start + offset, item)
249
+
250
+ def __delitem__(self, index) -> None:
251
+ doc = self.doc
252
+ try:
253
+ if isinstance(index, int):
254
+ self._ref.erase(self._check_index(index), 1)
255
+ elif isinstance(index, slice):
256
+ if index.step is not None:
257
+ raise RuntimeError("Step not supported")
258
+ if index.start is None:
259
+ start = 0
260
+ elif index.start < 0:
261
+ raise RuntimeError("Negative start not supported")
262
+ else:
263
+ start = index.start
264
+ if index.stop is None:
265
+ length = len(self) - start
266
+ elif index.stop < 0:
267
+ raise RuntimeError("Negative stop not supported")
268
+ else:
269
+ length = index.stop - start
270
+ if length > 0:
271
+ self._ref.erase(start, length)
272
+ else:
273
+ raise TypeError(
274
+ f"Array indices must be integers or slices, not {type(index).__name__}"
275
+ )
276
+ finally:
277
+ doc._raise_observer_errors()
278
+
279
+ def __contains__(self, item) -> bool:
280
+ return item in list(self)
281
+
282
+ def __iter__(self):
283
+ for index in range(len(self)):
284
+ yield self[index]
285
+
286
+ def observe(self, callback) -> Subscription:
287
+ observer = self.doc._observe_array(self.integrated)
288
+ subscription = Subscription(self.doc, observer)
289
+ self._doc._array_observers[observer] = (self, callback, arg_count(callback))
290
+ self._subscriptions.append(subscription)
291
+ return subscription
292
+
293
+ def observe_deep(self, callback) -> Subscription:
294
+ observer = self.doc._observe_deep_array(self.integrated)
295
+ subscription = Subscription(self.doc, observer)
296
+ self._doc._deep_observers[observer] = (callback, arg_count(callback))
297
+ self._subscriptions.append(subscription)
298
+ return subscription
299
+
300
+ def sticky_index(self, index: int, assoc: Assoc = Assoc.AFTER) -> StickyIndex:
301
+ return StickyIndex.new(self, index, assoc)
302
+
303
+ def unobserve(self, subscription) -> None:
304
+ self._subscriptions.remove(subscription)
305
+ subscription.drop()
306
+
307
+ def __eq__(self, other) -> bool:
308
+ if isinstance(other, Array):
309
+ return self.to_py() == other.to_py()
310
+ if isinstance(other, list):
311
+ return self.to_py() == other
312
+ return NotImplemented
313
+
314
+ def __str__(self) -> str:
315
+ return str(self.integrated.to_json())
316
+
317
+ def __repr__(self) -> str:
318
+ return f"Array({self.to_py()!r})"
ycpp/_awareness.py ADDED
@@ -0,0 +1,268 @@
1
+ """The y-protocols awareness layer, as pycrdt 0.14.13's _awareness.py. Clocks only ever move
2
+ forward: a state with a clock at or below the one already held is ignored."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ import json
8
+ import threading
9
+ from time import time
10
+ from typing import Any, Callable, Literal, cast, TYPE_CHECKING
11
+ from uuid import uuid4
12
+
13
+ from anyio import TASK_STATUS_IGNORED, create_task_group, sleep
14
+ from anyio.abc import TaskGroup, TaskStatus
15
+
16
+ from ._sync import Decoder, Encoder
17
+
18
+ if TYPE_CHECKING:
19
+ from ._doc import Doc
20
+
21
+
22
+ class Awareness:
23
+ """The states a set of clients publishes, with the clock and timestamp kept per client."""
24
+
25
+ client_id: int
26
+ _meta: dict[int, dict[str, Any]]
27
+ _states: dict[int, dict[str, Any]]
28
+ _subscriptions: dict[str, Callable[[str, tuple[dict[str, Any], Any]], None]]
29
+ _subscriptions_lock: threading.Lock
30
+ _task_group: TaskGroup | None
31
+
32
+ def __init__(self, ydoc: Doc, *, outdated_timeout: int = 30000) -> None:
33
+ if outdated_timeout <= 0:
34
+ raise ValueError("outdated_timeout must be positive")
35
+ self.client_id = ydoc.client_id
36
+ self._outdated_timeout = outdated_timeout
37
+ self._meta = {}
38
+ self._states = {}
39
+ self._subscriptions = {}
40
+ self._subscriptions_lock = threading.Lock()
41
+ self._task_group = None
42
+ self.set_local_state({})
43
+
44
+ @property
45
+ def meta(self) -> dict[int, dict[str, Any]]:
46
+ """The clients' metadata."""
47
+ return self._meta
48
+
49
+ @property
50
+ def states(self) -> dict[int, dict[str, Any]]:
51
+ """The client states."""
52
+ return self._states
53
+
54
+ def _emit(
55
+ self,
56
+ topic: Literal["change", "update"],
57
+ added: list[int],
58
+ updated: list[int],
59
+ removed: list[int],
60
+ origin: Any,
61
+ ) -> None:
62
+ with self._subscriptions_lock:
63
+ callbacks = tuple(self._subscriptions.values())
64
+ for callback in callbacks:
65
+ callback(
66
+ topic,
67
+ ({"added": added, "updated": updated, "removed": removed}, origin),
68
+ )
69
+
70
+ def _get_time(self) -> int:
71
+ return int(time() * 1000)
72
+
73
+ async def start(
74
+ self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED
75
+ ) -> None:
76
+ """Starts updating the awareness periodically."""
77
+ if self._task_group is not None:
78
+ raise RuntimeError("Awareness already started")
79
+
80
+ async with create_task_group() as tg:
81
+ self._task_group = tg
82
+ task_status.started()
83
+ tg.start_soon(self._start)
84
+
85
+ async def _start(self) -> None:
86
+ while True:
87
+ await sleep(self._outdated_timeout / 1000 / 10)
88
+ now = self._get_time()
89
+ if (
90
+ self.get_local_state() is not None
91
+ and self._outdated_timeout / 2
92
+ <= now - self._meta[self.client_id]["lastUpdated"]
93
+ ):
94
+ self.set_local_state(self.get_local_state())
95
+ remove: list[int] = []
96
+ for client_id, meta in self._meta.items():
97
+ if (
98
+ client_id != self.client_id
99
+ and self._outdated_timeout <= now - meta["lastUpdated"]
100
+ and client_id in self._states
101
+ ):
102
+ remove.append(client_id)
103
+ if remove:
104
+ self.remove_awareness_states(remove, "timeout")
105
+
106
+ async def stop(self) -> None:
107
+ """Stops updating the awareness periodically."""
108
+ if self._task_group is None:
109
+ raise RuntimeError("Awareness not started")
110
+ self._task_group.cancel_scope.cancel()
111
+ self._task_group = None
112
+
113
+ def get_local_state(self) -> dict[str, Any] | None:
114
+ """Returns the local state, if any."""
115
+ return self._states.get(self.client_id)
116
+
117
+ def set_local_state(self, state: dict[str, Any] | None) -> None:
118
+ """Updates the local state and meta, and reports the change to subscribers."""
119
+ client_id = self.client_id
120
+ curr_local_meta = self._meta.get(client_id)
121
+ clock = 0 if curr_local_meta is None else curr_local_meta["clock"] + 1
122
+ prev_state = self._states.get(client_id)
123
+ if prev_state is not None:
124
+ prev_state = copy.deepcopy(prev_state)
125
+ if state is None:
126
+ if client_id in self._states:
127
+ del self._states[client_id]
128
+ else:
129
+ self._states[client_id] = state
130
+ timestamp = self._get_time()
131
+ self._meta[client_id] = {"clock": clock, "lastUpdated": timestamp}
132
+ added = []
133
+ updated = []
134
+ filtered_updated = []
135
+ removed = []
136
+ if state is None:
137
+ removed.append(client_id)
138
+ elif prev_state is None:
139
+ added.append(client_id)
140
+ else:
141
+ updated.append(client_id)
142
+ if prev_state != state:
143
+ filtered_updated.append(client_id)
144
+ if added or filtered_updated or removed:
145
+ self._emit("change", added, filtered_updated, removed, "local")
146
+ self._emit("update", added, updated, removed, "local")
147
+
148
+ def set_local_state_field(self, field: str, value: Any) -> None:
149
+ """Sets a local state field, if there is a local state."""
150
+ state = self.get_local_state()
151
+ if state is not None:
152
+ state = copy.deepcopy(state)
153
+ state[field] = value
154
+ self.set_local_state(state)
155
+
156
+ def remove_awareness_states(self, client_ids: list[int], origin: Any) -> None:
157
+ """Removes the states of the given clients, if they have one."""
158
+ removed = []
159
+ for client_id in client_ids:
160
+ if client_id in self._states:
161
+ del self._states[client_id]
162
+ if client_id == self.client_id:
163
+ cur_meta = self._meta[client_id]
164
+ self._meta[client_id] = {
165
+ "clock": cur_meta["clock"] + 1,
166
+ "lastUpdated": self._get_time(),
167
+ }
168
+ removed.append(client_id)
169
+ if removed:
170
+ self._emit("change", [], [], removed, origin)
171
+ self._emit("update", [], [], removed, origin)
172
+
173
+ def encode_awareness_update(self, client_ids: list[int]) -> bytes:
174
+ """Creates an encoded awareness update of the clients given by their IDs."""
175
+ encoder = Encoder()
176
+ encoder.write_var_uint(len(client_ids))
177
+ for client_id in client_ids:
178
+ state = self._states.get(client_id)
179
+ clock = cast(int, self._meta.get(client_id, {}).get("clock"))
180
+ encoder.write_var_uint(client_id)
181
+ encoder.write_var_uint(clock)
182
+ encoder.write_var_string(json.dumps(state, separators=(",", ":")))
183
+ return encoder.to_bytes()
184
+
185
+ def apply_awareness_update(self, update: bytes, origin: Any) -> None:
186
+ """Applies the binary update and notifies subscribers with changes."""
187
+ # Decoded whole first: one malformed entry refuses the update instead of applying its prefix,
188
+ # and an empty state string is malformed (JSON.parse("") throws) rather than a removal.
189
+ entries = []
190
+ decoder = Decoder(update)
191
+ length = decoder.read_var_uint()
192
+ for _ in range(length):
193
+ client_id = decoder.read_var_uint()
194
+ clock = decoder.read_var_uint()
195
+ state_str = decoder.read_var_string()
196
+ if not state_str:
197
+ raise ValueError("Y protocol error: empty awareness state")
198
+ entries.append((client_id, clock, json.loads(state_str)))
199
+
200
+ timestamp = self._get_time()
201
+ added = []
202
+ updated = []
203
+ filtered_updated = []
204
+ removed = []
205
+ for client_id, clock, state in entries:
206
+ client_meta = self._meta.get(client_id)
207
+ prev_state = self._states.get(client_id)
208
+ curr_clock = 0 if client_meta is None else client_meta["clock"]
209
+ if curr_clock < clock or (
210
+ curr_clock == clock and state is None and client_id in self._states
211
+ ):
212
+ if state is None:
213
+ # Never let a remote client remove this local state: bump the clock instead, so
214
+ # the peers learn that this client still exists.
215
+ if (
216
+ client_id == self.client_id
217
+ and self.get_local_state() is not None
218
+ ):
219
+ clock += 1
220
+ elif client_id in self._states:
221
+ del self._states[client_id]
222
+ else:
223
+ self._states[client_id] = state
224
+ self._meta[client_id] = {"clock": clock, "lastUpdated": timestamp}
225
+ if client_meta is None and state is not None:
226
+ added.append(client_id)
227
+ elif client_meta is not None and state is None:
228
+ removed.append(client_id)
229
+ elif state is not None:
230
+ if state != prev_state:
231
+ filtered_updated.append(client_id)
232
+ updated.append(client_id)
233
+ if added or filtered_updated or removed:
234
+ self._emit("change", added, filtered_updated, removed, origin)
235
+ if added or updated or removed:
236
+ self._emit("update", added, updated, removed, origin)
237
+
238
+ def observe(
239
+ self, callback: Callable[[str, tuple[dict[str, Any], Any]], None]
240
+ ) -> str:
241
+ """Registers the given callback to awareness changes."""
242
+ id = str(uuid4())
243
+ with self._subscriptions_lock:
244
+ self._subscriptions[id] = callback
245
+ return id
246
+
247
+ def unobserve(self, id: str) -> None:
248
+ """Unregisters the given subscription ID from awareness changes."""
249
+ with self._subscriptions_lock:
250
+ del self._subscriptions[id]
251
+
252
+
253
+ def is_awareness_disconnect_message(message: bytes) -> bool:
254
+ """Whether the message body is exactly one length-prefixed awareness entry and that entry
255
+ removes its state."""
256
+ try:
257
+ decoder = Decoder(message)
258
+ payload = decoder.read_message()
259
+ if payload is None or decoder.length != 0:
260
+ return False
261
+ inner = Decoder(payload)
262
+ if inner.read_var_uint() != 1:
263
+ return False
264
+ inner.read_var_uint()
265
+ inner.read_var_uint()
266
+ return inner.read_var_string() == "null" and inner.length == 0
267
+ except RuntimeError:
268
+ return False