Coverage for src/gentrie/types.py: 100%

1# -*- coding: utf-8 -*-

2"""Core data types for the gentrie package."""

3

4 from typing import Any, NamedTuple, Optional

5

6 from .protocols import GeneralizedKey

7

8

9# Constants for TrieEntry fields (performance optimization)

10 TRIE_IDENT: int = 0

11"""Alias for field number 0 (ident) in TrieEntry. It is faster to use this than accessing the field by name."""

12 TRIE_KEY: int = 1

13"""Alias for field number 1 (key) in TrieEntry. It is faster to use this than accessing the field by name."""

14 TRIE_VALUE: int = 2

15"""Alias for field number 2 (value) in TrieEntry. It is faster to use this than accessing the field by name."""

16

17

18 class TrieId(int):

19 """Unique identifier for a key in a trie."""

20 __slots__ = ()

21

22 def __new__(cls, value: int):

23 return int.__new__(cls, value)

24

25 def __str__(self) -> str:

26 """Returns a string representation of the TrieId."""

27 return f'TrieId({int(self)})'

28

29 def __repr__(self) -> str:

30 """Returns a string representation of the TrieId for debugging."""

31 return f'TrieId({int(self)})'

32

33

34 class TrieEntry(NamedTuple):

35 """A :class:`TrieEntry` is a :class:`NamedTuple` containing the unique identifer and key for an entry in the trie.

36 """

37

38 ident: TrieId

39 """:class:`TrieId` Unique identifier for a key in the trie. Alias for field number 0."""

40 key: GeneralizedKey

41 """:class:`GeneralizedKey` Key for an entry in the trie. Alias for field number 1."""

42 value: Optional[Any] = None

43 """Optional value for the entry in the trie. Alias for field number 2."""

44

45 def __eq__(self, other: object) -> bool:

46 if not isinstance(other, TrieEntry):

47 return False

48 return self.ident == other.ident and tuple(self.key) == tuple(

49 other.key) and self.value == other.value

50

51 def __hash__(self) -> int:

52 return hash((self.ident, tuple(self.key), self.value)) # pyright: ignore[reportUnknownArgumentType]