From c624623efe934779df4dc6896515bc20a73294ca Mon Sep 17 00:00:00 2001 From: Robin Wellner Date: Tue, 16 Feb 2016 02:08:07 +0100 Subject: [PATCH] add ability to load from raw data see https://love2d.org/wiki/Data:getPointer --- bitser.lua | 14 ++++++++++---- spec/bitser_spec.lua | 3 +++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/bitser.lua b/bitser.lua index f42d3f1..de58901 100644 --- a/bitser.lua +++ b/bitser.lua @@ -15,7 +15,11 @@ end local function Buffer_newReader(str) local buf = ffi.new("uint8_t[?]", #str) ffi.copy(buf, str, #str) - return {size = #str, pos = 0, buf = buf} + return {pos = 0, buf = buf} +end + +local function Buffer_newDataReader(data) + return {pos = 0, buf = ffi.cast("uint8_t*", data)} end local function Buffer_reserve(self, additional_size) @@ -307,10 +311,12 @@ local function deserialize_Slither(instance, class) return getmetatable(class).allocate(instance) end -return {dump = nil, dumps = function(value) +return {dumps = function(value) return ffi.string(serialize(value)) -end, load = nil, loads = function(value) - return deserialize(Buffer_newReader(value)) +end, loadData = function(data) + return deserialize(Buffer_newDataReader(data)) +end, loads = function(str) + return deserialize(Buffer_newReader(str)) end, register = function(name, resource) assert(not resource_registry[name], name .. " already registered") resource_registry[name] = resource diff --git a/spec/bitser_spec.lua b/spec/bitser_spec.lua index 33fccae..7e8a3df 100644 --- a/spec/bitser_spec.lua +++ b/spec/bitser_spec.lua @@ -187,4 +187,7 @@ describe("bitser", function() assert.has_error(function() bitser.loads("\254") end, "unsupported serialized type 254") assert.has_error(function() bitser.loads("\255") end, "unsupported serialized type 255") end) + it("can load from raw data", function() + assert.are.same(bitser.loadData(ffi.new("uint8[4]", 195, 103, 118, 120)), "gvx") + end) end)