diff options
Diffstat (limited to 'src/nvim/lua')
-rw-r--r-- | src/nvim/lua/base64.c | 65 | ||||
-rw-r--r-- | src/nvim/lua/base64.h | 12 | ||||
-rw-r--r-- | src/nvim/lua/stdlib.c | 5 |
3 files changed, 82 insertions, 0 deletions
diff --git a/src/nvim/lua/base64.c b/src/nvim/lua/base64.c new file mode 100644 index 0000000000..3f246839d5 --- /dev/null +++ b/src/nvim/lua/base64.c @@ -0,0 +1,65 @@ +#include <assert.h> +#include <lauxlib.h> +#include <lua.h> + +#include "nvim/base64.h" +#include "nvim/lua/base64.h" +#include "nvim/memory.h" + +static int nlua_base64_encode(lua_State *L) +{ + if (lua_gettop(L) < 1) { + return luaL_error(L, "Expected 1 argument"); + } + + if (lua_type(L, 1) != LUA_TSTRING) { + luaL_argerror(L, 1, "expected string"); + } + + size_t src_len = 0; + const char *src = lua_tolstring(L, 1, &src_len); + + const char *ret = base64_encode(src, src_len); + assert(ret != NULL); + lua_pushstring(L, ret); + xfree((void *)ret); + + return 1; +} + +static int nlua_base64_decode(lua_State *L) +{ + if (lua_gettop(L) < 1) { + return luaL_error(L, "Expected 1 argument"); + } + + if (lua_type(L, 1) != LUA_TSTRING) { + luaL_argerror(L, 1, "expected string"); + } + + size_t src_len = 0; + const char *src = lua_tolstring(L, 1, &src_len); + + const char *ret = base64_decode(src, src_len); + if (ret == NULL) { + return luaL_error(L, "Invalid input"); + } + + lua_pushstring(L, ret); + xfree((void *)ret); + + return 1; +} + +static const luaL_Reg base64_functions[] = { + { "encode", nlua_base64_encode }, + { "decode", nlua_base64_decode }, + { NULL, NULL }, +}; + +int luaopen_base64(lua_State *L) +{ + lua_newtable(L); + luaL_register(L, NULL, base64_functions); + return 1; +} diff --git a/src/nvim/lua/base64.h b/src/nvim/lua/base64.h new file mode 100644 index 0000000000..570d9eb677 --- /dev/null +++ b/src/nvim/lua/base64.h @@ -0,0 +1,12 @@ +#ifndef NVIM_LUA_BASE64_H +#define NVIM_LUA_BASE64_H + +#include <lauxlib.h> +#include <lua.h> +#include <lualib.h> + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "lua/base64.h.generated.h" +#endif + +#endif // NVIM_LUA_BASE64_H diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 14e9902ee2..60be771b6c 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -26,6 +26,7 @@ #include "nvim/ex_eval.h" #include "nvim/fold.h" #include "nvim/globals.h" +#include "nvim/lua/base64.h" #include "nvim/lua/converter.h" #include "nvim/lua/spell.h" #include "nvim/lua/stdlib.h" @@ -606,6 +607,10 @@ void nlua_state_add_stdlib(lua_State *const lstate, bool is_thread) lua_pushcfunction(lstate, &nlua_iconv); lua_setfield(lstate, -2, "iconv"); + // vim.base64 + luaopen_base64(lstate); + lua_setfield(lstate, -2, "base64"); + nlua_state_add_internal(lstate); } |