Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/lib/uuid.py
1398 views
1
# vim:fileencoding=utf-8
2
# License: BSD Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
3
# globals: crypto
4
from __python__ import hash_literals
5
6
from encodings import hexlify, urlsafe_b64decode, urlsafe_b64encode
7
8
RFC_4122 = 1
9
10
if jstype(crypto) is 'object' and crypto.getRandomValues:
11
random_bytes = def (num):
12
ans = Uint8Array(num or 16)
13
crypto.getRandomValues(ans)
14
return ans
15
else:
16
random_bytes = def (num):
17
ans = Uint8Array(num or 16)
18
for i in range(ans.length):
19
ans[i] = Math.floor(Math.random() * 256)
20
return ans
21
22
23
def uuid4_bytes():
24
data = random_bytes()
25
data[6] = 0b01000000 | (data[6] & 0b1111)
26
data[8] = (((data[8] >> 4) & 0b11 | 0b1000) << 4) | (data[8] & 0b1111)
27
return data
28
29
30
def as_str():
31
h = this.hex
32
return h[:8] + '-' + h[8:12] + '-' + h[12:16] + '-' + h[16:20] + '-' + h[20:]
33
34
35
def uuid4():
36
b = uuid4_bytes()
37
return {
38
'hex': hexlify(b),
39
'bytes': b,
40
'variant': RFC_4122,
41
'version': 4,
42
'__str__': as_str,
43
'toString': as_str,
44
}
45
46
47
def num_to_string(numbers, alphabet, pad_to_length):
48
ans = v'[]'
49
alphabet_len = alphabet.length
50
numbers = Array.prototype.slice.call(numbers)
51
for v'var i = 0; i < numbers.length - 1; i++':
52
x = divmod(numbers[i], alphabet_len)
53
numbers[i] = x[0]
54
numbers[i+1] += x[1]
55
for v'var i = 0; i < numbers.length; i++':
56
number = numbers[i]
57
while number:
58
x = divmod(number, alphabet_len)
59
number = x[0]
60
ans.push(alphabet[x[1]])
61
if pad_to_length and pad_to_length > ans.length:
62
ans.push(alphabet[0].repeat(pad_to_length - ans.length))
63
return ans.join('')
64
65
66
def short_uuid():
67
# A totally random uuid encoded using only URL and filename safe characters
68
return urlsafe_b64encode(random_bytes(), '')
69
70
71
def short_uuid4():
72
# A uuid4 encoded using only URL and filename safe characters
73
return urlsafe_b64encode(uuid4_bytes(), '')
74
75
76
def decode_short_uuid(val):
77
return urlsafe_b64decode(val + '==')
78
79