add base64.encode_urlsafe, base64.decode_urlsafe

This commit is contained in:
MihailRis 2025-09-16 22:16:56 +03:00
parent 72f73661ae
commit 063cbde569

View File

@ -2,6 +2,7 @@
#include "util/stringutil.hpp" #include "util/stringutil.hpp"
template<std::string(*encode_func)(const ubyte*, size_t)>
static int l_encode(lua::State* L) { static int l_encode(lua::State* L) {
if (lua::istable(L, 1)) { if (lua::istable(L, 1)) {
lua::pushvalue(L, 1); lua::pushvalue(L, 1);
@ -13,12 +14,12 @@ static int l_encode(lua::State* L) {
lua::pop(L); lua::pop(L);
} }
lua::pop(L); lua::pop(L);
return lua::pushstring(L, util::base64_encode( return lua::pushstring(L, encode_func(
reinterpret_cast<const ubyte*>(buffer.data()), buffer.size() reinterpret_cast<const ubyte*>(buffer.data()), buffer.size()
)); ));
} else { } else {
auto string = lua::bytearray_as_string(L, 1); auto string = lua::bytearray_as_string(L, 1);
auto out = util::base64_encode( auto out = encode_func(
reinterpret_cast<const ubyte*>(string.data()), reinterpret_cast<const ubyte*>(string.data()),
string.size() string.size()
); );
@ -28,8 +29,9 @@ static int l_encode(lua::State* L) {
throw std::runtime_error("array or ByteArray expected"); throw std::runtime_error("array or ByteArray expected");
} }
template<util::Buffer<ubyte>(*decode_func)(std::string_view)>
static int l_decode(lua::State* L) { static int l_decode(lua::State* L) {
auto buffer = util::base64_decode(lua::require_lstring(L, 1)); auto buffer = decode_func(lua::require_lstring(L, 1));
if (lua::toboolean(L, 2)) { if (lua::toboolean(L, 2)) {
lua::createtable(L, buffer.size(), 0); lua::createtable(L, buffer.size(), 0);
for (size_t i = 0; i < buffer.size(); i++) { for (size_t i = 0; i < buffer.size(); i++) {
@ -43,7 +45,9 @@ static int l_decode(lua::State* L) {
} }
const luaL_Reg base64lib[] = { const luaL_Reg base64lib[] = {
{"encode", lua::wrap<l_encode>}, {"encode", lua::wrap<l_encode<util::base64_encode>>},
{"decode", lua::wrap<l_decode>}, {"decode", lua::wrap<l_decode<util::base64_decode>>},
{"encode_urlsafe", lua::wrap<l_encode<util::base64_urlsafe_encode>>},
{"decode_urlsafe", lua::wrap<l_decode<util::base64_urlsafe_decode>>},
{NULL, NULL} {NULL, NULL}
}; };