Debian Codegraph @

src/ulid_transform/_ulid_impl.cpp

raw symbols SCIP
1 #include "Python.h"
2
3 #include <cmath>
4 #include <string.h>
5
6 #ifdef __SIZEOF_INT128__
7 #include "ulid_uint128.hh"
8 #else
9 #include "ulid_struct.hh"
10 #endif
11
12 #if defined(__has_builtin)
13 #if __has_builtin(__builtin_expect)
14 #define ULID_LIKELY(x) __builtin_expect(!!(x), 1)
15 #else
16 #define ULID_LIKELY(x) (x)
17 #endif
18 #elif defined(__GNUC__)
19 #define ULID_LIKELY(x) __builtin_expect(!!(x), 1)
20 #else
21 #define ULID_LIKELY(x) (x)
22 #endif
23
24 constexpr Py_ssize_t ULID_BYTES_LEN = 16;
25 constexpr Py_ssize_t ULID_TEXT_LEN = 26;
26 constexpr Py_ssize_t ULID_HEX_LEN = 32;
27
28 /**
29 * Create a PyUnicode object from a known-ASCII buffer without validation.
30 * All callers MUST GUARANTEE the buffer contains only ASCII characters.
31 */
32 static inline PyObject*
33 unicode_from_ascii_buf(const char* buf, Py_ssize_t len)
34 {
35 PyObject* str = PyUnicode_New(len, 127);
36 if (!str) {
37 return NULL;
38 }
39 // This is likely on any and all current versions of CPython.
40 if (ULID_LIKELY(PyUnicode_IS_COMPACT_ASCII(str))) {
41 memcpy(PyUnicode_DATA(str), buf, len);
42 } else {
43 // Unexpected layout; copy character-by-character via public API.
44 for (Py_ssize_t i = 0; i < len; i++)
45 PyUnicode_WriteChar(str, i, (unsigned char)buf[i]);
46 }
47 return str;
48 }
49
50 static inline void
51 hexlify_16(const uint8_t b[ULID_BYTES_LEN], char dst[ULID_HEX_LEN])
52 {
53 static const char hexdigits[17] = "0123456789abcdef";
54 for (int i = 0, j = 0; i < ULID_BYTES_LEN; i++) {
55 dst[j++] = hexdigits[b[i] >> 4];
56 dst[j++] = hexdigits[b[i] & 0x0f];
57 }
58 }
59
60 static inline uint64_t
61 bytes_to_timestamp(const uint8_t b[ULID_BYTES_LEN])
62 {
63 return (static_cast<uint64_t>(b[0]) << 40) | (static_cast<uint64_t>(b[1]) << 32)
64 | (static_cast<uint64_t>(b[2]) << 24) | (static_cast<uint64_t>(b[3]) << 16)
65 | (static_cast<uint64_t>(b[4]) << 8) | static_cast<uint64_t>(b[5]);
66 }
67
68 /* ulid_hex() -> str */
69 static PyObject*
70 py_ulid_hex(PyObject* module, PyObject* Py_UNUSED(ignored))
71 {
72 ulid::ULID ulid;
73 ulid::EncodeTimeSystemClockNow(ulid);
74 ulid::EncodeEntropyFast(ulid);
75 uint8_t buf[ULID_BYTES_LEN];
76 ulid::MarshalBinaryTo(ulid, buf);
77 char hex[ULID_HEX_LEN];
78 hexlify_16(buf, hex);
79 return unicode_from_ascii_buf(hex, ULID_HEX_LEN); // SAFETY: Hexadecimal digits are ASCII characters
80 }
81
82 /* ulid_now_bytes() -> bytes */
83 static PyObject*
84 py_ulid_now_bytes(PyObject* module, PyObject* Py_UNUSED(ignored))
85 {
86 ulid::ULID ulid;
87 ulid::EncodeTimeSystemClockNow(ulid);
88 ulid::EncodeEntropyFast(ulid);
89 uint8_t buf[ULID_BYTES_LEN];
90 ulid::MarshalBinaryTo(ulid, buf);
91 return PyBytes_FromStringAndSize((const char*)buf, ULID_BYTES_LEN);
92 }
93
94 /* Validate a timestamp (in seconds) and convert to milliseconds.
95 * Returns 0 on success, -1 on error (with a Python exception set).
96 * Error types/messages mirror what int(ts * 1000).to_bytes(6, 'big') raises
97 * in the Python implementation, so the two impls have exception-type parity.
98 */
99 static inline int
100 validate_timestamp_ms(double ts, int64_t* out_ms)
101 {
102 if (std::isnan(ts)) {
103 PyErr_SetString(PyExc_ValueError,
104 "cannot convert float NaN to integer");
105 return -1;
106 }
107 if (std::isinf(ts)) {
108 PyErr_SetString(PyExc_OverflowError,
109 "cannot convert float infinity to integer");
110 return -1;
111 }
112 double ts_ms = ts * 1000.0;
113 if (ts_ms < 0.0) {
114 PyErr_SetString(PyExc_OverflowError,
115 "can't convert negative int to unsigned");
116 return -1;
117 }
118 // ULID timestamps are 48-bit unsigned milliseconds.
119 // 2^48 (281474976710656) is the exclusive upper bound and is exactly
120 // representable as a double, so the comparison is precise here.
121 if (ts_ms >= 281474976710656.0) {
122 PyErr_SetString(PyExc_OverflowError,
123 "int too big to convert");
124 return -1;
125 }
126 *out_ms = static_cast<int64_t>(ts_ms);
127 return 0;
128 }
129
130 /* ulid_at_time_bytes(timestamp) -> bytes */
131 static PyObject*
132 py_ulid_at_time_bytes(PyObject* module, PyObject* arg)
133 {
134 double ts = PyFloat_AsDouble(arg);
135 if (ts == -1.0 && PyErr_Occurred())
136 return NULL;
137 int64_t ts_ms;
138 if (validate_timestamp_ms(ts, &ts_ms) < 0)
139 return NULL;
140 ulid::ULID ulid;
141 ulid::EncodeTimestamp(ts_ms, ulid);
142 ulid::EncodeEntropyFast(ulid);
143 uint8_t buf[ULID_BYTES_LEN];
144 ulid::MarshalBinaryTo(ulid, buf);
145 return PyBytes_FromStringAndSize((const char*)buf, ULID_BYTES_LEN);
146 }
147
148 /* ulid_now() -> str */
149 static PyObject*
150 py_ulid_now(PyObject* module, PyObject* Py_UNUSED(ignored))
151 {
152 ulid::ULID ulid;
153 ulid::EncodeTimeSystemClockNow(ulid);
154 ulid::EncodeEntropyFast(ulid);
155 char buf[ULID_TEXT_LEN];
156 ulid::MarshalTo(ulid, buf);
157 return unicode_from_ascii_buf(buf, ULID_TEXT_LEN); // SAFETY: text ULIDs are ASCII
158 }
159
160 /* ulid_at_time(timestamp) -> str */
161 static PyObject*
162 py_ulid_at_time(PyObject* module, PyObject* arg)
163 {
164 double ts = PyFloat_AsDouble(arg);
165 if (ts == -1.0 && PyErr_Occurred())
166 return NULL;
167 int64_t ts_ms;
168 if (validate_timestamp_ms(ts, &ts_ms) < 0)
169 return NULL;
170 ulid::ULID ulid;
171 ulid::EncodeTimestamp(ts_ms, ulid);
172 ulid::EncodeEntropyFast(ulid);
173 char buf[ULID_TEXT_LEN];
174 ulid::MarshalTo(ulid, buf);
175 return unicode_from_ascii_buf(buf, ULID_TEXT_LEN); // SAFETY: text ULIDs are ASCII
176 }
177
178 /* ulid_to_bytes(value) -> bytes */
179 static PyObject*
180 py_ulid_to_bytes(PyObject* module, PyObject* arg)
181 {
182 if (!PyUnicode_Check(arg)) {
183 PyErr_Format(PyExc_TypeError,
184 "ULID must be a string, not %.200s",
185 Py_TYPE(arg)->tp_name);
186 return NULL;
187 }
188 Py_ssize_t len;
189 const char* str = PyUnicode_AsUTF8AndSize(arg, &len);
190 if (!str)
191 return NULL;
192 // len is the UTF-8 byte length. A non-ASCII string can still be exactly
193 // 26 bytes (e.g. 13 two-byte codepoints), so an ASCII check is required to
194 // reject it — otherwise DecodeBase32To reads garbage. Mirrors the Python
195 // impl's `len(value) != 26 or not value.isascii()`.
196 if (len != ULID_TEXT_LEN || !PyUnicode_IS_ASCII(arg)) {
197 PyErr_Format(PyExc_ValueError,
198 "ULID must be a 26 character string: %R", arg);
199 return NULL;
200 }
201 uint8_t buf[ULID_BYTES_LEN];
202 ulid::DecodeBase32To(str, buf);
203 return PyBytes_FromStringAndSize((const char*)buf, ULID_BYTES_LEN);
204 }
205
206 /* bytes_to_ulid(value) -> str */
207 static PyObject*
208 py_bytes_to_ulid(PyObject* module, PyObject* arg)
209 {
210 if (!PyBytes_Check(arg)) {
211 PyErr_Format(PyExc_TypeError,
212 "ULID bytes must be bytes, not %.200s",
213 Py_TYPE(arg)->tp_name);
214 return NULL;
215 }
216 if (PyBytes_GET_SIZE(arg) != ULID_BYTES_LEN) {
217 PyErr_Format(PyExc_ValueError,
218 "ULID bytes must be 16 bytes: %R", arg);
219 return NULL;
220 }
221 char buf[ULID_TEXT_LEN];
222 ulid::EncodeBase32From((const uint8_t*)PyBytes_AS_STRING(arg), buf);
223 return unicode_from_ascii_buf(buf, ULID_TEXT_LEN); // SAFETY: base32 is ASCII
224 }
225
226 /* ulid_to_bytes_or_none(ulid) -> bytes | None */
227 static PyObject*
228 py_ulid_to_bytes_or_none(PyObject* module, PyObject* arg)
229 {
230 if (arg == Py_None || !PyUnicode_Check(arg))
231 Py_RETURN_NONE;
232 Py_ssize_t len;
233 const char* str = PyUnicode_AsUTF8AndSize(arg, &len);
234 if (!str)
235 return NULL;
236 // See py_ulid_to_bytes: a non-ASCII string can be exactly 26 UTF-8 bytes,
237 // so reject anything non-ASCII to match the Python impl returning None.
238 if (len != ULID_TEXT_LEN || !PyUnicode_IS_ASCII(arg))
239 Py_RETURN_NONE;
240 uint8_t buf[ULID_BYTES_LEN];
241 ulid::DecodeBase32To(str, buf);
242 return PyBytes_FromStringAndSize((const char*)buf, ULID_BYTES_LEN);
243 }
244
245 /* bytes_to_ulid_or_none(ulid_bytes) -> str | None */
246 static PyObject*
247 py_bytes_to_ulid_or_none(PyObject* module, PyObject* arg)
248 {
249 if (arg == Py_None || !PyBytes_Check(arg) || PyBytes_GET_SIZE(arg) != ULID_BYTES_LEN)
250 Py_RETURN_NONE;
251 char buf[ULID_TEXT_LEN];
252 ulid::EncodeBase32From((const uint8_t*)PyBytes_AS_STRING(arg), buf);
253 return unicode_from_ascii_buf(buf, ULID_TEXT_LEN); // SAFETY: base32 is ASCII
254 }
255
256 /* ulid_to_timestamp(ulid) -> int */
257 static PyObject*
258 py_ulid_to_timestamp(PyObject* module, PyObject* arg)
259 {
260 if (PyBytes_Check(arg)) {
261 if (PyBytes_GET_SIZE(arg) != ULID_BYTES_LEN) {
262 PyErr_Format(PyExc_ValueError,
263 "ULID bytes must be 16 bytes: %R", arg);
264 return NULL;
265 }
266 uint64_t ts = bytes_to_timestamp(
267 (const uint8_t*)PyBytes_AS_STRING(arg));
268 return PyLong_FromUnsignedLongLong(ts);
269 }
270 if (!PyUnicode_Check(arg)) {
271 PyErr_Format(PyExc_TypeError,
272 "ULID must be a string or bytes, not %.200s",
273 Py_TYPE(arg)->tp_name);
274 return NULL;
275 }
276 Py_ssize_t len;
277 const char* str = PyUnicode_AsUTF8AndSize(arg, &len);
278 if (!str)
279 return NULL;
280 // See py_ulid_to_bytes: a non-ASCII string can be exactly 26 UTF-8 bytes,
281 // so reject anything non-ASCII to match the Python impl raising ValueError.
282 if (len != ULID_TEXT_LEN || !PyUnicode_IS_ASCII(arg)) {
283 PyErr_Format(PyExc_ValueError,
284 "ULID must be a 26 character string: %R", arg);
285 return NULL;
286 }
287 uint8_t buf[ULID_BYTES_LEN];
288 ulid::DecodeBase32To(str, buf);
289 uint64_t ts = bytes_to_timestamp(buf);
290 return PyLong_FromUnsignedLongLong(ts);
291 }
292
293 static PyMethodDef module_methods[] = {
294 { "ulid_hex", py_ulid_hex, METH_NOARGS,
295 "ulid_hex()\n--\n\n"
296 "Generate a ULID in lowercase hex that will work for a UUID.\n\n"
297 "This ulid should not be used for cryptographically secure\n"
298 "operations.\n\n"
299 "This string can be converted with https://github.com/ahawker/ulid\n\n"
300 "ulid.from_uuid(uuid.UUID(ulid_hex))" },
301 { "ulid_now_bytes", py_ulid_now_bytes, METH_NOARGS,
302 "ulid_now_bytes()\n--\n\n"
303 "Generate an ULID as 16 bytes that will work for a UUID." },
304 { "ulid_at_time_bytes", py_ulid_at_time_bytes, METH_O,
305 "ulid_at_time_bytes($self, timestamp, /)\n--\n\n"
306 "Generate an ULID as 16 bytes that will work for a UUID.\n\n"
307 "uuid.UUID(bytes=ulid_bytes)" },
308 { "ulid_now", py_ulid_now, METH_NOARGS,
309 "ulid_now()\n--\n\n"
310 "Generate a ULID." },
311 { "ulid_at_time", py_ulid_at_time, METH_O,
312 "ulid_at_time($self, timestamp, /)\n--\n\n"
313 "Generate a ULID.\n\n"
314 "This ulid should not be used for cryptographically secure\n"
315 "operations.\n\n"
316 " 01AN4Z07BY 79KA1307SR9X4MV3\n"
317 "|----------| |----------------|\n"
318 " Timestamp Randomness\n"
319 " 48bits 80bits\n\n"
320 "This string can be loaded directly with https://github.com/ahawker/ulid\n\n"
321 "import ulid_transform as ulid_util\n"
322 "import ulid\n"
323 "ulid.parse(ulid_util.ulid())" },
324 { "ulid_to_bytes", py_ulid_to_bytes, METH_O,
325 "ulid_to_bytes($self, value, /)\n--\n\n"
326 "Decode a ulid to bytes." },
327 { "bytes_to_ulid", py_bytes_to_ulid, METH_O,
328 "bytes_to_ulid($self, value, /)\n--\n\n"
329 "Encode bytes to a ulid." },
330 { "ulid_to_bytes_or_none", py_ulid_to_bytes_or_none, METH_O,
331 "ulid_to_bytes_or_none($self, ulid, /)\n--\n\n"
332 "Convert an ulid to bytes." },
333 { "bytes_to_ulid_or_none", py_bytes_to_ulid_or_none, METH_O,
334 "bytes_to_ulid_or_none($self, ulid_bytes, /)\n--\n\n"
335 "Convert bytes to a ulid." },
336 { "ulid_to_timestamp", py_ulid_to_timestamp, METH_O,
337 "ulid_to_timestamp($self, ulid, /)\n--\n\n"
338 "Get the timestamp from a ULID.\n"
339 "The returned value is in milliseconds since the UNIX epoch." },
340 { NULL, NULL, 0, NULL }
341 };
342
343 static struct PyModuleDef moduledef = {
344 PyModuleDef_HEAD_INIT,
345 "ulid_transform._ulid_impl",
346 NULL,
347 -1,
348 module_methods,
349 };
350
351 PyMODINIT_FUNC
352 PyInit__ulid_impl(void)
353 {
354 return PyModule_Create(&moduledef);
355 }