Skip to content
This repository was archived by the owner on Jul 12, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 54 additions & 4 deletions lib/instances/HttpService.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
23 changes: 23 additions & 0 deletions lib/instances/HttpService_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down