fix __init_bits and make it cross-platform (i.e., support Windows)

This commit is contained in:
Michael Becker 2024-12-22 22:08:30 -05:00
parent e6a28a3b03
commit 8c15252151
Signed by: beckermj
GPG Key ID: 24F8DAA73DCB2C8F

View File

@ -16,13 +16,36 @@ class UUIDParseResult:
self.kind = kind
self.message = message
class URandom:
def __init__(self):
try:
self.__urand = open("/dev/urandom", "rb")
except:
self.__urand = None
def read(self, length : int) -> bytes:
if self.__urand is not None:
return self.__urand.read(length)
else:
# If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
# __pr_bits = ""
# for cnt in range(0, 16):
# __pr_bits += chr ( __mt_rand ( 0, 255 ) )
pass
import os
return os.urandom(length)
class Guid:
__urand = None
def __init__(self):
if Guid.__urand is None:
Guid.__urand = open("/dev/urandom", "rb")
Guid.__urand = URandom()
self.__a = 0
self.__b = 0
@ -80,7 +103,7 @@ class Guid:
guidBytes = [ myBytes[3], myBytes[2], myBytes[1], myBytes[0], myBytes[5], myBytes[4], myBytes[7], myBytes[6], myBytes[8],
myBytes[9], myBytes[10], myBytes[11], myBytes[12], myBytes[13], myBytes[14], myBytes[15] ]
result.parsedGuid = Guid.fromBytes(guidBytes)
result.parsedGuid = Guid.from_bytes(guidBytes)
return result
"""
@ -228,25 +251,20 @@ class Guid:
)
@staticmethod
def __init_bits():
__pr_bits = False
if Guid.__urand is not None:
__pr_bits += Guid.__urand.read(16)
if not self.__pr_bits:
fp = open ( '/dev/urandom', 'rb' )
if fp is not False:
__pr_bits += fp.read(16)
fp.close()
else:
# If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
__pr_bits = ""
for cnt in range(0, 16):
__pr_bits += chr ( __mt_rand ( 0, 255 ) )
return __pr_bits
def __init_bits(self):
self.pr_bits = Guid.__urand.read(16)
self.__a = (int(self.pr_bits[3]) << 24) | (int(self.pr_bits[2]) << 16) | (int(self.pr_bits[1]) << 8) | self.pr_bits[0]
self.__b = ((int(self.pr_bits[5]) << 8) | self.pr_bits[4])
self.__c = ((int(self.pr_bits[7]) << 8) | self.pr_bits[6])
self.__d = self.pr_bits[8]
self.__e = self.pr_bits[9]
self.__f = self.pr_bits[10]
self.__g = self.pr_bits[11]
self.__h = self.pr_bits[12]
self.__i = self.pr_bits[13]
self.__j = self.pr_bits[14]
self.__k = self.pr_bits[15]
"""
@brief Generates a Universally Unique IDentifier, version 4.
@ -261,20 +279,7 @@ class Guid:
@staticmethod
def generate():
uuid = Guid()
__pr_bits = Guid.__init_bits()
uuid.__a = (int(pr_bits[3]) << 24) | (int(pr_bits[2]) << 16) | (int(pr_bits[1]) << 8) | pr_bits[0]
uuid.__b = ((int(pr_bits[5]) << 8) | pr_bits[4])
uuid.__c = ((int(pr_bits[7]) << 8) | pr_bits[6])
uuid.__d = pr_bits[8]
uuid.__e = pr_bits[9]
uuid.__f = pr_bits[10]
uuid.__g = pr_bits[11]
uuid.__h = pr_bits[12]
uuid.__i = pr_bits[13]
uuid.__j = pr_bits[14]
uuid.__k = pr_bits[15]
uuid.__init_bits()
return uuid
@staticmethod