diff --git a/lib/instances/HttpService.lua b/lib/instances/HttpService.lua index 93e3004..8b5e660 100644 --- a/lib/instances/HttpService.lua +++ b/lib/instances/HttpService.lua @@ -4,6 +4,30 @@ local json = import("../json") local HttpService = BaseInstance:extend("HttpService") +-- Credit to https://stackoverflow.com/a/32389020 +local AND, OR = 1, 4 + +local function bit(a, b, oper) + local r, m, s = 0, 2^52 + repeat + s, a, b = a + b + m, a % m, b % m + r, m = r + m * oper % (s - a - b), m / 2 + until m < 1 + return r +end + +local function band(a, b) + return bit(a, b, AND) +end + +local function bor(a, b) + return bit(a, b, OR) +end + +local function tohex(number) + return ("%02x"):format(number) +end + function HttpService.prototype:JSONEncode(input) return json.encode(input) end @@ -18,15 +42,41 @@ function HttpService.prototype:GenerateGUID(wrapInCurlyBraces) error(("Unable to cast %s to bool"):format(argType), 2) end + local random = math.random + + local guid = + ("%s%s%s%s-%s%s-%s%s-%s%s-%s%s%s%s%s%s"):format( + tohex(random(0, 255), 2), + tohex(random(0, 255)), + tohex(random(0, 255)), + tohex(random(0, 255)), + + tohex(random(0, 255)), + tohex(random(0, 255)), + + tohex(bor(band(random(0, 255), 0x0F), 0x40)), + tohex(random(0, 255)), + + tohex(bor(band(random(0, 255), 0x3F), 0x80)), + tohex(random(0, 255)), + + tohex(random(0, 255)), + tohex(random(0, 255)), + tohex(random(0, 255)), + tohex(random(0, 255)), + tohex(random(0, 255)), + tohex(random(0, 255)) + ) + --[[ `GenerateGUID` allows any value type for `wrapInCurlyBraces`, but it only omits the curly braces when `wrapInCurlyBraces` is set to `false` ]] - if wrapInCurlyBraces == false then - return "04AEBFEA-87FC-480F-A98B-E5E221007A90" - else - return "{04AEBFEA-87FC-480F-A98B-E5E221007A90}" + if wrapInCurlyBraces ~= false then + guid = "{" .. guid .. "}" end + + return guid end return HttpService \ No newline at end of file diff --git a/lib/instances/HttpService_spec.lua b/lib/instances/HttpService_spec.lua index ca45d3a..4c66d0f 100644 --- a/lib/instances/HttpService_spec.lua +++ b/lib/instances/HttpService_spec.lua @@ -20,6 +20,29 @@ describe("instances.HttpService", function() end) describe("GenerateGUID", function() + it("should have proper length guids", function() + local instance = HttpService:new() + local guid = instance:GenerateGUID(false) + + assert.equal(36, #guid) + end) + + it("should give unique guids", function() + local instance = HttpService:new() + local guids = {} + + for _ = 1, 100 do + guids[instance:GenerateGUID()] = true + end + + local guidsGenerated = 0 + for _ in pairs(guids) do + guidsGenerated = guidsGenerated + 1 + end + + assert.equal(100, guidsGenerated) + end) + it("should omit curly braces when wrapInCurlyBraces is false", function() local instance = HttpService:new() local guid = instance:GenerateGUID(false)