rqjs_ext/modules/encoding/
mod.rs1pub mod encoder;
4pub mod text_decoder;
5pub mod text_encoder;
6
7use rquickjs::{
8 module::{Declarations, Exports, ModuleDef},
9 prelude::Func,
10 Class, Ctx, Result, Value,
11};
12
13use crate::{
14 modules::module::export_default,
16 utils::{
17 object::{bytes_to_typed_array, get_bytes},
18 result::ResultExt,
19 },
20};
21
22use self::encoder::{bytes_from_b64, bytes_from_hex, bytes_to_b64_string, bytes_to_hex_string};
23use self::text_decoder::TextDecoder;
24use self::text_encoder::TextEncoder;
25
26pub struct HexModule;
27
28impl HexModule {
29 pub fn encode<'js>(ctx: Ctx<'js>, buffer: Value<'js>) -> Result<String> {
30 let bytes = get_bytes(&ctx, buffer)?;
31 Ok(bytes_to_hex_string(&bytes))
32 }
33
34 pub fn decode(ctx: Ctx, encoded: String) -> Result<Value> {
35 let bytes = bytes_from_hex(encoded.as_bytes())
36 .or_throw_msg(&ctx, "Cannot decode unrecognized sequence")?;
37
38 bytes_to_typed_array(ctx, &bytes)
39 }
40}
41
42impl ModuleDef for HexModule {
43 fn declare(declare: &Declarations<'_>) -> Result<()> {
44 declare.declare(stringify!(encode))?;
45 declare.declare(stringify!(decode))?;
46 declare.declare("default")?;
47 Ok(())
48 }
49
50 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
51 export_default(ctx, exports, |default| {
52 default.set(stringify!(encode), Func::from(Self::encode))?;
53 default.set(stringify!(decode), Func::from(Self::decode))?;
54 Ok(())
55 })?;
56
57 Ok(())
58 }
59}
60
61pub fn atob(ctx: Ctx<'_>, encoded_value: String) -> Result<String> {
71 let vec = bytes_from_b64(encoded_value.as_bytes()).or_throw(&ctx)?;
72 Ok(unsafe { String::from_utf8_unchecked(vec) })
73}
74
75pub fn btoa(value: String) -> String {
76 bytes_to_b64_string(value.as_bytes())
77}
78
79pub fn init(ctx: &Ctx<'_>) -> Result<()> {
80 let globals = ctx.globals();
81
82 globals.set("atob", Func::from(atob))?;
83 globals.set("btoa", Func::from(btoa))?;
84
85 Class::<TextEncoder>::define(&globals)?;
86 Class::<TextDecoder>::define(&globals)?;
87
88 Ok(())
89}