1use config::{any_err, get_or_create_sub_module};
2use data_encoding::{
3 BASE32, BASE32HEX, BASE32HEX_NOPAD, BASE32_NOPAD, BASE64, BASE64URL, BASE64URL_NOPAD,
4 BASE64_NOPAD, HEXLOWER,
5};
6use mlua::{Lua, Value};
7
8pub fn register(lua: &Lua) -> anyhow::Result<()> {
9 let digest_mod = get_or_create_sub_module(lua, "encode")?;
10
11 for (name, enc) in [
12 ("base32", BASE32),
13 ("base32hex", BASE32HEX),
14 ("base32hex_nopad", BASE32HEX_NOPAD),
15 ("base32_nopad", BASE32_NOPAD),
16 ("base64", BASE64),
17 ("base64url", BASE64URL),
18 ("base64url_nopad", BASE64URL_NOPAD),
19 ("base64_nopad", BASE64_NOPAD),
20 ("hex", HEXLOWER),
21 ] {
22 let encoder = enc.clone();
23 digest_mod.set(
24 format!("{name}_encode"),
25 lua.create_function(move |_, data: mlua::Value| match data {
26 Value::String(s) => Ok(encoder.encode(&s.as_bytes())),
27 _ => Err(mlua::Error::external(
28 "parameter must be a string".to_string(),
29 )),
30 })?,
31 )?;
32 digest_mod.set(
33 format!("{name}_decode"),
34 lua.create_function(move |lua, data: String| {
35 let bytes = enc.decode(data.as_bytes()).map_err(any_err)?;
36 lua.create_string(&bytes)
37 })?,
38 )?;
39 }
40 Ok(())
41}