aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/lua/base64.c
blob: c1f43a37d7548631e4e06dc72cda6bd70c3b0868 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <assert.h>
#include <lauxlib.h>
#include <lua.h>
#include <stddef.h>

#include "nvim/base64.h"
#include "nvim/lua/base64.h"
#include "nvim/memory.h"

#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "lua/base64.c.generated.h"
#endif

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;
}