uuid58 0.1.0__tar.gz

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.
uuid58-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nakano as a Service
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
uuid58-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: uuid58
3
+ Version: 0.1.0
4
+ Summary: Encode UUIDs as 22-character, order-preserving Base58 strings (uuid58)
5
+ Keywords: uuid,base58,uuid58,short-id,encoding
6
+ Author: Nakano as a Service
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Project-URL: Homepage, https://github.com/nakanoasaservice/uuid58/tree/main/python
24
+ Project-URL: Repository, https://github.com/nakanoasaservice/uuid58
25
+ Project-URL: Specification, https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md
26
+ Project-URL: Issues, https://github.com/nakanoasaservice/uuid58/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # uuid58 (Python)
30
+
31
+ Encode UUIDs as 22-character Base58 strings, and back.
32
+
33
+ ```text
34
+ f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf <-> XDY9dmBbcMBXqcRvYw8xJ2
35
+ ```
36
+
37
+ - Always exactly 22 characters, using the Bitcoin Base58 alphabet (no `0`,
38
+ `O`, `I`, `l`).
39
+ - Order-preserving: sorting uuid58 strings by code point sorts the UUIDs
40
+ numerically (useful with UUIDv7).
41
+ - Strict: implements the [uuid58 specification](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md)
42
+ and passes its [test vectors](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json).
43
+ - No dependencies, fully typed (`py.typed`), CPython 3.10+.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install uuid58
49
+ ```
50
+
51
+ or `uv add uuid58`.
52
+
53
+ ## Usage
54
+
55
+ ```python
56
+ import uuid
57
+ import uuid58
58
+
59
+ s = "XDY9dmBbcMBXqcRvYw8xJ2"
60
+
61
+ # All of these return s:
62
+ uuid58.encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf")
63
+ uuid58.encode("F4B247FD1F8745D4AA061C6FC0A8DFAF") # plain hex, any case
64
+ uuid58.encode(uuid.UUID("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf"))
65
+ uuid58.encode(bytes.fromhex("f4b247fd1f8745d4aa061c6fc0a8dfaf"))
66
+ uuid58.encode(0xF4B247FD1F8745D4AA061C6FC0A8DFAF)
67
+
68
+ uuid58.decode(s) # 'f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf'
69
+ uuid58.decode_uuid(s) # UUID('f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf')
70
+ uuid58.decode_bytes(s) # b'\xf4\xb2G\xfd\x1f\x87E\xd4...'
71
+ uuid58.decode_int(s) # 325257319917903217740243107280071483311
72
+
73
+ uuid58.is_uuid58("XDY9dmBbcMBXqcRvYw8xJ2") # True
74
+ uuid58.is_uuid58("zzzzzzzzzzzzzzzzzzzzzz") # False: exceeds 128 bits
75
+
76
+ uuid58.uuid58() # a random UUIDv4, encoded, e.g. 'Tj5D5H2Bc1LcPjwNNhH4xS'
77
+ ```
78
+
79
+ ### Errors
80
+
81
+ All invalid-input errors subclass `uuid58.Uuid58Error`, which subclasses
82
+ `ValueError`. Each carries the spec error kind (SPEC.md Section 7) in `kind`,
83
+ an `ErrorKind` that compares equal to its spec name:
84
+
85
+ | Exception | `kind` | Raised when |
86
+ | ----------------------- | --------------------- | ---------------------------------------------------------------- |
87
+ | `InvalidLengthError` | `"invalid_length"` | a string of the wrong length, or bytes whose length is not 16 |
88
+ | `InvalidCharacterError` | `"invalid_character"` | a character not allowed in its position (incl. any non-ASCII) |
89
+ | `ValueOverflowError` | `"overflow"` | a value outside `0..2**128 - 1` (decoded string or encoded `int`) |
90
+
91
+ ```python
92
+ try:
93
+ uuid58.decode(user_input)
94
+ except uuid58.InvalidCharacterError:
95
+ ...
96
+ except uuid58.Uuid58Error as e:
97
+ print(e.kind) # invalid_length / overflow
98
+ ```
99
+
100
+ Passing an unsupported type (for example `bool`, `float` or `None`) raises
101
+ `TypeError`. Error messages are not part of the specification and may change.
102
+
103
+ ## API
104
+
105
+ | Name | Description |
106
+ | ---------------------------------------- | --------------------------------------------------------------------------------- |
107
+ | `encode(value: UUIDLike) -> str` | Encode a UUID string, `uuid.UUID`, 16 `bytes`/`bytearray`, or `int`. |
108
+ | `decode(s: str) -> str` | Decode to the lowercase hyphenated UUID string. |
109
+ | `decode_uuid(s: str) -> uuid.UUID` | Decode to a `uuid.UUID`. |
110
+ | `decode_bytes(s: str) -> bytes` | Decode to 16 big-endian bytes (`uuid.UUID.bytes` order). |
111
+ | `decode_int(s: str) -> int` | Decode to an `int` in `0..2**128 - 1`. |
112
+ | `is_uuid58(s: object) -> bool` | `True` exactly when `decode(s)` would succeed. Never raises. |
113
+ | `uuid58() -> str` | Generate a random UUIDv4 and return its encoding. |
114
+ | `ALPHABET`, `MAX_UUID58` | The Base58 alphabet and the largest valid uuid58 string. |
115
+ | `Uuid58Error`, `ErrorKind`, … | See [Errors](#errors). |
116
+
117
+ ### Accepted UUID strings
118
+
119
+ `encode` accepts exactly two textual forms, in any letter case (SPEC.md
120
+ Section 5.1):
121
+
122
+ - hyphenated, 36 characters: `f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf`
123
+ - plain, 32 hex digits: `f4b247fd1f8745d4aa061c6fc0a8dfaf`
124
+
125
+ Everything else is rejected, including forms that `uuid.UUID()` accepts:
126
+ braces, the `urn:uuid:` prefix, misplaced hyphens and surrounding
127
+ whitespace. To encode those, parse them with `uuid.UUID(...)` first and pass
128
+ the resulting object.
129
+
130
+ `bytes` passed to `encode` are the 16 raw bytes of the UUID, never the ASCII
131
+ text of a UUID string.
132
+
133
+ ## Development
134
+
135
+ Uses [uv](https://docs.astral.sh/uv/) (pinned via `mise.toml`).
136
+
137
+ ```bash
138
+ uv run pytest # tests, including spec/vectors.json conformance
139
+ uv run ruff check # lint
140
+ uv run ruff format # format
141
+ uv run mypy # type check (strict)
142
+ ```
143
+
144
+ The conformance tests read `../spec/vectors.json`, so run them from a
145
+ checkout of the repository.
146
+
147
+ ## License
148
+
149
+ MIT
uuid58-0.1.0/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # uuid58 (Python)
2
+
3
+ Encode UUIDs as 22-character Base58 strings, and back.
4
+
5
+ ```text
6
+ f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf <-> XDY9dmBbcMBXqcRvYw8xJ2
7
+ ```
8
+
9
+ - Always exactly 22 characters, using the Bitcoin Base58 alphabet (no `0`,
10
+ `O`, `I`, `l`).
11
+ - Order-preserving: sorting uuid58 strings by code point sorts the UUIDs
12
+ numerically (useful with UUIDv7).
13
+ - Strict: implements the [uuid58 specification](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md)
14
+ and passes its [test vectors](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json).
15
+ - No dependencies, fully typed (`py.typed`), CPython 3.10+.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install uuid58
21
+ ```
22
+
23
+ or `uv add uuid58`.
24
+
25
+ ## Usage
26
+
27
+ ```python
28
+ import uuid
29
+ import uuid58
30
+
31
+ s = "XDY9dmBbcMBXqcRvYw8xJ2"
32
+
33
+ # All of these return s:
34
+ uuid58.encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf")
35
+ uuid58.encode("F4B247FD1F8745D4AA061C6FC0A8DFAF") # plain hex, any case
36
+ uuid58.encode(uuid.UUID("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf"))
37
+ uuid58.encode(bytes.fromhex("f4b247fd1f8745d4aa061c6fc0a8dfaf"))
38
+ uuid58.encode(0xF4B247FD1F8745D4AA061C6FC0A8DFAF)
39
+
40
+ uuid58.decode(s) # 'f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf'
41
+ uuid58.decode_uuid(s) # UUID('f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf')
42
+ uuid58.decode_bytes(s) # b'\xf4\xb2G\xfd\x1f\x87E\xd4...'
43
+ uuid58.decode_int(s) # 325257319917903217740243107280071483311
44
+
45
+ uuid58.is_uuid58("XDY9dmBbcMBXqcRvYw8xJ2") # True
46
+ uuid58.is_uuid58("zzzzzzzzzzzzzzzzzzzzzz") # False: exceeds 128 bits
47
+
48
+ uuid58.uuid58() # a random UUIDv4, encoded, e.g. 'Tj5D5H2Bc1LcPjwNNhH4xS'
49
+ ```
50
+
51
+ ### Errors
52
+
53
+ All invalid-input errors subclass `uuid58.Uuid58Error`, which subclasses
54
+ `ValueError`. Each carries the spec error kind (SPEC.md Section 7) in `kind`,
55
+ an `ErrorKind` that compares equal to its spec name:
56
+
57
+ | Exception | `kind` | Raised when |
58
+ | ----------------------- | --------------------- | ---------------------------------------------------------------- |
59
+ | `InvalidLengthError` | `"invalid_length"` | a string of the wrong length, or bytes whose length is not 16 |
60
+ | `InvalidCharacterError` | `"invalid_character"` | a character not allowed in its position (incl. any non-ASCII) |
61
+ | `ValueOverflowError` | `"overflow"` | a value outside `0..2**128 - 1` (decoded string or encoded `int`) |
62
+
63
+ ```python
64
+ try:
65
+ uuid58.decode(user_input)
66
+ except uuid58.InvalidCharacterError:
67
+ ...
68
+ except uuid58.Uuid58Error as e:
69
+ print(e.kind) # invalid_length / overflow
70
+ ```
71
+
72
+ Passing an unsupported type (for example `bool`, `float` or `None`) raises
73
+ `TypeError`. Error messages are not part of the specification and may change.
74
+
75
+ ## API
76
+
77
+ | Name | Description |
78
+ | ---------------------------------------- | --------------------------------------------------------------------------------- |
79
+ | `encode(value: UUIDLike) -> str` | Encode a UUID string, `uuid.UUID`, 16 `bytes`/`bytearray`, or `int`. |
80
+ | `decode(s: str) -> str` | Decode to the lowercase hyphenated UUID string. |
81
+ | `decode_uuid(s: str) -> uuid.UUID` | Decode to a `uuid.UUID`. |
82
+ | `decode_bytes(s: str) -> bytes` | Decode to 16 big-endian bytes (`uuid.UUID.bytes` order). |
83
+ | `decode_int(s: str) -> int` | Decode to an `int` in `0..2**128 - 1`. |
84
+ | `is_uuid58(s: object) -> bool` | `True` exactly when `decode(s)` would succeed. Never raises. |
85
+ | `uuid58() -> str` | Generate a random UUIDv4 and return its encoding. |
86
+ | `ALPHABET`, `MAX_UUID58` | The Base58 alphabet and the largest valid uuid58 string. |
87
+ | `Uuid58Error`, `ErrorKind`, … | See [Errors](#errors). |
88
+
89
+ ### Accepted UUID strings
90
+
91
+ `encode` accepts exactly two textual forms, in any letter case (SPEC.md
92
+ Section 5.1):
93
+
94
+ - hyphenated, 36 characters: `f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf`
95
+ - plain, 32 hex digits: `f4b247fd1f8745d4aa061c6fc0a8dfaf`
96
+
97
+ Everything else is rejected, including forms that `uuid.UUID()` accepts:
98
+ braces, the `urn:uuid:` prefix, misplaced hyphens and surrounding
99
+ whitespace. To encode those, parse them with `uuid.UUID(...)` first and pass
100
+ the resulting object.
101
+
102
+ `bytes` passed to `encode` are the 16 raw bytes of the UUID, never the ASCII
103
+ text of a UUID string.
104
+
105
+ ## Development
106
+
107
+ Uses [uv](https://docs.astral.sh/uv/) (pinned via `mise.toml`).
108
+
109
+ ```bash
110
+ uv run pytest # tests, including spec/vectors.json conformance
111
+ uv run ruff check # lint
112
+ uv run ruff format # format
113
+ uv run mypy # type check (strict)
114
+ ```
115
+
116
+ The conformance tests read `../spec/vectors.json`, so run them from a
117
+ checkout of the repository.
118
+
119
+ ## License
120
+
121
+ MIT
@@ -0,0 +1,95 @@
1
+ [project]
2
+ name = "uuid58"
3
+ version = "0.1.0"
4
+ description = "Encode UUIDs as 22-character, order-preserving Base58 strings (uuid58)"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.10"
9
+ dependencies = []
10
+ keywords = [
11
+ "uuid",
12
+ "base58",
13
+ "uuid58",
14
+ "short-id",
15
+ "encoding",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "Programming Language :: Python :: 3.15",
29
+ "Topic :: Software Development :: Libraries",
30
+ "Typing :: Typed",
31
+ ]
32
+
33
+ [[project.authors]]
34
+ name = "Nakano as a Service"
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/nakanoasaservice/uuid58/tree/main/python"
38
+ Repository = "https://github.com/nakanoasaservice/uuid58"
39
+ Specification = "https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md"
40
+ Issues = "https://github.com/nakanoasaservice/uuid58/issues"
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.13,<0.14"]
44
+ build-backend = "uv_build"
45
+
46
+ [dependency-groups]
47
+ dev = [
48
+ "hypothesis>=6",
49
+ "mypy>=1.13",
50
+ "pytest>=8",
51
+ "ruff>=0.8",
52
+ ]
53
+
54
+ [tool.uv]
55
+ required-version = ">=0.13,<0.14"
56
+
57
+ [tool.ruff]
58
+ line-length = 88
59
+
60
+ [tool.ruff.lint]
61
+ select = [
62
+ "E",
63
+ "W",
64
+ "F",
65
+ "I",
66
+ "B",
67
+ "UP",
68
+ "SIM",
69
+ "RUF",
70
+ "PT",
71
+ "N",
72
+ ]
73
+
74
+ [tool.ruff.lint.per-file-ignores]
75
+ "tests/**" = ["RUF001"]
76
+
77
+ [tool.mypy]
78
+ strict = true
79
+ files = [
80
+ "src",
81
+ "tests",
82
+ ]
83
+
84
+ [tool.pytest.ini_options]
85
+ testpaths = [
86
+ "tests",
87
+ "src",
88
+ ]
89
+ addopts = [
90
+ "--doctest-modules",
91
+ "--strict-markers",
92
+ "--strict-config",
93
+ "-ra",
94
+ ]
95
+ xfail_strict = true
@@ -0,0 +1,67 @@
1
+ [project]
2
+ name = "uuid58"
3
+ version = "0.1.0"
4
+ description = "Encode UUIDs as 22-character, order-preserving Base58 strings (uuid58)"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Nakano as a Service" }]
9
+ requires-python = ">=3.10"
10
+ dependencies = []
11
+ keywords = ["uuid", "base58", "uuid58", "short-id", "encoding"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: 3.15",
24
+ "Topic :: Software Development :: Libraries",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/nakanoasaservice/uuid58/tree/main/python"
30
+ Repository = "https://github.com/nakanoasaservice/uuid58"
31
+ Specification = "https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md"
32
+ Issues = "https://github.com/nakanoasaservice/uuid58/issues"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.13,<0.14"]
36
+ build-backend = "uv_build"
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "hypothesis>=6",
41
+ "mypy>=1.13",
42
+ "pytest>=8",
43
+ "ruff>=0.8",
44
+ ]
45
+
46
+ [tool.uv]
47
+ # Keep in sync with mise.toml. setup-uv in CI reads this too.
48
+ required-version = ">=0.13,<0.14"
49
+
50
+ [tool.ruff]
51
+ line-length = 88
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "W", "F", "I", "B", "UP", "SIM", "RUF", "PT", "N"]
55
+
56
+ [tool.ruff.lint.per-file-ignores]
57
+ # The tests deliberately use confusable non-ASCII characters (SPEC.md 4.1).
58
+ "tests/**" = ["RUF001"]
59
+
60
+ [tool.mypy]
61
+ strict = true
62
+ files = ["src", "tests"]
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests", "src"]
66
+ addopts = ["--doctest-modules", "--strict-markers", "--strict-config", "-ra"]
67
+ xfail_strict = true
@@ -0,0 +1,287 @@
1
+ """Encode UUIDs as 22-character, order-preserving Base58 strings.
2
+
3
+ This package implements the uuid58 specification:
4
+ https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md
5
+
6
+ >>> import uuid58
7
+ >>> uuid58.encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf")
8
+ 'XDY9dmBbcMBXqcRvYw8xJ2'
9
+ >>> uuid58.decode("XDY9dmBbcMBXqcRvYw8xJ2")
10
+ 'f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf'
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import enum
16
+ import uuid as _uuid
17
+ from typing import Final
18
+
19
+ __all__ = [
20
+ "ALPHABET",
21
+ "MAX_UUID58",
22
+ "ErrorKind",
23
+ "InvalidCharacterError",
24
+ "InvalidLengthError",
25
+ "UUIDLike",
26
+ "Uuid58Error",
27
+ "ValueOverflowError",
28
+ "decode",
29
+ "decode_bytes",
30
+ "decode_int",
31
+ "decode_uuid",
32
+ "encode",
33
+ "is_uuid58",
34
+ "uuid58",
35
+ ]
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ ALPHABET: Final = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
40
+ """The Bitcoin Base58 alphabet, in ascending ASCII order (SPEC.md Section 2)."""
41
+
42
+ MAX_UUID58: Final = "YcVfxkQb6JRzqk5kF2tNLv" # cspell:disable-line
43
+ """The largest valid uuid58 string, the encoding of 2**128 - 1."""
44
+
45
+ UUIDLike = str | _uuid.UUID | bytes | bytearray | int
46
+ """The input types accepted by :func:`encode`."""
47
+
48
+ _ENCODED_LENGTH: Final = 22
49
+ _MAX_UINT128: Final = (1 << 128) - 1
50
+ _DIGIT_VALUES: Final = {c: i for i, c in enumerate(ALPHABET)}
51
+ _HEX_DIGITS: Final = frozenset("0123456789abcdefABCDEF")
52
+ _HYPHEN_POSITIONS: Final = (8, 13, 18, 23)
53
+ _MAX_PREVIEW_LENGTH: Final = 40
54
+
55
+
56
+ class ErrorKind(str, enum.Enum):
57
+ """The error kinds defined in SPEC.md Section 7.
58
+
59
+ Members compare equal to their spec names, e.g.
60
+ ``ErrorKind.OVERFLOW == "overflow"``.
61
+ """
62
+
63
+ INVALID_LENGTH = "invalid_length"
64
+ INVALID_CHARACTER = "invalid_character"
65
+ OVERFLOW = "overflow"
66
+
67
+ def __str__(self) -> str:
68
+ return self.value
69
+
70
+
71
+ class Uuid58Error(ValueError):
72
+ """Base class for every error raised by this package for invalid input.
73
+
74
+ Catch a subclass, or inspect :attr:`kind`, to tell the error kinds apart.
75
+ Error messages are not part of the specification and may change.
76
+ """
77
+
78
+ kind: ErrorKind
79
+ """The spec error kind (SPEC.md Section 7)."""
80
+
81
+
82
+ class InvalidLengthError(Uuid58Error):
83
+ """The input has the wrong length (``invalid_length``)."""
84
+
85
+ kind = ErrorKind.INVALID_LENGTH
86
+
87
+
88
+ class InvalidCharacterError(Uuid58Error):
89
+ """The input contains a character not allowed in its position
90
+ (``invalid_character``)."""
91
+
92
+ kind = ErrorKind.INVALID_CHARACTER
93
+
94
+
95
+ class ValueOverflowError(Uuid58Error):
96
+ """The value is outside ``0..2**128 - 1`` (``overflow``).
97
+
98
+ Named to avoid shadowing the built-in :class:`OverflowError`, which it
99
+ does not subclass.
100
+ """
101
+
102
+ kind = ErrorKind.OVERFLOW
103
+
104
+
105
+ def _preview(value: object) -> str:
106
+ """Formats untrusted input for an error message: truncated and repr()'d,
107
+ so huge or multi-line inputs cannot bloat or forge log lines."""
108
+ if isinstance(value, (str, bytes, bytearray)) and len(value) > _MAX_PREVIEW_LENGTH:
109
+ return f"{value[:_MAX_PREVIEW_LENGTH]!r}... (length {len(value)})"
110
+ return repr(value)
111
+
112
+
113
+ # --- encoding ---------------------------------------------------------------
114
+
115
+
116
+ def _encode_uint128(value: int) -> str:
117
+ digits = [""] * _ENCODED_LENGTH
118
+ for i in range(_ENCODED_LENGTH - 1, -1, -1):
119
+ value, digit = divmod(value, 58)
120
+ digits[i] = ALPHABET[digit]
121
+ return "".join(digits)
122
+
123
+
124
+ def _parse_uuid_string(s: str) -> int:
125
+ """Parses the hyphenated or plain UUID form strictly (SPEC.md Section 5.1).
126
+
127
+ ``uuid.UUID()`` and ``int(s, 16)`` are deliberately not used for
128
+ validation: both accept inputs the spec requires to be rejected.
129
+ """
130
+ length = len(s)
131
+ if length == 36:
132
+ for pos in _HYPHEN_POSITIONS:
133
+ if s[pos] != "-":
134
+ raise InvalidCharacterError(
135
+ f"Invalid UUID: expected '-' at position {pos} in {_preview(s)}"
136
+ )
137
+ hex_digits = s[0:8] + s[9:13] + s[14:18] + s[19:23] + s[24:36]
138
+ elif length == 32:
139
+ hex_digits = s
140
+ else:
141
+ raise InvalidLengthError(
142
+ f"Invalid UUID length: expected 32 or 36 characters, got {length} "
143
+ f"in {_preview(s)}"
144
+ )
145
+ # Membership in an explicit ASCII set: no Unicode digits, signs,
146
+ # underscores or whitespace can slip through to int().
147
+ for c in hex_digits:
148
+ if c not in _HEX_DIGITS:
149
+ raise InvalidCharacterError(
150
+ f"Invalid UUID: {c!r} is not a hexadecimal digit in {_preview(s)}"
151
+ )
152
+ return int(hex_digits, 16)
153
+
154
+
155
+ def encode(value: UUIDLike) -> str:
156
+ """Encodes a UUID as a 22-character uuid58 string.
157
+
158
+ ``value`` may be:
159
+
160
+ - a UUID string, hyphenated (``f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf``)
161
+ or plain (32 hex digits), in any letter case. Nothing else is accepted:
162
+ no braces, ``urn:uuid:`` prefix, whitespace or misplaced hyphens;
163
+ - a :class:`uuid.UUID`;
164
+ - exactly 16 :class:`bytes` (or :class:`bytearray`), big-endian
165
+ (``uuid.UUID.bytes`` order);
166
+ - an :class:`int` in ``0..2**128 - 1``.
167
+
168
+ Raises:
169
+ InvalidLengthError: a string of the wrong length, or bytes whose
170
+ length is not 16.
171
+ InvalidCharacterError: a string that is not a valid UUID form.
172
+ ValueOverflowError: an int outside ``0..2**128 - 1``.
173
+ TypeError: any other type (including :class:`bool`).
174
+
175
+ >>> encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf")
176
+ 'XDY9dmBbcMBXqcRvYw8xJ2'
177
+ """
178
+ if isinstance(value, str):
179
+ n = _parse_uuid_string(value)
180
+ elif isinstance(value, _uuid.UUID):
181
+ n = value.int
182
+ elif isinstance(value, (bytes, bytearray)):
183
+ if len(value) != 16:
184
+ raise InvalidLengthError(
185
+ f"Invalid UUID bytes: expected 16 bytes, got {len(value)}"
186
+ )
187
+ n = int.from_bytes(value, "big")
188
+ elif isinstance(value, int) and not isinstance(value, bool):
189
+ if not 0 <= value <= _MAX_UINT128:
190
+ raise ValueOverflowError(
191
+ f"Integer out of range for a 128-bit UUID: {_preview(value)}"
192
+ )
193
+ n = int(value)
194
+ else:
195
+ raise TypeError(
196
+ "encode() expects str, uuid.UUID, bytes, bytearray or int, "
197
+ f"not {type(value).__name__}"
198
+ )
199
+ return _encode_uint128(n)
200
+
201
+
202
+ # --- decoding ---------------------------------------------------------------
203
+
204
+
205
+ def _decode_uint128(s: str) -> int:
206
+ """Decodes per SPEC.md Section 4: length, then characters, then range."""
207
+ if not isinstance(s, str):
208
+ raise TypeError(f"expected str, not {type(s).__name__}")
209
+ if len(s) != _ENCODED_LENGTH:
210
+ raise InvalidLengthError(
211
+ f"Invalid uuid58 length: expected {_ENCODED_LENGTH} characters, "
212
+ f"got {len(s)} in {_preview(s)}"
213
+ )
214
+ value = 0
215
+ for c in s:
216
+ digit = _DIGIT_VALUES.get(c)
217
+ if digit is None:
218
+ raise InvalidCharacterError(
219
+ f"Invalid uuid58 character {c!r} in {_preview(s)}"
220
+ )
221
+ value = value * 58 + digit
222
+ if value > _MAX_UINT128:
223
+ raise ValueOverflowError(f"uuid58 value exceeds 128 bits: {_preview(s)}")
224
+ return value
225
+
226
+
227
+ def decode_int(s: str) -> int:
228
+ """Decodes a uuid58 string to an int in ``0..2**128 - 1``.
229
+
230
+ Raises:
231
+ InvalidLengthError: ``s`` is not exactly 22 characters long.
232
+ InvalidCharacterError: ``s`` contains a character outside the alphabet.
233
+ ValueOverflowError: the value exceeds ``2**128 - 1``.
234
+ TypeError: ``s`` is not a str.
235
+ """
236
+ return _decode_uint128(s)
237
+
238
+
239
+ def decode_bytes(s: str) -> bytes:
240
+ """Decodes a uuid58 string to 16 big-endian bytes.
241
+
242
+ Raises the same errors as :func:`decode_int`.
243
+ """
244
+ return _decode_uint128(s).to_bytes(16, "big")
245
+
246
+
247
+ def decode_uuid(s: str) -> _uuid.UUID:
248
+ """Decodes a uuid58 string to a :class:`uuid.UUID`.
249
+
250
+ Raises the same errors as :func:`decode_int`.
251
+ """
252
+ return _uuid.UUID(int=_decode_uint128(s))
253
+
254
+
255
+ def decode(s: str) -> str:
256
+ """Decodes a uuid58 string to a lowercase, hyphenated UUID string.
257
+
258
+ Raises the same errors as :func:`decode_int`.
259
+
260
+ >>> decode("XDY9dmBbcMBXqcRvYw8xJ2")
261
+ 'f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf'
262
+ """
263
+ h = f"{_decode_uint128(s):032x}"
264
+ return f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
265
+
266
+
267
+ # --- validation and generation ----------------------------------------------
268
+
269
+
270
+ def is_uuid58(s: object) -> bool:
271
+ """Returns True exactly when :func:`decode` would succeed on ``s``.
272
+
273
+ Never raises; any non-str input returns False.
274
+ """
275
+ # Same length and alphabet, so ASCII order equals numeric order
276
+ # (SPEC.md Section 3.2) and comparing with MAX_UUID58 checks the range.
277
+ return (
278
+ isinstance(s, str)
279
+ and len(s) == _ENCODED_LENGTH
280
+ and all(c in _DIGIT_VALUES for c in s)
281
+ and s <= MAX_UUID58
282
+ )
283
+
284
+
285
+ def uuid58() -> str:
286
+ """Generates a random (version 4) UUID and returns its uuid58 encoding."""
287
+ return _encode_uint128(_uuid.uuid4().int)
File without changes