Skip to content

Commit 9b359db

Browse files
author
Chris Dickinson
committed
feat: add Host.arrayBufferToBase64 and Host.base64ToArrayBuffer
1 parent 89758e2 commit 9b359db

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

crates/core/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ extism-pdk = "1"
1212
once_cell = "1.16"
1313
anyhow = { workspace = true }
1414
quickjs-wasm-rs = "3"
15-
chrono = { version = "0.4", default_features = false, features = ["clock"]}
15+
chrono = { version = "0.4", default_features = false, features = ["clock"] }
16+
base64 = "0.22.1"
1617

1718
[lib]
1819
crate_type = ["cdylib"]

crates/core/src/globals.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,44 @@ fn build_host_object(context: &JSContextRef) -> anyhow::Result<JSValueRef> {
155155
Ok(JSValue::Bool(true))
156156
},
157157
)?;
158+
159+
let to_base64 = context.wrap_callback(
160+
|_ctx: &JSContextRef, _this: JSValueRef, args: &[JSValueRef]| {
161+
let data = args.first().unwrap();
162+
if !data.is_array_buffer() {
163+
return Err(anyhow!("expected array buffer"));
164+
}
165+
166+
use base64::prelude::*;
167+
let bytes = data.as_bytes()?;
168+
let as_string = BASE64_STANDARD.encode(bytes);
169+
170+
Ok(JSValue::String(as_string))
171+
},
172+
)?;
173+
174+
let from_base64 = context.wrap_callback(
175+
|_ctx: &JSContextRef, _this: JSValueRef, args: &[JSValueRef]| {
176+
let data = args.first().unwrap();
177+
if !data.is_str() {
178+
return Err(anyhow!("expected string"));
179+
}
180+
181+
use base64::prelude::*;
182+
let string = data.as_str()?;
183+
let bytes = BASE64_STANDARD.decode(string)?;
184+
185+
Ok(JSValue::ArrayBuffer(bytes))
186+
},
187+
)?;
188+
158189
let host_object = context.object_value()?;
159190
host_object.set_property("inputBytes", host_input_bytes)?;
160191
host_object.set_property("inputString", host_input_string)?;
161192
host_object.set_property("outputBytes", host_output_bytes)?;
162193
host_object.set_property("outputString", host_output_string)?;
194+
host_object.set_property("arrayBufferToBase64", to_base64)?;
195+
host_object.set_property("base64ToArrayBuffer", from_base64)?;
163196
Ok(host_object)
164197
}
165198

0 commit comments

Comments
 (0)