PyEventEngine 0.6.2__cp315-cp315t-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 (56) hide show
  1. event_engine/__infra__.pxd +2 -0
  2. event_engine/__init__.pxd +2 -0
  3. event_engine/__init__.py +62 -0
  4. event_engine/base/__infra__.pxd +9 -0
  5. event_engine/base/__init__.pxd +9 -0
  6. event_engine/base/__init__.py +31 -0
  7. event_engine/base/c_allocator_protocol.c +14310 -0
  8. event_engine/base/c_allocator_protocol.cp315t-win_amd64.pyd +0 -0
  9. event_engine/base/c_allocator_protocol.h +23 -0
  10. event_engine/base/c_allocator_protocol.pxd +31 -0
  11. event_engine/base/c_allocator_protocol.pyx +193 -0
  12. event_engine/capi/__infra__.pxd +189 -0
  13. event_engine/capi/__init__.pxd +189 -0
  14. event_engine/capi/__init__.py +84 -0
  15. event_engine/capi/c_engine.c +32542 -0
  16. event_engine/capi/c_engine.cp315t-win_amd64.pyd +0 -0
  17. event_engine/capi/c_engine.h +393 -0
  18. event_engine/capi/c_engine.pxd +84 -0
  19. event_engine/capi/c_engine.pyi +478 -0
  20. event_engine/capi/c_engine.pyx +673 -0
  21. event_engine/capi/c_event.c +22826 -0
  22. event_engine/capi/c_event.cp315t-win_amd64.pyd +0 -0
  23. event_engine/capi/c_event.h +342 -0
  24. event_engine/capi/c_event.pxd +159 -0
  25. event_engine/capi/c_event.pyi +265 -0
  26. event_engine/capi/c_event.pyx +444 -0
  27. event_engine/capi/c_topic.c +34545 -0
  28. event_engine/capi/c_topic.cp315t-win_amd64.pyd +0 -0
  29. event_engine/capi/c_topic.h +1007 -0
  30. event_engine/capi/c_topic.pxd +147 -0
  31. event_engine/capi/c_topic.pyi +644 -0
  32. event_engine/capi/c_topic.pyx +818 -0
  33. event_engine/capi/fallback_engine.py +707 -0
  34. event_engine/config_view.c +10271 -0
  35. event_engine/config_view.cp315t-win_amd64.pyd +0 -0
  36. event_engine/config_view.pyx +55 -0
  37. event_engine/includes/event_engine/base/c_allocator_protocol.c +14310 -0
  38. event_engine/includes/event_engine/base/c_allocator_protocol.h +23 -0
  39. event_engine/includes/event_engine/capi/c_engine.c +32542 -0
  40. event_engine/includes/event_engine/capi/c_engine.h +393 -0
  41. event_engine/includes/event_engine/capi/c_event.c +22826 -0
  42. event_engine/includes/event_engine/capi/c_event.h +342 -0
  43. event_engine/includes/event_engine/capi/c_topic.c +34545 -0
  44. event_engine/includes/event_engine/capi/c_topic.h +1007 -0
  45. event_engine/includes/event_engine/config_view.c +10271 -0
  46. event_engine/native/__init__.py +60 -0
  47. event_engine/native/_event.py +420 -0
  48. event_engine/native/_topic.py +171 -0
  49. event_engine/native/engine.py +793 -0
  50. event_engine/native/event.py +469 -0
  51. event_engine/native/topic.py +943 -0
  52. pyeventengine-0.6.2.dist-info/METADATA +189 -0
  53. pyeventengine-0.6.2.dist-info/RECORD +56 -0
  54. pyeventengine-0.6.2.dist-info/WHEEL +5 -0
  55. pyeventengine-0.6.2.dist-info/licenses/LICENSE +21 -0
  56. pyeventengine-0.6.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,943 @@
