Software /
code /
prosody
Comparison
util-src/strbitop.c @ 11163:37a6a535343e 0.11
util.strbitop: Library for bitwise operations on strings
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Sat, 07 Sep 2019 13:37:47 +0200 |
child | 11167:ba32b9a6d75b |
comparison
equal
deleted
inserted
replaced
11162:ee399a0522cc | 11163:37a6a535343e |
---|---|
1 /* | |
2 * This project is MIT licensed. Please see the | |
3 * COPYING file in the source package for more information. | |
4 * | |
5 * Copyright (C) 2016 Kim Alvefur | |
6 */ | |
7 | |
8 #include <lua.h> | |
9 #include <lauxlib.h> | |
10 | |
11 #if (LUA_VERSION_NUM == 501) | |
12 #define luaL_setfuncs(L, R, N) luaL_register(L, NULL, R) | |
13 #endif | |
14 | |
15 /* TODO Deduplicate code somehow */ | |
16 | |
17 int strop_and(lua_State* L) { | |
18 luaL_Buffer buf; | |
19 size_t a, b, i; | |
20 const char* str_a = luaL_checklstring(L, 1, &a); | |
21 const char* str_b = luaL_checklstring(L, 2, &b); | |
22 | |
23 luaL_buffinit(L, &buf); | |
24 | |
25 if(a == 0 || b == 0) { | |
26 lua_settop(L, 1); | |
27 return 1; | |
28 } | |
29 | |
30 for(i = 0; i < a; i++) { | |
31 luaL_addchar(&buf, str_a[i] & str_b[i % b]); | |
32 } | |
33 | |
34 luaL_pushresult(&buf); | |
35 return 1; | |
36 } | |
37 | |
38 int strop_or(lua_State* L) { | |
39 luaL_Buffer buf; | |
40 size_t a, b, i; | |
41 const char* str_a = luaL_checklstring(L, 1, &a); | |
42 const char* str_b = luaL_checklstring(L, 2, &b); | |
43 | |
44 luaL_buffinit(L, &buf); | |
45 | |
46 if(a == 0 || b == 0) { | |
47 lua_settop(L, 1); | |
48 return 1; | |
49 } | |
50 | |
51 for(i = 0; i < a; i++) { | |
52 luaL_addchar(&buf, str_a[i] | str_b[i % b]); | |
53 } | |
54 | |
55 luaL_pushresult(&buf); | |
56 return 1; | |
57 } | |
58 | |
59 int strop_xor(lua_State* L) { | |
60 luaL_Buffer buf; | |
61 size_t a, b, i; | |
62 const char* str_a = luaL_checklstring(L, 1, &a); | |
63 const char* str_b = luaL_checklstring(L, 2, &b); | |
64 | |
65 luaL_buffinit(L, &buf); | |
66 | |
67 if(a == 0 || b == 0) { | |
68 lua_settop(L, 1); | |
69 return 1; | |
70 } | |
71 | |
72 for(i = 0; i < a; i++) { | |
73 luaL_addchar(&buf, str_a[i] ^ str_b[i % b]); | |
74 } | |
75 | |
76 luaL_pushresult(&buf); | |
77 return 1; | |
78 } | |
79 | |
80 LUA_API int luaopen_util_strbitop(lua_State *L) { | |
81 luaL_Reg exports[] = { | |
82 { "sand", strop_and }, | |
83 { "sor", strop_or }, | |
84 { "sxor", strop_xor }, | |
85 { NULL, NULL } | |
86 }; | |
87 | |
88 lua_newtable(L); | |
89 luaL_setfuncs(L, exports, 0); | |
90 return 1; | |
91 } |