-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuuid.py
60 lines (51 loc) · 1.97 KB
/
uuid.py
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
# Copyright (c) Quectel Wireless Solution, Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file :uuid.py
@author :Jack Sun (jack.sun@quectel.com)
@brief :<description>
@version :1.0.0
@date :2024-03-15 10:38:22
@copyright :Copyright (c) 2024
"""
import urandom
int_ = int # The built-in int type
bytes_ = bytes # The built-in bytes type
class UUID:
def __init__(self, bytes=None, version=None, int=None):
if bytes is not None:
if len(bytes) != 16:
raise ValueError('bytes is not a 16-char string')
assert isinstance(bytes, bytes_), repr(bytes)
int = int_.from_bytes(bytes, "big")
if int is not None:
if not 0 <= int < (1 << 128):
raise ValueError('int is out of range (need a 128-bit value)')
if version is not None:
if not 1 <= version <= 5:
raise ValueError('illegal version number')
# Set the variant to RFC 4122.
int &= ~(0xc000 << 48)
int |= 0x8000 << 48
# Set the version number.
int &= ~(0xf000 << 64)
int |= version << 76
self.int = int
def __str__(self):
hex = '%032x' % self.int
return '%s-%s-%s-%s-%s' % (hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
def uuid4():
return UUID(bytes=bytes([urandom.getrandbits(8) for _ in range(16)]), version=4)