1
+ """
2
+ Native Python fallback implementation for PyTopic and related classes.
3
+
4
+ This module provides a pure Python implementation that mimics the behavior of the
5
+ Cython-based c_topic module. It is used as a fallback when the Cython extension
6
+ cannot be compiled (e.g., due to lack of Cython, GCC, or Clang).
7
+
8
+ The API is designed to match event_engine.capi.c_topic as closely as possible.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import enum
14
+ import re
15
+ from collections import deque
16
+ from collections.abc import Iterable, Iterator
17
+ from functools import cached_property
18
+ from typing import Any, TypedDict, overload
19
+
20
+ # Global internal map for topic internalization
21
+ _GLOBAL_INTERNAL_MAP: dict[str, PyTopic] = {}
22
+ _GLOBAL_ALLOCATOR = None
23
+
24
+ # Topic parsing configuration (matching C defaults)
25
+ DEFAULT_TOPIC_SEP = '.'
26
+ DEFAULT_OPTION_SEP = '|'
27
+ DEFAULT_RANGE_BRACKETS = "()"
28
+ DEFAULT_WILDCARD_BRACKETS = "{}"
29
+ DEFAULT_WILDCARD_MARKER = '+'
30
+ DEFAULT_PATTERN_DELIM = '/'
31
+
32
+
33
+ def init_internal_map(default_capacity: int = 1024) -> dict[str, PyTopic]:
34
+ """Initialize or return a shared internal byte map.
35
+
36
+ Args:
37
+ default_capacity: Default capacity (in bytes) used when creating the internal map.
38
+
39
+ Returns:
40
+ A ByteMap instance wrapping the shared internal bytemap.
41
+ """
42
+ global _GLOBAL_INTERNAL_MAP
43
+ # In pure Python, we just use a dict, so capacity is ignored
44
+ return _GLOBAL_INTERNAL_MAP
45
+
46
+
47
+ def clear_internal_map() -> None:
48
+ """Clear and free the shared internal bytemap.
49
+
50
+ This releases the internal resources and resets any cached references.
51
+ """
52
+ global _GLOBAL_INTERNAL_MAP
53
+ _GLOBAL_INTERNAL_MAP.clear()
54
+
55
+
56
+ def get_internal_topic(key: str, owner: bool = False) -> PyTopic | None:
57
+ """Get a registered topic from the internal map, if there is any.
58
+
59
+ Args:
60
+ key: the literal of the topic to look up.
61
+ owner: whether to return a copy (True) or the original reference (False).
62
+ In pure Python, ownership is always with the object itself.
63
+
64
+ Returns:
65
+ PyTopic instance if found or None.
66
+ """
67
+ global _GLOBAL_INTERNAL_MAP
68
+ topic = _GLOBAL_INTERNAL_MAP.get(key)
69
+ if topic is None:
70
+ return None
71
+
72
+ # Return a copy if owner is True, otherwise return reference
73
+ if owner:
74
+ new_topic = PyTopic.__new__(PyTopic)
75
+ new_topic._parts = list(topic._parts)
76
+ new_topic._value = topic._value
77
+ new_topic._hash = topic._hash
78
+ new_topic._is_exact = topic._is_exact
79
+ return new_topic
80
+
81
+ return topic
82
+
83
+
84
+ def get_internal_map() -> dict[str, PyTopic]:
85
+ """Return a dictionary view of the internal topic map.
86
+
87
+ Returns:
88
+ A dictionary mapping topic literal strings to PyTopic instances.
89
+ """
90
+ global _GLOBAL_INTERNAL_MAP
91
+ return _GLOBAL_INTERNAL_MAP.copy()
92
+
93
+
94
+ def init_allocator(init_capacity: int = 4096, with_shm: bool = False) -> None:
95
+ """Initialize or return the global Allocator.
96
+
97
+ Args:
98
+ init_capacity: Initial capacity (in bytes) for the allocator.
99
+ (Ignored in pure Python implementation)
100
+ with_shm: If True, create an allocator backed by shared memory.
101
+ (Ignored in pure Python implementation)
102
+
103
+ Returns:
104
+ None (allocator not used in pure Python implementation)
105
+
106
+ Note:
107
+ This function is provided for API compatibility with the Cython version,
108
+ but does nothing in the pure Python implementation.
109
+ """
110
+ # No-op in pure Python - allocators are not needed
111
+ pass
112
+
113
+
114
+ class PyTopicType(enum.IntEnum):
115
+ """Enumeration of topic part types.
116
+
117
+ Maps to the underlying C-level TopicType constants.
118
+ """
119
+ TOPIC_PART_EXACT = 0
120
+ TOPIC_PART_ANY = 1
121
+ TOPIC_PART_RANGE = 2
122
+ TOPIC_PART_PATTERN = 3
123
+
124
+
125
+ class PyTopicPart:
126
+ """Base Python wrapper for a single topic part.
127
+
128
+ In the native Python implementation, all topic parts own their underlying memory.
129
+ """
130
+
131
+ __slots__ = ('_next', '_ttype')
132
+
133
+ def __init__(self, *args: Any, alloc: bool = False, **kwargs: Any) -> None:
134
+ """Create or attach to a topic part.
135
+
136
+ Args:
137
+ alloc: If True, allocate and initialize internal structures.
138
+ """
139
+ self._next: PyTopicPart | None = None
140
+ self._ttype: PyTopicType = PyTopicType.TOPIC_PART_EXACT
141
+
142
+ def next(self) -> PyTopicPart:
143
+ """Return the next topic part.
144
+
145
+ Returns:
146
+ The next PyTopicPart instance.
147
+
148
+ Raises:
149
+ StopIteration: If this is the last part.
150
+ """
151
+ if self._next is None:
152
+ raise StopIteration
153
+ return self._next
154
+
155
+ @property
156
+ def owner(self) -> bool:
157
+ """bool: Whether this Python object owns the underlying memory (always True in native Python)."""
158
+ return True
159
+
160
+ @property
161
+ def ttype(self) -> PyTopicType:
162
+ """int: The topic part type as a PyTopicType."""
163
+ return self._ttype
164
+
165
+ @property
166
+ def addr(self) -> int:
167
+ """int: Numeric address / id of the underlying C structure."""
168
+ return id(self)
169
+
170
+
171
+ class PyTopicPartExact(PyTopicPart):
172
+ """Topic part representing an exact literal segment."""
173
+
174
+ __slots__ = ('_part',)
175
+
176
+ def __init__(self, part: str = None, *args: Any, alloc: bool = False, **kwargs: Any) -> None:
177
+ """Create an exact topic part.
178
+
179
+ Args:
180
+ part: Literal string to store. If omitted and alloc is True, an empty initialized part is created.
181
+ alloc: If True, allocate underlying structures.
182
+ """
183
+ super().__init__(*args, alloc=alloc, **kwargs)
184
+ self._ttype = PyTopicType.TOPIC_PART_EXACT
185
+ self._part: str = part if part is not None else ""
186
+
187
+ def __repr__(self) -> str:
188
+ """Return human-readable representation."""
189
+ return f'<TopicPartExact>(topic="{self.part}")'
190
+
191
+ def __len__(self) -> int:
192
+ """Return the length of the stored literal in bytes."""
193
+ return len(self._part.encode('utf-8'))
194
+
195
+ @property
196
+ def part(self) -> str:
197
+ """The literal string value for this part."""
198
+ return self._part
199
+
200
+
201
+ class PyTopicPartAny(PyTopicPart):
202
+ """Topic part representing a named wildcard."""
203
+
204
+ __slots__ = ('_name',)
205
+
206
+ def __init__(self, name: str = None, *args: Any, alloc: bool = False, **kwargs: Any) -> None:
207
+ """Create an 'any' topic part.
208
+
209
+ Args:
210
+ name: Optional name for the wildcard.
211
+ alloc: If True, allocate underlying structures.
212
+ """
213
+ super().__init__(*args, alloc=alloc, **kwargs)
214
+ self._ttype = PyTopicType.TOPIC_PART_ANY
215
+ self._name: str = name if name is not None else ""
216
+
217
+ def __repr__(self) -> str:
218
+ """Return human-readable representation."""
219
+ return f'<TopicPartAny>(name="{self.name}")'
220
+
221
+ @property
222
+ def name(self) -> str:
223
+ """The wildcard name (identifier)."""
224
+ return self._name
225
+
226
+
227
+ class PyTopicPartRange(PyTopicPart):
228
+ """Topic part representing a range (choice) among multiple literals."""
229
+
230
+ __slots__ = ('_options',)
231
+
232
+ def __init__(self, options: list[str] = None, *args: Any, alloc: bool = False, **kwargs: Any) -> None:
233
+ """Create a range part.
234
+
235
+ Args:
236
+ options: List of literal option strings.
237
+ alloc: If True, allocate underlying structures.
238
+ """
239
+ super().__init__(*args, alloc=alloc, **kwargs)
240
+ self._ttype = PyTopicType.TOPIC_PART_RANGE
241
+ self._options: list[str] = options if options is not None else []
242
+
243
+ def __repr__(self) -> str:
244
+ """Return human-readable representation."""
245
+ return f'<TopicPartRange>(n={len(self._options)}, options={self._options})'
246
+
247
+ def __len__(self) -> int:
248
+ """Return the number of options."""
249
+ return len(self._options)
250
+
251
+ def __iter__(self) -> Iterator[str]:
252
+ """Iterate over option strings."""
253
+ return iter(self._options)
254
+
255
+ def options(self) -> Iterator[str]:
256
+ """Yield option strings in order.
257
+
258
+ Yields:
259
+ Each option as a Python string.
260
+ """
261
+ return iter(self._options)
262
+
263
+
264
+ class PyTopicPartPattern(PyTopicPart):
265
+ """Topic part representing a regex pattern."""
266
+
267
+ __slots__ = ('_pattern', '_compiled_regex')
268
+
269
+ def __init__(self, regex: str = None, *args: Any, alloc: bool = False, **kwargs: Any) -> None:
270
+ """Create a pattern topic part.
271
+
272
+ Args:
273
+ regex: Regular expression string.
274
+ alloc: If True, allocate underlying structures.
275
+ """
276
+ super().__init__(*args, alloc=alloc, **kwargs)
277
+ self._ttype = PyTopicType.TOPIC_PART_PATTERN
278
+ self._pattern: str = regex if regex is not None else ""
279
+ self._compiled_regex: re.Pattern | None = None
280
+
281
+ def __repr__(self) -> str:
282
+ """Return human-readable representation."""
283
+ return f'<TopicPartPattern>(regex="{self.pattern}")'
284
+
285
+ @property
286
+ def pattern(self) -> str:
287
+ """str: The raw regex pattern string."""
288
+ return self._pattern
289
+
290
+ @property
291
+ def regex(self) -> re.Pattern:
292
+ """re.Pattern: Compiled regex object for the pattern."""
293
+ if self._compiled_regex is None:
294
+ self._compiled_regex = re.compile(self._pattern)
295
+ return self._compiled_regex
296
+
297
+
298
+ class TopicMatchNode(TypedDict):
299
+ """TypedDict describing a single match node returned by PyTopicMatchResult accessors.
300
+
301
+ Keys:
302
+ matched: Whether this node matched.
303
+ part_a: The left-side topic part (or None).
304
+ part_b: The right-side topic part (or None).
305
+ literal: The literal string associated with this node (if any).
306
+ """
307
+ matched: bool
308
+ part_a: PyTopicPart | None
309
+ part_b: PyTopicPart | None
310
+ literal: str | None
311
+
312
+
313
+ class PyTopicMatchResult:
314
+ """Container for topic part match results (linked list-like).
315
+
316
+ Provides iteration and indexing over match nodes and utilities to convert results.
317
+
318
+ The public API yields `TopicMatchNode` entries for per-node accessors.
319
+ """
320
+
321
+ def __init__(self, n_parts: int = 0, alloc: bool = False, allocator: Any = None, **kwargs: Any) -> None:
322
+ """Allocate or attach a chain of match result nodes.
323
+
324
+ Args:
325
+ n_parts: Number of nodes to pre-create.
326
+ alloc: If True, allocate underlying structures.
327
+ allocator: Optional Allocator (ignored in pure Python implementation).
328
+ """
329
+ self._nodes: deque[TopicMatchNode] = deque()
330
+ if alloc and n_parts > 0:
331
+ for _ in range(n_parts):
332
+ self._nodes.append({'matched': False, 'part_a': None, 'part_b': None, 'literal': None})
333
+
334
+ def __repr__(self) -> str:
335
+ """Return a compact representation with success/failure and length."""
336
+ status = "success" if self.matched else "failed"
337
+ return f'<TopicPartMatchResult {status}>(nodes={self.length})'
338
+
339
+ def __bool__(self) -> bool:
340
+ """True if all nodes matched."""
341
+ return self.matched
342
+
343
+ def __len__(self) -> int:
344
+ """Return number of nodes in the result chain."""
345
+ return len(self._nodes)
346
+
347
+ def __getitem__(self, idx: int) -> TopicMatchNode:
348
+ """Return a single node's info as a TopicMatchNode.
349
+
350
+ Args:
351
+ idx: Index of the node (supports negative indexing).
352
+
353
+ Returns:
354
+ A TopicMatchNode TypedDict containing 'matched', 'part_a', 'part_b', 'literal'.
355
+
356
+ Raises:
357
+ IndexError: If idx is out of range.
358
+ """
359
+ # deque doesn't support negative indexing directly, convert to list for that
360
+ nodes_list = list(self._nodes)
361
+ return nodes_list[idx]
362
+
363
+ def __iter__(self) -> Iterator[TopicMatchNode]:
364
+ """Iterate over node info dicts in sequence."""
365
+ return iter(self._nodes)
366
+
367
+ def to_dict(self) -> dict[str, PyTopicPart]:
368
+ """Convert match results into a dictionary mapping literal -> matched part.
369
+
370
+ Returns:
371
+ A mapping from literal string to the matched PyTopicPart.
372
+ """
373
+ result = {}
374
+ for node in self._nodes:
375
+ if node['literal'] and node['part_b']:
376
+ result[node['literal']] = node['part_b']
377
+ return result
378
+
379
+ @property
380
+ def owner(self) -> bool:
381
+ """bool: Whether this Python object owns the underlying memory (always True in native Python)."""
382
+ return True
383
+
384
+ @property
385
+ def length(self) -> int:
386
+ """int: Number of nodes in the result chain."""
387
+ return len(self._nodes)
388
+
389
+ @cached_property
390
+ def matched(self) -> bool:
391
+ """bool: True if every node in the chain reports matched == True."""
392
+ return all(node['matched'] for node in self._nodes) if self._nodes else False
393
+
394
+
395
+ class PyTopic:
396
+ """High-level Python representation of a parsed topic.
397
+
398
+ PyTopic instances internalize their literal content into a shared internal dict.
399
+ All topics created via the normal constructor are internalized into the global map and do not
400
+ own the underlying character storage (the buffer is bound to the global map).
401
+ """
402
+
403
+ __slots__ = ('_parts', '_value', '_hash', '_is_exact')
404
+
405
+ def __init__(self, topic: str = None, *args: Any, alloc: bool = True, allocator: Any = None, **kwargs: Any):
406
+ """Create a PyTopic from a topic string.
407
+
408
+ Args:
409
+ topic: Topic string to parse.
410
+ alloc: If True, allocate and initialize (default for normal usage).
411
+ allocator: Optional allocator (ignored in pure Python implementation).
412
+ """
413
+ self._parts: list[PyTopicPart] = []
414
+ self._value: str = ""
415
+ self._hash: int = 0
416
+ self._is_exact: bool = True
417
+
418
+ if not alloc:
419
+ if topic:
420
+ raise RuntimeError('Can not assign topic string when uninitialized!')
421
+ return
422
+
423
+ if topic:
424
+ self._parse_topic(topic)
425
+ # Internalize into global map
426
+ global _GLOBAL_INTERNAL_MAP
427
+ if topic not in _GLOBAL_INTERNAL_MAP:
428
+ _GLOBAL_INTERNAL_MAP[topic] = self
429
+ self._value = topic
430
+ self._hash = hash(topic)
431
+
432
+ def _parse_topic(self, topic_str: str) -> None:
433
+ """Parse a topic string into parts.
434
+
435
+ Token-based algorithm mirroring the C parser in
436
+ ``event_engine/capi/c_topic.h``:
437
+ - ``.`` separates tokens; empty tokens are dropped.
438
+ - ``./re/`` (or ``/re/`` at the start) is a pattern part; it must be
439
+ closed by ``/`` at the end of the string or by ``/.``.
440
+ - ``+name`` (non-empty name) is an any part; a lone ``+`` is exact.
441
+ - ``{name}`` (non-empty) is an any part; an unclosed ``{`` is exact.
442
+ - ``(a|b)`` is a range part (empty options dropped); an unclosed or
443
+ empty ``()`` is exact.
444
+
445
+ Raises:
446
+ ValueError: on an unclosed pattern (mirrors the C parser failure).
447
+ """
448
+ if not topic_str:
449
+ return
450
+
451
+ parts = []
452
+ n = len(topic_str)
453
+ i = 0
454
+
455
+ while i < n:
456
+ # Pattern: "./" at the start, or '.' directly followed by '/'
457
+ if (i == 0 and topic_str[0] == DEFAULT_PATTERN_DELIM) or (
458
+ i + 1 < n and topic_str[i] == DEFAULT_TOPIC_SEP
459
+ and topic_str[i + 1] == DEFAULT_PATTERN_DELIM):
460
+ content_start = i + 2 if topic_str[i] == DEFAULT_TOPIC_SEP else 1
461
+ j = content_start
462
+ found_close = False
463
+ while j < n:
464
+ if (j == n - 1 and topic_str[j] == DEFAULT_PATTERN_DELIM) or (
465
+ j + 1 < n and topic_str[j] == DEFAULT_PATTERN_DELIM
466
+ and topic_str[j + 1] == DEFAULT_TOPIC_SEP):
467
+ parts.append(PyTopicPartPattern(topic_str[content_start:j], alloc=True))
468
+ self._is_exact = False
469
+ i = j + 2 # advance past "/."
470
+ found_close = True
471
+ break
472
+ j += 1
473
+ if not found_close:
474
+ raise ValueError(f'Unclosed pattern in {topic_str!r}')
475
+ continue
476
+
477
+ # Normal token: run up to the next '.' that is not part of "./"
478
+ token_start = i
479
+ while i < n:
480
+ if topic_str[i] == DEFAULT_TOPIC_SEP:
481
+ if i + 1 < n and topic_str[i + 1] == DEFAULT_PATTERN_DELIM:
482
+ break
483
+ break
484
+ i += 1
485
+ token = topic_str[token_start:i]
486
+
487
+ if token:
488
+ if len(token) >= 2 and token[0] == DEFAULT_WILDCARD_MARKER:
489
+ parts.append(PyTopicPartAny(token[1:], alloc=True))
490
+ self._is_exact = False
491
+ elif len(token) >= 3 and token[0] == DEFAULT_WILDCARD_BRACKETS[0] \
492
+ and token[-1] == DEFAULT_WILDCARD_BRACKETS[1]:
493
+ parts.append(PyTopicPartAny(token[1:-1], alloc=True))
494
+ self._is_exact = False
495
+ elif len(token) >= 3 and token[0] == DEFAULT_RANGE_BRACKETS[0] \
496
+ and token[-1] == DEFAULT_RANGE_BRACKETS[1]:
497
+ options = [opt for opt in token[1:-1].split(DEFAULT_OPTION_SEP) if opt]
498
+ parts.append(PyTopicPartRange(options, alloc=True))
499
+ self._is_exact = False
500
+ else:
501
+ parts.append(PyTopicPartExact(token, alloc=True))
502
+
503
+ # Consume the terminating '.' only if it is not part of "./"
504
+ if i < n and topic_str[i] == DEFAULT_TOPIC_SEP:
505
+ if i + 1 >= n or topic_str[i + 1] != DEFAULT_PATTERN_DELIM:
506
+ i += 1
507
+
508
+ # Link parts
509
+ for j in range(len(parts) - 1):
510
+ parts[j]._next = parts[j + 1]
511
+
512
+ self._parts = parts
513
+
514
+ def _update_literal(self) -> None:
515
+ """Reconstruct the literal value from parts."""
516
+ if not self._parts:
517
+ self._value = ""
518
+ return
519
+
520
+ parts_strs = []
521
+ for part in self._parts:
522
+ if isinstance(part, PyTopicPartExact):
523
+ parts_strs.append(part.part)
524
+ elif isinstance(part, PyTopicPartAny):
525
+ parts_strs.append(f"{DEFAULT_WILDCARD_BRACKETS[0]}{part.name}{DEFAULT_WILDCARD_BRACKETS[1]}")
526
+ elif isinstance(part, PyTopicPartRange):
527
+ options_str = DEFAULT_OPTION_SEP.join(part._options)
528
+ parts_strs.append(f"{DEFAULT_RANGE_BRACKETS[0]}{options_str}{DEFAULT_RANGE_BRACKETS[1]}")
529
+ elif isinstance(part, PyTopicPartPattern):
530
+ parts_strs.append(f"{DEFAULT_PATTERN_DELIM}{part.pattern}{DEFAULT_PATTERN_DELIM}")
531
+
532
+ self._value = DEFAULT_TOPIC_SEP.join(parts_strs)
533
+ self._hash = hash(self._value)
534
+
535
+ def __len__(self) -> int:
536
+ """Return the number of parts in the topic."""
537
+ return len(self._parts)
538
+
539
+ def __bool__(self) -> bool:
540
+ """True if the topic has at least one part (mirrors the Cython Topic)."""
541
+ return len(self._parts) > 0
542
+
543
+ def __iter__(self) -> Iterator[PyTopicPart]:
544
+ """Iterate over topic parts (yields PyTopicPart subclasses)."""
545
+ return iter(self._parts)
546
+
547
+ def __getitem__(self, idx: int) -> PyTopicPart:
548
+ """Return the topic part at index `idx`.
549
+
550
+ Supports negative indexing.
551
+
552
+ Raises:
553
+ IndexError: If index is out of range.
554
+ """
555
+ return self._parts[idx]
556
+
557
+ @overload
558
+ def __add__(self, topic: 'PyTopic') -> 'PyTopic':
559
+ ...
560
+
561
+ @overload
562
+ def __add__(self, topic: PyTopicPart) -> 'PyTopic':
563
+ ...
564
+
565
+ def __add__(self, topic: 'PyTopic | PyTopicPart') -> 'PyTopic':
566
+ """Return a new PyTopic that aggregates this topic with another PyTopic or PyTopicPart.
567
+
568
+ Behavior:
569
+ - `__add__` creates and returns a copy; both operands remain unchanged.
570
+ - Use `append` or `__iadd__` for in-place modifications.
571
+
572
+ Args:
573
+ topic: Either a PyTopic or PyTopicPart.
574
+
575
+ Returns:
576
+ A new aggregated PyTopic.
577
+
578
+ Raises:
579
+ TypeError: When the operand type is unsupported.
580
+ """
581
+ new_topic = PyTopic.__new__(PyTopic)
582
+ new_topic._parts = list(self._parts)
583
+ new_topic._is_exact = self._is_exact
584
+
585
+ if isinstance(topic, PyTopic):
586
+ new_topic._parts.extend(topic._parts)
587
+ if not topic._is_exact:
588
+ new_topic._is_exact = False
589
+ elif isinstance(topic, PyTopicPart):
590
+ new_topic._parts.append(topic)
591
+ if topic.ttype != PyTopicType.TOPIC_PART_EXACT:
592
+ new_topic._is_exact = False
593
+ else:
594
+ raise TypeError(f'Can not add {topic} to {self}, expected either a PyTopic or PyTopicPart')
595
+
596
+ new_topic._update_literal()
597
+ return new_topic
598
+
599
+ @overload
600
+ def __iadd__(self, topic: 'PyTopic') -> 'PyTopic':
601
+ ...
602
+
603
+ @overload
604
+ def __iadd__(self, topic: PyTopicPart) -> 'PyTopic':
605
+ ...
606
+
607
+ def __iadd__(self, topic: 'PyTopic | PyTopicPart') -> 'PyTopic':
608
+ """In-place append another PyTopic or PyTopicPart.
609
+
610
+ Behavior:
611
+ - Modifies `self` in place and leaves the other operand unchanged.
612
+ - This is equivalent to `self.append(...)` and returns `self`.
613
+ """
614
+ if isinstance(topic, PyTopic):
615
+ self._parts.extend(topic._parts)
616
+ if not topic._is_exact:
617
+ self._is_exact = False
618
+ elif isinstance(topic, PyTopicPart):
619
+ self._parts.append(topic)
620
+ if topic.ttype != PyTopicType.TOPIC_PART_EXACT:
621
+ self._is_exact = False
622
+ else:
623
+ raise TypeError(f'Can not add {topic} to {self}, expected either a PyTopic or PyTopicPart')
624
+
625
+ self._update_literal()
626
+ return self
627
+
628
+ def __hash__(self):
629
+ """Return hash based on the topic's literal value.
630
+
631
+ The hash is precomputed during initialization for efficiency.
632
+
633
+ Returns:
634
+ A uint64_t hash integer.
635
+ """
636
+ return self._hash
637
+
638
+ def __eq__(self, other: 'PyTopic') -> bool:
639
+ """Check equality between this topic and another topic.
640
+
641
+ Args:
642
+ other: The other PyTopic to compare against.
643
+
644
+ Returns:
645
+ True if both topics have the same literal value.
646
+ """
647
+ if not isinstance(other, PyTopic):
648
+ return False
649
+ return self._value == other._value
650
+
651
+ def __repr__(self) -> str:
652
+ """Return string representation."""
653
+ exact_or_generic = "Exact" if self._is_exact else "Generic"
654
+ return f'<{self.__class__.__name__} {exact_or_generic}>(value="{self._value}", n_parts={len(self._parts)})'
655
+
656
+ def __str__(self) -> str:
657
+ """Return the topic literal value."""
658
+ return self._value
659
+
660
+ def __call__(self, **kwargs) -> 'PyTopic':
661
+ """Alias of ``format`` method to format the topic by replacing named wildcards with provided values."""
662
+ return self.format_map(kwargs, internalized=True, strict=False)
663
+
664
+ @classmethod
665
+ def from_parts(cls, topic_parts: Iterable[PyTopicPart]) -> PyTopic:
666
+ """Build a PyTopic from an iterable of PyTopicPart instances."""
667
+ new_topic = cls.__new__(cls)
668
+ new_topic._parts = list(topic_parts)
669
+ new_topic._is_exact = all(p.ttype == PyTopicType.TOPIC_PART_EXACT for p in new_topic._parts)
670
+ new_topic._update_literal()
671
+ return new_topic
672
+
673
+ @classmethod
674
+ def join(cls, topic_parts: Iterable[str]) -> 'PyTopic':
675
+ """Build a PyTopic from an iterable of literal strings.
676
+
677
+ Each string is appended as an exact part.
678
+
679
+ Notes:
680
+ - This is a higher-level helper for simple literal-only topics.
681
+ - For complex parts that need escaping or patterns, use `from_parts`.
682
+ """
683
+ parts = [PyTopicPartExact(part, alloc=True) for part in topic_parts]
684
+ return cls.from_parts(parts)
685
+
686
+ def append(self, topic_part: PyTopicPart) -> 'PyTopic':
687
+ """Append a PyTopicPart to this topic (high-level API).
688
+
689
+ Args:
690
+ topic_part: The part to append.
691
+
692
+ Returns:
693
+ Self for chaining.
694
+
695
+ Raises:
696
+ RuntimeError: If either topic or part is uninitialized.
697
+ """
698
+ self._parts.append(topic_part)
699
+ if topic_part.ttype != PyTopicType.TOPIC_PART_EXACT:
700
+ self._is_exact = False
701
+ self._update_literal()
702
+ return self
703
+
704
+ def match(self, other: 'PyTopic') -> PyTopicMatchResult:
705
+ """Match this topic against another topic.
706
+
707
+ Semantics mirror the Cython ``Topic.match``:
708
+ - Identical topics (same object, or same non-empty literal) yield a
709
+ single matched node whose literal is the full topic literal.
710
+ - Per-part matching: a part matches only when exactly one side is an
711
+ exact part; the other side must be equal (exact), match the
712
+ wildcard (any), be one of the options (range), or be matched by the
713
+ unanchored regex (pattern, POSIX ERE ``regexec`` semantics).
714
+ - Matching stops at the first failing part (fail-fast).
715
+ - A length mismatch appends one trailing failed node carrying the
716
+ residual part on the longer side.
717
+
718
+ Args:
719
+ other: The topic to match against.
720
+
721
+ Returns:
722
+ A PyTopicMatchResult describing per-part matches.
723
+ """
724
+ result = PyTopicMatchResult(alloc=True)
725
+
726
+ # Short-circuit: same topic address or same non-empty literal
727
+ if self is other or (
728
+ self._value and other._value and self._value == other._value):
729
+ result._nodes.append({
730
+ 'matched': True,
731
+ 'part_a': self._parts[0] if self._parts else None,
732
+ 'part_b': other._parts[0] if other._parts else None,
733
+ 'literal': self._value,
734
+ })
735
+ return result
736
+
737
+ self_parts = list(self._parts)
738
+ other_parts = list(other._parts)
739
+ n = min(len(self_parts), len(other_parts))
740
+ i = 0
741
+
742
+ while i < n:
743
+ part_a = self_parts[i]
744
+ part_b = other_parts[i]
745
+ node: TopicMatchNode = {
746
+ 'matched': False,
747
+ 'part_a': part_a,
748
+ 'part_b': part_b,
749
+ 'literal': None,
750
+ }
751
+
752
+ # Determine which side is exact (neither → fail-fast)
753
+ if part_a.ttype == PyTopicType.TOPIC_PART_EXACT:
754
+ part_exact, part_other = part_a, part_b
755
+ elif part_b.ttype == PyTopicType.TOPIC_PART_EXACT:
756
+ part_exact, part_other = part_b, part_a
757
+ else:
758
+ result._nodes.append(node)
759
+ return result
760
+
761
+ # Match the non-exact side against the exact literal
762
+ if part_other.ttype == PyTopicType.TOPIC_PART_EXACT:
763
+ matched = (
764
+ isinstance(part_other, PyTopicPartExact)
765
+ and isinstance(part_exact, PyTopicPartExact)
766
+ and part_exact.part == part_other.part
767
+ )
768
+ elif part_other.ttype == PyTopicType.TOPIC_PART_ANY:
769
+ matched = True
770
+ elif part_other.ttype == PyTopicType.TOPIC_PART_RANGE:
771
+ matched = (
772
+ isinstance(part_exact, PyTopicPartExact)
773
+ and isinstance(part_other, PyTopicPartRange)
774
+ and part_exact.part in part_other._options
775
+ )
776
+ elif part_other.ttype == PyTopicType.TOPIC_PART_PATTERN:
777
+ # POSIX ERE regexec is unanchored → use re.search
778
+ matched = (
779
+ isinstance(part_exact, PyTopicPartExact)
780
+ and isinstance(part_other, PyTopicPartPattern)
781
+ and part_other.regex.search(part_exact.part) is not None
782
+ )
783
+ else:
784
+ matched = False
785
+
786
+ if not matched:
787
+ result._nodes.append(node)
788
+ return result
789
+
790
+ node['matched'] = True
791
+ # The C match code sets `literal` for EXACT/ANY/RANGE but not PATTERN.
792
+ if part_other.ttype != PyTopicType.TOPIC_PART_PATTERN \
793
+ and not isinstance(part_other, PyTopicPartPattern):
794
+ node['literal'] = part_exact.part
795
+ result._nodes.append(node)
796
+ i += 1
797
+
798
+ # Any residual part on either side is considered a mismatch
799
+ if i < len(self_parts) or i < len(other_parts):
800
+ result._nodes.append({
801
+ 'matched': False,
802
+ 'part_a': self_parts[i] if i < len(self_parts) else None,
803
+ 'part_b': other_parts[i] if i < len(other_parts) else None,
804
+ 'literal': None,
805
+ })
806
+
807
+ return result
808
+
809
+ def update_literal(self) -> 'PyTopic':
810
+ """Update the internal literal buffer to reflect the current parts.
811
+
812
+ This is useful after in-place modifications of the subordinate TopicParts.
813
+ To avoid inconsistencies, call this method to regenerate the internal literal.
814
+
815
+ Returns:
816
+ Self for chaining.
817
+
818
+ Raises:
819
+ RuntimeError: If the topic is uninitialized.
820
+ """
821
+ self._update_literal()
822
+ return self
823
+
824
+ def format(self, **kwargs) -> PyTopic:
825
+ """Format the topic by replacing named wildcards with provided values.
826
+
827
+ Args:
828
+ **kwargs: Mapping from wildcard names to replacement strings.
829
+
830
+ Returns:
831
+ A new Exact PyTopic with wildcards replaced by the provided values.
832
+
833
+ Raises:
834
+ KeyError: If a required wildcard name is missing in kwargs.
835
+ ValueError: If having subordinate parts that are not exact or wildcards.
836
+ """
837
+ return self.format_map(kwargs, internalized=True, strict=False)
838
+
839
+ def format_map(self, mapping: dict[str, str], internalized: bool = True, strict: bool = False) -> PyTopic:
840
+ """Format the topic by replacing named wildcards with provided values from a mapping.
841
+
842
+ Args:
843
+ mapping: Dictionary mapping wildcard names to replacement strings.
844
+ internalized: If True, the returned topic is internalized into the global map and not owning its underlying buffer.
845
+ If False, the returned topic owns its internal buffer.
846
+ strict: If True, raises KeyError if a wildcard name is missing in mapping.
847
+
848
+ Returns:
849
+ A new PyTopic with wildcards replaced by the provided values. If strict is True, the new PyTopic is guaranteed to be an exact PyTopic.
850
+
851
+ Raises:
852
+ KeyError: If a required wildcard name is missing in mapping.
853
+ ValueError: If having subordinate parts that are not exact or wildcards.
854
+ """
855
+ new_parts = []
856
+
857
+ for part in self._parts:
858
+ if part.ttype == PyTopicType.TOPIC_PART_EXACT:
859
+ part_exact = part if isinstance(part, PyTopicPartExact) else None
860
+ if part_exact:
861
+ new_parts.append(PyTopicPartExact(part_exact.part, alloc=True))
862
+ elif part.ttype == PyTopicType.TOPIC_PART_ANY:
863
+ part_any = part if isinstance(part, PyTopicPartAny) else None
864
+ if part_any:
865
+ if part_any.name not in mapping:
866
+ if strict:
867
+ raise KeyError(part_any.name)
868
+ else:
869
+ new_parts.append(PyTopicPartAny(part_any.name, alloc=True))
870
+ else:
871
+ new_parts.append(PyTopicPartExact(mapping[part_any.name], alloc=True))
872
+ else:
873
+ raise ValueError(f'Not supported topic type {part.ttype}')
874
+
875
+ new_topic = PyTopic.from_parts(new_parts)
876
+
877
+ if internalized:
878
+ global _GLOBAL_INTERNAL_MAP
879
+ if new_topic._value not in _GLOBAL_INTERNAL_MAP:
880
+ _GLOBAL_INTERNAL_MAP[new_topic._value] = new_topic
881
+
882
+ return new_topic
883
+
884
+ @property
885
+ def value(self) -> str:
886
+ """str: The full topic literal value.
887
+
888
+ Getting returns the current literal. Setting attempts to assign and will raise
889
+ ValueError on syntax errors. Setting mutates the internalized buffer and will
890
+ re-register the topic in the internal mapping.
891
+ """
892
+ return self._value
893
+
894
+ @value.setter
895
+ def value(self, value: str) -> None:
896
+ """Set the topic literal value.
897
+
898
+ Args:
899
+ value: New topic string to assign.
900
+
901
+ Raises:
902
+ ValueError: If assignment fails due to syntax error.
903
+
904
+ Notes:
905
+ - Mutating `value` is an expensive operation (de-register / re-register). Avoid frequent calls.
906
+ - Prefer lazy-init: create an empty topic and set `value` once when needed.
907
+ """
908
+ # Remove from internal map if present
909
+ global _GLOBAL_INTERNAL_MAP
910
+ if self._value in _GLOBAL_INTERNAL_MAP and _GLOBAL_INTERNAL_MAP[self._value] is self:
911
+ del _GLOBAL_INTERNAL_MAP[self._value]
912
+
913
+ # Parse new value
914
+ self._parts = []
915
+ self._value = ""
916
+ self._hash = 0
917
+ self._is_exact = True
918
+
919
+ try:
920
+ self._parse_topic(value)
921
+ self._value = value
922
+ self._hash = hash(value)
923
+
924
+ # Re-internalize
925
+ if value not in _GLOBAL_INTERNAL_MAP:
926
+ _GLOBAL_INTERNAL_MAP[value] = self
927
+ except Exception as e:
928
+ raise ValueError(f'Failed to assign topic "{value}", check if syntax is correct!') from e
929
+
930
+ @property
931
+ def owner(self) -> bool:
932
+ """bool: Whether this Python object owns the underlying memory (always True in native Python)."""
933
+ return True
934
+
935
+ @property
936
+ def is_exact(self) -> bool:
937
+ """bool: True if the topic consists only of exact parts (no wildcards, ranges, or patterns)."""
938
+ return self._is_exact
939
+
940
+ @property
941
+ def addr(self) -> int:
942
+ """int: Numeric address / id of the underlying structure."""
943
+ return id(self)