2from multiprocessing
import BoundedSemaphore
12TAG_RANGE_STATE = range(2, 256)
13TAG_RANGE_VALUE = range(256, 4096)
14TAG_RANGE_ELSE = range(4096, LIMIT_TAG)
16ID_RANGE_VALUE = range(256, 4096)
17ID_RANGE_ELSE = list(range(2, 256)) + list(range(4096, LIMIT_ID))
23TAG_SEM = BoundedSemaphore(1)
24ID_SEM = BoundedSemaphore(1)
25FILE_SEM = BoundedSemaphore(1)
28async def map_unique_pair(string_tag: str, string_id: str, map_range: range) -> int:
29 """Allocates both a TAG and ID mapping where they both map to the same number.
32 string_tag (str): The string tag to map
33 string_id (str): The string message to map
34 map_range (range): The range the mapping should be in
37 Error.TAGIDMismatchException: If both mappings already exist and do not match in value
38 Error.OutOfRangeException: If either mapping is unable to allocate another value within the given range
41 int: The value mapping to both the string tag and message
43 if TAGs.get(string_tag)
and IDs.get(string_id):
44 if TAGs[string_tag] != IDs[string_id]:
45 raise Error.TAGIDMismatchException(f
"{string_tag} : {string_id}")
46 return TAGs[string_tag]
48 with ID_SEM
and TAG_SEM:
49 ids = set(IDs.values())
50 tags = set(TAGs.values())
53 if i
not in BLACKLIST_IDS
and i
not in ids
and i
not in tags:
58 raise Error.OutOfRangeException(
"Either IDs or TAGs are out")
61async def map_unique_id(string_id: str, map_range: range = ID_RANGE_ELSE) -> int:
62 """Allocates an ID mapping
65 string_id (str): The string message to map
66 map_range (range, optional): The range the mapping should be in. Defaults to ID_RANGE_ELSE.
69 Error.OutOfRangeException: If mapping is unable to allocate another value within the given range
72 int: The value mapping to the string message
74 if IDs.get(string_id):
78 values = set(IDs.values())
81 if i
not in BLACKLIST_IDS
and i
not in values:
86 raise Error.OutOfRangeException(
"IDs")
89async def map_unique_tag(string_tag: str, map_range: range = TAG_RANGE_ELSE) -> int:
90 """Allocates a TAG mapping
93 string_tag (str): The string tag to map
94 map_range (range, optional): The range the mapping should be in. Defaults to TAG_RANGE_ELSE.
97 Error.OutOfRangeException: If mapping is unable to allocate another value within the given range
100 int: The value mapping to the string tag
102 if TAGs.get(string_tag):
103 return TAGs[string_tag]
106 values = set(TAGs.values())
109 if i
not in BLACKLIST_IDS
and i
not in values:
114 raise Error.OutOfRangeException(
"TAGs")
117def clear_blanks() -> None:
118 """Remove empty strings mappings, if any"""
129def save_lookup(file_path: str) ->
None:
130 """Saves current mappings
133 file_path (str): Valid path to a file to save to
135 to_save = (TAGs, IDs)
136 Util.touch(file_path)
137 with open(file_path,
"w", encoding=
"utf-8")
as file:
138 json.dump(to_save, file, indent=4, separators=(
",",
": "))