Skip to content

Instantly share code, notes, and snippets.

@catwell
Created May 16, 2018 18:41
Show Gist options
  • Save catwell/7c43be1a2ae4ab58183fd7aaa99f1391 to your computer and use it in GitHub Desktop.
Save catwell/7c43be1a2ae4ab58183fd7aaa99f1391 to your computer and use it in GitHub Desktop.
Encode stuff with LuaJIT FFI
-- https://twitter.com/kellabyte/status/996803727477489664
local ffi = require "ffi"
local key = "12345" -- your key
local value = "somethingelse" -- your value
local key_len = #key
local value_len = #value
-- first create a buffer
local uchar_vla = ffi.typeof("unsigned char[?]")
local buf = uchar_vla(4 + 4 + key_len + value_len)
-- cast the buffer to a table of u32 and write the lengths
local u32_p = ffi.typeof("uint32_t *")
local u32_array = ffi.cast(u32_p, buf)
u32_array[0] = key_len
u32_array[1] = value_len
-- now copy the values
ffi.copy(buf + 4 + 4, key, key_len)
ffi.copy(buf + 4 + 4 + key_len, value, value_len)
-- finally get a Lua string back
local s = ffi.string(buf, 4 + 4 + key_len + value_len)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment