50 lines
1.1 KiB
GDScript
50 lines
1.1 KiB
GDScript
class_name Guid
|
|
extends Resource
|
|
|
|
@export var bytes: PackedByteArray
|
|
|
|
|
|
static func new_guid() -> Guid:
|
|
var guid = Guid.new()
|
|
guid.bytes = _generate_random_bytes(16)
|
|
# Set UUID version (4) and variant bits
|
|
guid.bytes[6] = (guid.bytes[6] & 0x0F) | 0x40
|
|
guid.bytes[8] = (guid.bytes[8] & 0x3F) | 0x80
|
|
return guid
|
|
|
|
|
|
static func from_string(input: String) -> Guid:
|
|
var clean = input.replace("-", "")
|
|
if clean.length() != 32:
|
|
push_error("Invalid GUID string format")
|
|
return null
|
|
var guid = Guid.new()
|
|
guid.bytes = PackedByteArray()
|
|
for i in range(0, 32, 2):
|
|
guid.bytes.append(clean.substr(i, 2).hex_to_int())
|
|
return guid
|
|
|
|
|
|
func _to_string() -> String:
|
|
var hex = ""
|
|
for b in bytes:
|
|
hex += "%02x" % b
|
|
return (
|
|
hex.substr(0,8) + "-" +
|
|
hex.substr(8,4) + "-" +
|
|
hex.substr(12,4) + "-" +
|
|
hex.substr(16,4) + "-" +
|
|
hex.substr(20,12)
|
|
)
|
|
|
|
|
|
func to_base64() -> String:
|
|
return Marshalls.raw_to_base64(bytes)
|
|
|
|
|
|
static func _generate_random_bytes(length: int) -> PackedByteArray:
|
|
var arr = PackedByteArray()
|
|
for i in range(length):
|
|
arr.append(randi() & 0xFF)
|
|
return arr
|