Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lua-shmem implementation using LuaJIT FFI
local ffi = require("ffi")
ffi.cdef([[
typedef size_t off_t;
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
]])
local MAP_SHARED = 1
local MAP_ANONYMOUS = 32
local PROT_READ = 4
local PROT_WRITE = 2
local function mmap(size)
return ffi.C.mmap(nil, size, bit.bor(PROT_READ, PROT_WRITE), bit.bor(MAP_SHARED, MAP_ANONYMOUS), -1, 0)
end
local shmem = {}
local shmem_mt = {}
shmem.new = function(size)
local mem = {
addr = mmap(size),
size = size,
}
setmetatable(mem, {__index = shmem_mt})
return mem
end
shmem_mt.clear = function(mem)
ffi.fill(mem.addr, mem.size)
end
shmem_mt.write = function(mem, data)
ffi.copy(mem.addr, data)
end
shmem_mt.fill = function(mem, data, c)
ffi.fill(mem.addr, mem.size, c)
ffi.copy(mem.addr, data)
end
shmem_mt.read = function(mem)
return ffi.string(mem.addr)
end
shmem_mt.free = function(mem)
local err = ffi.C.munmap(mem.addr, mem.size)
if (err < 0) then
return false, err
else
return true
end
end
return shmem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.