use js function to encode

This commit is contained in:
Toshit Chawda 2024-07-26 22:24:25 -07:00
parent 11a0c09179
commit eebefbc070
No known key found for this signature in database
GPG key ID: 91480ED99E2B3D9D
7 changed files with 41 additions and 17 deletions

View file

@ -2,8 +2,8 @@ pub mod rewrite;
use std::{panic, str::FromStr};
use js_sys::encode_uri_component;
use rewrite::rewrite;
use js_sys::Function;
use rewrite::{rewrite, EncodeFn};
use url::Url;
use wasm_bindgen::prelude::*;
@ -13,26 +13,40 @@ extern "C" {
fn log(s: &str);
}
// import the SCRAM!!! jet encoder here later
fn encode(s: String) -> String {
encode_uri_component(&s).into()
}
#[wasm_bindgen]
pub fn init() {
panic::set_hook(Box::new(console_error_panic_hook::hook));
}
#[wasm_bindgen]
pub fn rewrite_js(js: &str, url: &str) -> Vec<u8> {
rewrite(js, Url::from_str(url).unwrap(), Box::new(encode))
fn create_encode_function(encode: Function) -> EncodeFn {
Box::new(move |str| {
encode
.call1(&JsValue::NULL, &str.into())
.unwrap()
.as_string()
.unwrap()
.to_string()
})
}
#[wasm_bindgen]
pub fn rewrite_js_from_arraybuffer(js: &[u8], url: &str) -> Vec<u8> {
pub fn rewrite_js(js: &str, url: &str, encode: Function) -> Vec<u8> {
rewrite(
js,
Url::from_str(url).unwrap(),
create_encode_function(encode),
)
}
#[wasm_bindgen]
pub fn rewrite_js_from_arraybuffer(js: &[u8], url: &str, encode: Function) -> Vec<u8> {
// technically slower than the c++ string conversion but it will create *less copies*
let js = unsafe { std::str::from_utf8_unchecked(js) };
rewrite(js, Url::from_str(url).unwrap(), Box::new(encode))
rewrite(
js,
Url::from_str(url).unwrap(),
create_encode_function(encode),
)
}

View file

@ -27,7 +27,7 @@ enum JsChange {
},
}
type EncodeFn = Box<dyn Fn(String) -> String>;
pub type EncodeFn = Box<dyn Fn(String) -> String>;
struct Rewriter {
jschanges: Vec<JsChange>,
base: Url,