Repository navigation
Expand file tree
/
Copy path_uuidmodule.c
More file actions
1907 lines (1624 loc) · 52.7 KB
/
Copy path_uuidmodule.c
File metadata and controls
1907 lines (1624 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Python UUID module:
* - wraps libuuid or Windows rpcrt4.dll.
* - implements fast version of the uuid.py:UUID class.
* - re-implements uuid4() and uuid7() functions with improved performance
* by virtue of them being implemented in C and better entropy fetching
* strategy.
*
* DCE compatible Universally Unique Identifier library.
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
#include "pycore_long.h" // _PyLong_AsByteArray(), _PyLong_GetOne()
#include "pycore_pylifecycle.h" // _PyOS_URandom()
#include "pycore_runtime_init.h" // _Py_ID()
#include "pycore_strhex.h" // _Py_strhex()
#if defined(HAVE_UUID_H)
// AIX, FreeBSD, libuuid with pkgconf
#include <uuid.h>
#elif defined(HAVE_UUID_UUID_H)
// libuuid without pkgconf
#include <uuid/uuid.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h> // getpid()
#endif
#ifdef HAVE_PROCESS_H
# include <process.h> // getpid()
#endif
#ifdef MS_WINDOWS
# include <windows.h> // GetCurrentProcessId()
#endif
#ifdef MS_WINDOWS
#include <rpc.h>
#ifndef RPC_S_OK
#define RPC_S_OK 0L
#endif
#endif
#include <string.h> // memcpy(), memset(), strncmp()
#ifndef MS_WINDOWS
/*[clinic input]
module _uuid
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7cbed123a45a3859]*/
static PyObject *
py_uuid_generate_time_safe(PyObject *Py_UNUSED(context),
PyObject *Py_UNUSED(ignored))
{
uuid_t uuid;
#ifdef HAVE_UUID_GENERATE_TIME_SAFE
int res;
res = uuid_generate_time_safe(uuid);
return Py_BuildValue("y#i", (const char *) uuid, sizeof(uuid), res);
#elif defined(HAVE_UUID_CREATE)
uint32_t status;
uuid_create(&uuid, &status);
# if defined(HAVE_UUID_ENC_BE)
unsigned char buf[sizeof(uuid)];
uuid_enc_be(buf, &uuid);
return Py_BuildValue("y#i", buf, sizeof(uuid), (int) status);
# else
return Py_BuildValue("y#i", (const char *) &uuid, sizeof(uuid), (int) status);
# endif /* HAVE_UUID_CREATE */
#else /* HAVE_UUID_GENERATE_TIME_SAFE */
uuid_generate_time(uuid);
return Py_BuildValue("y#O", (const char *) uuid, sizeof(uuid), Py_None);
#endif /* HAVE_UUID_GENERATE_TIME_SAFE */
}
#else /* MS_WINDOWS */
static PyObject *
py_UuidCreate(PyObject *Py_UNUSED(context),
PyObject *Py_UNUSED(ignored))
{
UUID uuid;
RPC_STATUS res;
Py_BEGIN_ALLOW_THREADS
res = UuidCreateSequential(&uuid);
Py_END_ALLOW_THREADS
switch (res) {
case RPC_S_OK:
case RPC_S_UUID_LOCAL_ONLY:
case RPC_S_UUID_NO_ADDRESS:
/*
All success codes, but the latter two indicate that the UUID is random
rather than based on the MAC address. If the OS can't figure this out,
neither can we, so we'll take it anyway.
*/
return Py_BuildValue("y#", (const char *)&uuid, sizeof(uuid));
}
PyErr_SetFromWindowsErr(res);
return NULL;
}
static int
py_windows_has_stable_node(void)
{
UUID uuid;
RPC_STATUS res;
Py_BEGIN_ALLOW_THREADS
res = UuidCreateSequential(&uuid);
Py_END_ALLOW_THREADS
return res == RPC_S_OK;
}
#endif /* MS_WINDOWS */
#define UUID_SIZE 16
typedef struct uuidobject {
PyObject_HEAD
uint8_t bytes[UUID_SIZE];
Py_hash_t cached_hash;
PyObject *is_safe;
PyObject *weakreflist;
} uuidobject;
#define uuidobject_CAST(OP) ((uuidobject *)(OP))
// UUID Structure per RFC 9562:
//
// A UUID is 128 bits (16 bytes) represented as:
//
// String: xx xx xx xx - xx xx - Mx xx - Nx xx - xx xx xx xx xx xx
// Byte pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
// Time-based layouts in big-endian order (field widths in bits):
//
// v1: time_low(32) | time_mid(16) | version(4) | time_high(12) |
// variant(2) | clock_seq(14) | node(48)
// v6: time_high(32) | time_mid(16) | version(4) | time_low(12) |
// variant(2) | clock_seq(14) | node(48)
// v7: unix_ts_ms(48) | version(4) | rand_a(12) | variant(2) | rand_b(62)
//
// v1 and v6 encode the same 60-bit timestamp in 100-nanosecond intervals
// since 1582-10-15, with different field ordering. v7 uses milliseconds
// since the Unix epoch. Its rand_a and rand_b fields hold random/counter
// bits, with no clock sequence or node field.
//
// M is the version field: the most significant 4 bits of byte 6.
//
// N contains the variant: the most significant variable bits of byte 8.
// 0xxx: Reserved for NCS compatibility
// 10xx: RFC 4122/9562 (standard)
// 110x: Reserved for Microsoft compatibility
// 111x: Reserved for future definition
#define RANDOM_BUF_SIZE 256
#define MAX_FREE_LIST_SIZE 32
/* State of the _uuid module */
typedef struct {
PyTypeObject *uuid_type;
PyObject *safe_uuid;
PyObject *uint128_max;
PyObject *random_func;
PyObject *random_size_int;
PyObject *time_func;
// A freelist for uuid objects -- 15-20% performance boost.
uuidobject *freelist;
size_t freelist_size;
// We overfetch entropy to speed up successive uuid generations;
// this enables 10x peformance boost.
uint8_t random_buf[RANDOM_BUF_SIZE];
Py_ssize_t random_idx;
uint64_t random_last_pid;
// UUID v7 state
uint64_t last_timestamp_v7;
uint64_t last_counter_v7;
uint8_t last_timestamp_v7_init;
} uuid_state;
#include "clinic/_uuidmodule.c.h"
/*[clinic input]
class _uuid.UUID "uuidobject *" "&uuid_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b62c7d736c192881]*/
// Forward declarations
static int from_hex(uuidobject *self, PyObject *hex);
static int from_bytes_le(uuidobject *self, PyObject *bytes_le);
static int from_int(uuidobject *self, PyObject *int_value, int validate);
static int from_fields(uuidobject *self, PyObject *fields);
static PyObject *get_SafeUUID(uuid_state *state);
static uint64_t
uuid_getpid(void)
{
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
return (uint64_t)getpid();
#else
return (uint64_t)GetCurrentProcessId();
#endif
}
static struct PyModuleDef uuidmodule;
static inline uuid_state *
get_uuid_state(PyObject *mod)
{
uuid_state *state = PyModule_GetState(mod);
assert(state != NULL);
return state;
}
static inline uuid_state *
get_uuid_state_by_cls(PyTypeObject *cls)
{
PyObject *module = PyType_GetModuleByDef(cls, &uuidmodule);
assert(module != NULL);
uuid_state *state = get_uuid_state(module);
assert(state != NULL);
return state;
}
// Forward declaration
static PyObject *uuid_from_bytes_array(PyTypeObject *type, uint8_t bytes[UUID_SIZE]);
static int
gen_time(uuid_state *state, PyTime_t *time)
{
if (state->time_func == NULL) {
return PyTime_Time(time);
}
PyObject *time_func = Py_NewRef(state->time_func);
PyObject *ret = PyObject_CallNoArgs(time_func);
Py_DECREF(time_func);
if (ret == NULL) {
return -1;
}
if (!PyLong_CheckExact(ret)) {
PyErr_SetString(PyExc_ValueError, "time_func must return int");
Py_DECREF(ret);
return -1;
}
int res = PyLong_AsInt64(ret, time);
Py_DECREF(ret);
return res;
}
static int
gen_random_lock_held(PyObject *module, uuid_state *state, uint8_t *bytes,
Py_ssize_t size)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(module);
// Overfetching & caching entropy improves the performance 10x.
// There's a precedent with NodeJS doing exact same thing for
// improving performance of their UUID implementation.
uint64_t pid = uuid_getpid();
if (pid != state->random_last_pid) {
// The main concern to take core of with caching entropy is handling
// fork -- we don't want the child process to share any entropy with
// us. Luckily getpid() is fast.
state->random_last_pid = pid;
state->random_idx = RANDOM_BUF_SIZE;
}
if (state->random_idx + size <= RANDOM_BUF_SIZE) {
memcpy(bytes, state->random_buf + state->random_idx, size);
state->random_idx += size;
}
else {
if (state->random_idx < RANDOM_BUF_SIZE) {
// We exhaustively consume cached entropy. We do that
// because we have tests that compare Python and C
// implementations and it's important that they see incoming
// entropy as a continuous stream.
// The overhead here must be negligible, but we want the same
// code to be run in production and in tests.
Py_ssize_t partial = RANDOM_BUF_SIZE - state->random_idx;
memcpy(bytes, state->random_buf + state->random_idx, partial);
bytes += partial;
size -= partial;
}
// Reserve the cached bytes before a refill can release the module's
// critical section. Another call must not consume the same bytes.
state->random_idx = RANDOM_BUF_SIZE;
uint8_t random_buf[RANDOM_BUF_SIZE];
if (state->random_func != NULL) {
PyObject *random_func = Py_NewRef(state->random_func);
PyObject *buf = PyObject_CallOneArg(
random_func, state->random_size_int);
Py_DECREF(random_func);
if (buf == NULL) {
return -1;
}
if (!PyBytes_CheckExact(buf)) {
PyErr_SetString(PyExc_ValueError, "random_func must return bytes");
Py_DECREF(buf);
return -1;
}
if (PyBytes_Size(buf) != (Py_ssize_t)RANDOM_BUF_SIZE) {
PyErr_Format(
PyExc_ValueError,
"random_func must return bytes of length %zd exactly",
(Py_ssize_t)RANDOM_BUF_SIZE
);
Py_DECREF(buf);
return -1;
}
memcpy(random_buf, PyBytes_AsString(buf), sizeof(random_buf));
Py_DECREF(buf);
}
else {
// _PyOS_URandom() releases the thread state. Fill a private buffer
// so concurrent refills cannot write into the same memory.
if (_PyOS_URandom(random_buf, sizeof(random_buf)) < 0) {
return -1;
}
}
// We hold the caller's module lock again after fetching entropy.
// Replace the cache, discarding any unused bytes from a concurrent refill.
memcpy(state->random_buf, random_buf, sizeof(random_buf));
memcpy(bytes, state->random_buf, size);
state->random_idx = size;
}
return 0;
}
/*[clinic input]
@critical_section
_uuid.uuid4
Generate a random UUID (version 4).
[clinic start generated code]*/
static PyObject *
_uuid_uuid4_impl(PyObject *module)
/*[clinic end generated code: output=b835af30d9d6efc5 input=9cfb3a3b71c25cdf]*/
{
uuid_state *state = get_uuid_state(module);
uint8_t bytes[UUID_SIZE];
if (gen_random_lock_held(module, state, bytes, sizeof(bytes)) < 0) {
return NULL;
}
// Set version (4) and variant
bytes[6] = (uint8_t)((bytes[6] & 0x0f) | 0x40);
bytes[8] = (uint8_t)((bytes[8] & 0x3f) | 0x80);
return uuid_from_bytes_array(state->uuid_type, bytes);
}
static inline int
uuid7_get_counter_and_tail(PyObject *module, uuid_state *state,
uint64_t *counter, uint8_t *tail)
{
uint8_t rand_bytes[10];
if (gen_random_lock_held(module, state, rand_bytes, sizeof(rand_bytes)) < 0) {
return -1;
}
*counter = (((uint64_t)rand_bytes[0] & 0x01) << 40) |
((uint64_t)rand_bytes[1] << 32) |
((uint64_t)rand_bytes[2] << 24) |
((uint64_t)rand_bytes[3] << 16) |
((uint64_t)rand_bytes[4] << 8) |
((uint64_t)rand_bytes[5]);
memcpy(tail, rand_bytes + 6, 4);
return 0;
}
// The module's critical section protects the cached entropy and UUIDv7 state.
// It may be suspended during entropy fetching or a Python testing hook.
/*[clinic input]
@critical_section
_uuid.uuid7
Generate a UUID from a Unix timestamp in milliseconds and random bits.
UUIDv7 objects feature monotonicity within a millisecond.
[clinic start generated code]*/
static PyObject *
_uuid_uuid7_impl(PyObject *module)
/*[clinic end generated code: output=f301accc11162c91 input=88514d61dc785108]*/
{
uuid_state *state = get_uuid_state(module);
uint8_t bytes[UUID_SIZE];
uint64_t timestamp_ms, counter;
PyTime_t pytime;
if (gen_time(state, &pytime) < 0) {
return NULL;
}
uint64_t last_timestamp, last_counter;
uint8_t last_timestamp_init;
do {
last_timestamp = state->last_timestamp_v7;
last_counter = state->last_counter_v7;
last_timestamp_init = state->last_timestamp_v7_init;
timestamp_ms = (uint64_t)(pytime / 1000000);
if (!last_timestamp_init || timestamp_ms > last_timestamp) {
if (uuid7_get_counter_and_tail(module, state, &counter, bytes + 12) < 0) {
return NULL;
}
}
else {
if (timestamp_ms < last_timestamp) {
timestamp_ms = last_timestamp + 1;
}
// advance the 42-bit counter
counter = last_counter + 1;
if (counter > 0x3FFFFFFFFFF) {
// advance the 48-bit timestamp
timestamp_ms += 1;
if (uuid7_get_counter_and_tail(module, state, &counter, bytes + 12) < 0) {
return NULL;
}
}
else {
// This is the common fast path, we only need 4 bytes of entropy
// 32-bit random data
if (gen_random_lock_held(module, state, bytes + 12, 4) < 0) {
return NULL;
}
}
}
// A refill can suspend the critical section and let another call
// advance the state. Recompute instead of committing a stale counter.
} while (last_timestamp != state->last_timestamp_v7 ||
last_counter != state->last_counter_v7 ||
last_timestamp_init != state->last_timestamp_v7_init);
timestamp_ms &= 0xFFFFFFFFFFFF;
bytes[0] = (uint8_t)(timestamp_ms >> 40);
bytes[1] = (uint8_t)(timestamp_ms >> 32);
bytes[2] = (uint8_t)(timestamp_ms >> 24);
bytes[3] = (uint8_t)(timestamp_ms >> 16);
bytes[4] = (uint8_t)(timestamp_ms >> 8);
bytes[5] = (uint8_t)timestamp_ms;
uint16_t counter_hi = (uint16_t)((counter >> 30) & 0x0FFF);
bytes[6] = (uint8_t)(0x70 | (counter_hi >> 8)); // Version 7 = 0111
bytes[7] = (uint8_t)counter_hi;
uint16_t counter_mid = (uint16_t)((counter >> 16) & 0x3FFF);
bytes[8] = (uint8_t)(0x80 | (counter_mid >> 8)); // Variant = 10
bytes[9] = (uint8_t)counter_mid;
uint16_t counter_lo = (uint16_t)(counter & 0xFFFF);
bytes[10] = (uint8_t)(counter_lo >> 8);
bytes[11] = (uint8_t)counter_lo;
state->last_timestamp_v7_init = 1;
state->last_timestamp_v7 = timestamp_ms;
state->last_counter_v7 = counter;
return uuid_from_bytes_array(state->uuid_type, bytes);
}
/*[clinic input]
@critical_section
_uuid._install_c_hooks
*
random_func: object
time_func: object
[clinic start generated code]*/
static PyObject *
_uuid__install_c_hooks_impl(PyObject *module, PyObject *random_func,
PyObject *time_func)
/*[clinic end generated code: output=884aa6e91b2ea832 input=6c5017297067e2ea]*/
{
uuid_state *state = get_uuid_state(module);
// Reset bufferred entropy -- tests need to always start fresh
// when the random function is changed. Reset last_timestamp_v7 --
// important for repeatable tests
state->random_idx = RANDOM_BUF_SIZE;
state->last_timestamp_v7_init = 0;
if (random_func == Py_None) {
Py_CLEAR(state->random_func);
}
else {
Py_XSETREF(state->random_func, Py_NewRef(random_func));
}
if (time_func == Py_None) {
Py_CLEAR(state->time_func);
}
else {
Py_XSETREF(state->time_func, Py_NewRef(time_func));
}
Py_RETURN_NONE;
}
/*[clinic input]
_uuid.UUID.__init__
hex: object = None
bytes: object = None
bytes_le: object = None
fields: object = None
int: object = None
version: object = None
*
is_safe: object = NULL
UUID is a fast base implementation type for uuid.UUID.
[clinic start generated code]*/
static int
_uuid_UUID___init___impl(uuidobject *self, PyObject *hex, PyObject *bytes,
PyObject *bytes_le, PyObject *fields,
PyObject *int_value, PyObject *version,
PyObject *is_safe)
/*[clinic end generated code: output=6d100803f5ecd751 input=23c754454cc11724]*/
{
// Explicit None values do not select a UUID input form.
int passed = 0;
if (hex != Py_None) passed++;
if (bytes != Py_None) passed++;
if (bytes_le != Py_None) passed++;
if (fields != Py_None) passed++;
if (int_value != Py_None) passed++;
if (passed != 1) {
PyErr_SetString(
PyExc_TypeError,
"one of the hex, bytes, bytes_le, fields, or int arguments must be given"
);
return -1;
}
if (hex != Py_None) {
if (from_hex(self, hex) < 0) {
return -1;
}
}
else if (bytes != Py_None) {
if (!PyBytes_Check(bytes)) {
PyErr_SetString(PyExc_TypeError, "bytes must be a bytes object");
return -1;
}
if (PyBytes_GET_SIZE(bytes) != UUID_SIZE) {
PyErr_SetString(
PyExc_ValueError,
"bytes is not a 16-char string"
);
return -1;
}
memcpy(self->bytes, PyBytes_AS_STRING(bytes), sizeof(self->bytes));
}
else if (bytes_le != Py_None) {
if (from_bytes_le(self, bytes_le) < 0) {
return -1;
}
}
else if (fields != Py_None) {
if (from_fields(self, fields) < 0) {
return -1;
}
}
else if (int_value != Py_None) {
if (from_int(self, int_value, 1) < 0) {
return -1;
}
}
else {
Py_UNREACHABLE();
}
if (version != Py_None) {
long version_num = PyLong_AsLong(version);
if (version_num == -1 && PyErr_Occurred()) {
return -1;
}
if (version_num < 1 || version_num > 8) {
PyErr_SetString(PyExc_ValueError, "illegal version number");
return -1;
}
// Clear variant bits (keep only lower 6 bits of byte 8)
self->bytes[8] &= 0x3f; // 0011 1111
// Clear version bits (keep only lower 4 bits of byte 6)
self->bytes[6] &= 0x0f; // 0000 1111
// Set the variant to RFC 4122/9562 (binary 10xx xxxx)
self->bytes[8] |= 0x80; // 1000 0000
// Set the version number (upper 4 bits of byte 6)
self->bytes[6] |= (uint8_t)(version_num << 4);
}
Py_XSETREF(self->is_safe, Py_XNewRef(is_safe));
return 0;
}
static const uint8_t INT_TO_HEX[] = "0123456789abcdef";
// Lookup table for hex character to value conversion
// -1 for invalid characters
static const int8_t HEX_TO_INT[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
static inline void
byte_to_hex(uint8_t byte, char *hex)
{
hex[0] = INT_TO_HEX[(byte >> 4) & 0xf];
hex[1] = INT_TO_HEX[byte & 0xf];
}
static int
from_hex(uuidobject *self, PyObject *hex)
{
Py_ssize_t size;
const char *start = PyUnicode_AsUTF8AndSize(hex, &size);
if (start == NULL) {
return -1;
}
uint8_t ch;
uint8_t acc, acc_set;
int8_t part;
int i, j;
// Reimplement `hex = hex.replace('urn:', '').replace('uuid:', '')`
if (size > 0 && start[0] == 'u') {
if (size >= 9 && (strncmp(start, "urn:uuid:", 9) == 0 ||
strncmp(start, "uuid:urn:", 9) == 0)) {
start += 9;
size -= 9;
}
else if (size >= 4 && strncmp(start, "urn:", 4) == 0) {
start += 4;
size -= 4;
}
else if (size >= 5 && strncmp(start, "uuid:", 5) == 0) {
start += 5;
size -= 5;
}
}
// Reimplement `hex = hex.strip('{}')`
while (size >= 1 && (start[0] == '{' || start[0] == '}')) {
start++;
size -= 1;
}
while (size >= 1 && (start[size - 1] == '{' || start[size - 1] == '}')) {
size -= 1;
}
if (size < 32) {
PyErr_SetString(
PyExc_ValueError,
"badly formed hexadecimal UUID string"
);
return -1;
}
acc_set = 0;
j = 0;
for (i = 0; i < size; i++) {
ch = (uint8_t)start[i];
if (ch == '-') {
continue;
}
part = HEX_TO_INT[ch];
if (part == -1) {
PyErr_SetString(
PyExc_ValueError,
"badly formed hexadecimal UUID string"
);
return -1;
}
if (acc_set) {
acc |= (uint8_t)part;
self->bytes[j] = acc;
acc_set = 0;
j++;
}
else {
acc = (uint8_t)(part << 4);
acc_set = 1;
}
if (j > UUID_SIZE || (j == UUID_SIZE && acc_set)) {
PyErr_Format(PyExc_ValueError,
"invalid UUID '%s': decodes to more than 16 bytes",
hex);
return -1;
}
}
if (j != UUID_SIZE) {
PyErr_Format(PyExc_ValueError,
"invalid UUID '%s': decodes to less than 16 bytes",
hex);
return -1;
}
return 0;
}
static int
from_bytes_le(uuidobject *self, PyObject *bytes_le)
{
if (!PyBytes_Check(bytes_le)) {
PyErr_SetString(PyExc_TypeError, "bytes_le must be a bytes object");
return -1;
}
if (PyBytes_GET_SIZE(bytes_le) != UUID_SIZE) {
PyErr_SetString(PyExc_ValueError,
"bytes_le is not a 16-char string");
return -1;
}
// Convert from little-endian to big-endian UUID format
// UUID fields in little-endian order need to be byte-swapped:
// - time_low (4 bytes)
// - time_mid (2 bytes)
// - time_hi_version (2 bytes)
// - clock_seq_hi_variant (1 byte) - no swap needed
// - clock_seq_low (1 byte) - no swap needed
// - node (6 bytes) - no swap needed
const unsigned char *src = (const unsigned char *)PyBytes_AS_STRING(bytes_le);
unsigned char *dst = (unsigned char *)self->bytes;
// Swap time_low (bytes 0-3)
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
// Swap time_mid (bytes 4-5)
dst[4] = src[5];
dst[5] = src[4];
// Swap time_hi_version (bytes 6-7)
dst[6] = src[7];
dst[7] = src[6];
// Copy clock_seq and node as-is (bytes 8-15)
memcpy(dst + 8, src + 8, 8);
return 0;
}
static int
validate_int(uuid_state *state, PyObject *int_value)
{
if (!PyLong_Check(int_value)) {
PyErr_SetString(PyExc_TypeError, "value must be an integer");
return -1;
}
int cmp = PyLong_IsNegative(int_value);
if (cmp < 0) {
return -1;
}
if (cmp == 1) {
PyErr_SetString(PyExc_ValueError,
"int is out of range (need a 128-bit value)");
return -1;
}
// Check if it's greater than max (2^128 - 1)
cmp = PyObject_RichCompareBool(int_value, state->uint128_max, Py_GT);
if (cmp < 0) {
return -1;
}
if (cmp == 1) {
PyErr_SetString(PyExc_ValueError,
"int is out of range (need a 128-bit value)");
return -1;
}
return 0;
}
static int
from_int(uuidobject *self, PyObject *int_value, int validate)
{
// Convert a 128-bit integer to UUID bytes (big-endian)
uuid_state *state = get_uuid_state_by_cls(Py_TYPE(self));
if (validate && validate_int(state, int_value) < 0) {
return -1;
}
return _PyLong_AsByteArray(
(PyLongObject *)int_value,
(unsigned char *)self->bytes,
sizeof(self->bytes),
0, // big-endian
0, // unsigned
1 // with_exceptions
);
}
static int
extract_field(
PyObject *fields,
int field_num,
uint64_t max_value,
const char *error_msg,
uint64_t *result
) {
PyObject *field = PySequence_GetItem(fields, field_num);
if (field == NULL) {
return -1;
}
if (!PyLong_Check(field)) {
PyErr_Format(PyExc_TypeError, "field %d must be an integer", field_num);
goto fail;
}
uint64_t value;
if (PyLong_AsUInt64(field, &value) < 0) {
goto fail;
}
if (value > max_value) {
PyErr_SetString(PyExc_ValueError, error_msg);
goto fail;
}
*result = value;
Py_DECREF(field);
return 0;
fail:
Py_DECREF(field);
return -1;
}
static int
from_fields(uuidobject *self, PyObject *fields)
{
// Validate the length without replacing errors raised by __len__.
Py_ssize_t len = PySequence_Size(fields);
if (len < 0) {
return -1;
}
if (len != 6) {
PyErr_SetString(PyExc_ValueError, "fields is not a 6-tuple");
return -1;
}
#define EXTRACT_FIELD(FIELD_NUM, MAX_VALUE, ERROR_MSG, TYPE, NAME) \
TYPE NAME; \
do { \
uint64_t NAME##_extracted; \
if (extract_field(fields, FIELD_NUM, MAX_VALUE, ERROR_MSG, \
&NAME##_extracted) < 0) \
{ \
return -1; \
} \
NAME = (TYPE)NAME##_extracted; \
} while (0)
EXTRACT_FIELD(
0, (1ULL << 32) - 1, "field 1 out of range (need a 32-bit value)",
uint32_t, time_low
);
EXTRACT_FIELD(
1, (1ULL << 16) - 1, "field 2 out of range (need a 16-bit value)",
uint16_t, time_mid
);
EXTRACT_FIELD(
2, (1ULL << 16) - 1, "field 3 out of range (need a 16-bit value)",
uint16_t, time_hi_version
);
EXTRACT_FIELD(
3, (1ULL << 8) - 1, "field 4 out of range (need an 8-bit value)",
uint8_t, clock_seq_hi_variant
);
EXTRACT_FIELD(
4, (1ULL << 8) - 1, "field 5 out of range (need an 8-bit value)",
uint8_t, clock_seq_low
);
EXTRACT_FIELD(
5, (1ULL << 48) - 1, "field 6 out of range (need a 48-bit value)",
uint64_t, node
);
#undef EXTRACT_FIELD
self->bytes[0] = (uint8_t)(time_low >> 24);
self->bytes[1] = (uint8_t)(time_low >> 16);
self->bytes[2] = (uint8_t)(time_low >> 8);
self->bytes[3] = (uint8_t)time_low;
self->bytes[4] = (uint8_t)(time_mid >> 8);
self->bytes[5] = (uint8_t)time_mid;
self->bytes[6] = (uint8_t)(time_hi_version >> 8);
self->bytes[7] = (uint8_t)time_hi_version;
self->bytes[8] = clock_seq_hi_variant;
self->bytes[9] = clock_seq_low;
self->bytes[10] = (uint8_t)(node >> 40);
self->bytes[11] = (uint8_t)(node >> 32);
self->bytes[12] = (uint8_t)(node >> 24);
self->bytes[13] = (uint8_t)(node >> 16);
self->bytes[14] = (uint8_t)(node >> 8);
self->bytes[15] = (uint8_t)node;
return 0;
}
static PyObject *
get_int(uuidobject *self)
{
return _PyLong_FromByteArray(
(unsigned char *)self->bytes, sizeof(self->bytes), 0, 0);
}
static PyObject *
get_uuidmod_attr(const char *name)
{
return PyImport_ImportModuleAttrString("uuid", name);
}
static PyObject *
get_SafeUUID(uuid_state *state)
{
if (state->safe_uuid != NULL) {
return Py_NewRef(state->safe_uuid);
}
state->safe_uuid = get_uuidmod_attr("SafeUUID");
return Py_XNewRef(state->safe_uuid);
}
static uuidobject *
make_uuid(PyTypeObject *type)
{
uuidobject *self = NULL;
uuid_state *state = get_uuid_state_by_cls(type);
if (type != state->uuid_type) {