LuPPC/src/lua/core/uuidmgr.lua

63 lines
1.8 KiB
Lua

local uuidmgr = {}
local uuidstorage = {}
local storeheader = "c32BH"
do
local store = io.open("uuidstore.dat", "r")
if store then
pcall(function()
local count = string.unpack("H", store:read(2))
for i=1, count do
local uuid, clen, ilen = storeheader:unpack(store:read(storeheader:packsize()))
local cname, id = store:read(clen), store:read(ilen)
uuidstorage[cname] = uuidstorage[cname] or {}
uuidstorage[cname][id] = uuid
end
store:close()
end)
end
end
function uuidmgr.lookup(component, identifier)
uuidstorage[component] = uuidstorage[component] or {}
local uuid = uuidstorage[component][identifier]
if not uuid then
uuid = modules.random.uuid()
if native.debug then
lprint(string.format("DEBUG: Registed component of type %s with identifier %s as uuid %s", component, identifier, uuid))
end
uuidstorage[component][identifier] = uuid
uuidmgr.store()
else
if native.debug then
lprint(string.format("DEBUG: Looked up component of type %s with identifier %s as uuid %s", component, identifier, uuid))
end
end
return uuid
end
function uuidmgr.store()
local store = io.open("uuidstore.dat", "w")
local saved_ids = {}
for component, ids in pairs(uuidstorage) do
for id, uuid in pairs(ids) do
table.insert(saved_ids, {uuid=uuid, component=component, id=id})
end
end
if native.debug then
lprint(string.format("DEBUG: Saving %d static UUIDs", #saved_ids))
end
store:write(string.pack("H", #saved_ids))
for i=1, #saved_ids do
local uuid, component, id = saved_ids[i].uuid, saved_ids[i].component, saved_ids[i].id
store:write(storeheader:pack(uuid, #component, #id),component,id)
if native.debug then
lprint(string.format("DEBUG: Saving %s:%s as %s", component, id, uuid))
end
end
store:close()
end
return uuidmgr