Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_serial.py

raw
1 # Copyright (c) 2024, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 from ansible.module_utils.common.text.converters import to_text
11
12 from ansible_collections.community.crypto.plugins.module_utils._crypto.math import (
13 convert_int_to_hex,
14 )
15
16
17 def th(number: int) -> str:
18 abs_number = abs(number)
19 mod_10 = abs_number % 10
20 mod_100 = abs_number % 100
21 if mod_100 not in (11, 12, 13):
22 if mod_10 == 1:
23 return "st"
24 if mod_10 == 2:
25 return "nd"
26 if mod_10 == 3:
27 return "rd"
28 return "th"
29
30
31 def parse_serial(value: str | bytes) -> int:
32 """
33 Given a colon-separated string of hexadecimal byte values, converts it to an integer.
34 """
35 value_str = to_text(value)
36 result = 0
37 for i, part in enumerate(value_str.split(":")):
38 try:
39 part_value = int(part, 16)
40 if part_value < 0 or part_value > 255:
41 raise ValueError("the value is not in range [0, 255]")
42 except ValueError as exc:
43 raise ValueError(
44 f"The {i + 1}{th(i + 1)} part {part!r} is not a hexadecimal number in range [0, 255]: {exc}"
45 ) from exc
46 result = (result << 8) | part_value
47 return result
48
49
50 def to_serial(value: int) -> str:
51 """
52 Given an integer, converts its absolute value to a colon-separated string of hexadecimal byte values.
53 """
54 value_str = convert_int_to_hex(value).upper()
55 if len(value_str) % 2 != 0:
56 value_str = f"0{value_str}"
57 return ":".join(value_str[i : i + 2] for i in range(0, len(value_str), 2))
58
59
60 __all__ = ("parse_serial", "to_serial")