Skip to content

Commit 840b0da

Browse files
support encoding strings in base64
1 parent c274c96 commit 840b0da

File tree

1 file changed

+34
-16
lines changed

1 file changed

+34
-16
lines changed

src/modules/encoding/mod.rs

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,31 +50,49 @@ pub(crate) fn create_base64_proxy(_realm: &QuickJsRealmAdapter) -> JsProxy {
5050
.static_method("encode", |_runtime, realm, args| {
5151
// todo async
5252

53-
if args.is_empty() || !args[0].is_typed_array() {
54-
Err(JsError::new_str("encode expects a single type array arg"))
55-
} else {
53+
if args.is_empty() {
54+
Err(JsError::new_str(
55+
"encode expects a single type array or string arg",
56+
))
57+
} else if args[0].is_typed_array() {
5658
let bytes = realm.copy_typed_array_buffer(&args[0])?;
57-
realm.create_resolving_promise(
58-
move || {
59-
let engine = base64::engine::general_purpose::STANDARD;
60-
let encoded = engine.encode(bytes);
61-
Ok(encoded)
62-
},
63-
|realm, p_res| realm.create_string(p_res.as_str()),
64-
)
59+
let engine = base64::engine::general_purpose::STANDARD;
60+
let encoded = engine.encode(bytes);
61+
62+
realm.create_string(encoded.as_str())
63+
} else if args[0].is_string() {
64+
let engine = base64::engine::general_purpose::STANDARD;
65+
let string = args[0].to_string()?;
66+
let encoded = engine.encode(&string);
67+
68+
realm.create_string(encoded.as_str())
69+
} else {
70+
Err(JsError::new_str(
71+
"encode expects a single type array or string arg",
72+
))
6573
}
6674
})
6775
.static_method("encodeSync", |_runtime, realm, args| {
68-
// todo async
69-
70-
if args.is_empty() || !args[0].is_typed_array() {
71-
Err(JsError::new_str("encode expects a single type array arg"))
72-
} else {
76+
if args.is_empty() {
77+
Err(JsError::new_str(
78+
"encode expects a single type array or string arg",
79+
))
80+
} else if args[0].is_typed_array() {
7381
let bytes = realm.copy_typed_array_buffer(&args[0])?;
7482
let engine = base64::engine::general_purpose::STANDARD;
7583
let encoded = engine.encode(bytes);
7684

7785
realm.create_string(encoded.as_str())
86+
} else if args[0].is_string() {
87+
let engine = base64::engine::general_purpose::STANDARD;
88+
let string = args[0].to_string()?;
89+
let encoded = engine.encode(&string);
90+
91+
realm.create_string(encoded.as_str())
92+
} else {
93+
Err(JsError::new_str(
94+
"encode expects a single type array or string arg",
95+
))
7896
}
7997
})
8098
.static_method("decode", |_runtime, realm, args| {

0 commit comments

Comments
 (0)