Skip to content

Commit

Permalink
chore: use serde_wasm_bindgen instead of serde_json
Browse files Browse the repository at this point in the history
with serde_wasm_bindgen, we have directly the JsValue.
  • Loading branch information
pythonbrad committed Mar 25, 2024
1 parent 7a9f853 commit b83999a
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 54 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ serde-wasm-bindgen = "0.6.1"
afrim-translator = { version = "0.1.4", default-features = false, features = ["serde"], git = "https://github.com/pythonbrad/afrim", rev = "5192a5f" }
indexmap = { version = "2.1.0", features = ["serde"] }
toml = "0.8.10"
serde_json = "1.0.114"

[dev-dependencies]
wasm-bindgen-test = "0.3.42"
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use wasm_bindgen::prelude::*;
pub fn convert_toml_to_json(content: &str) -> Result<JsValue, String> {
let data: toml::Value = toml::from_str(content)
.map_err(|err| format!("Invalid toml data.\nCaused by:\n\t{err}."))?;
let json = serde_json::to_string(&data).unwrap();

Ok(JsValue::from_str(&json))
Ok(serde_wasm_bindgen::to_value(&data).unwrap())
}
40 changes: 7 additions & 33 deletions src/preprocessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ impl Preprocessor {
/// let preprocessor = new Preprocessor(data, 64);
/// ```
#[wasm_bindgen(constructor)]
pub fn new(data: &JsValue, buffer_size: usize) -> Result<Preprocessor, String> {
let data: IndexMap<String, String> = serde_wasm_bindgen::from_value(data.clone())
pub fn new(data: JsValue, buffer_size: usize) -> Result<Preprocessor, String> {
let data: IndexMap<String, String> = serde_wasm_bindgen::from_value(data)
.map_err(|err| format!("[preprocessor] Invalid data.\nCaused by:\n\t{err}."))?;
let data = data
.iter()
Expand Down Expand Up @@ -82,12 +82,13 @@ impl Preprocessor {
/// preprocessor.popQueue() == "NOP";
/// ```
#[wasm_bindgen(js_name = popQueue)]
pub fn pop_queue(&mut self) -> String {
pub fn pop_queue(&mut self) -> JsValue {
self.engine
.pop_queue()
.as_ref()
.map(utils::serialize_command)
.unwrap_or("\"NOP\"".to_owned())
.map(serde_wasm_bindgen::to_value)
.unwrap_or(Ok("NOP".into()))
.unwrap()
}

/// Return the input from the memory.
Expand Down Expand Up @@ -127,7 +128,7 @@ impl Preprocessor {

pub mod utils {
pub use afrim_preprocessor::utils::*;
use afrim_preprocessor::{Command, Key, KeyState, KeyboardEvent};
use afrim_preprocessor::{Key, KeyState, KeyboardEvent};
use std::str::FromStr;

/// Convert an JsKeyboardEvent to KeyboardEvent.
Expand All @@ -145,11 +146,6 @@ pub mod utils {

Ok(event)
}

/// Convert a preprocessor command to speudo code.
pub fn serialize_command(command: &Command) -> String {
serde_json::to_string(command).unwrap()
}
}

#[cfg(test)]
Expand Down Expand Up @@ -179,26 +175,4 @@ mod test {
assert!(utils::deserialize_event("key", "keyup").is_err());
assert!(utils::deserialize_event("a", "up").is_err());
}

#[test]
fn test_serialize_command() {
use afrim_preprocessor::Command;

assert_eq!(
utils::serialize_command(&Command::CommitText("text".to_string())),
"{\"CommitText\":\"text\"}".to_string()
);
assert_eq!(
utils::serialize_command(&Command::Pause),
"\"Pause\"".to_string()
);
assert_eq!(
utils::serialize_command(&Command::Resume),
"\"Resume\"".to_string()
);
assert_eq!(
utils::serialize_command(&Command::Delete),
"\"Delete\"".to_string()
);
}
}
7 changes: 3 additions & 4 deletions src/translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ impl Translator {
/// let translator = new Translator(data, false);
/// ```
#[wasm_bindgen(constructor)]
pub fn new(dictionary: &JsValue, auto_commit: bool) -> Result<Translator, String> {
let dictionary: IndexMap<String, Vec<String>> =
serde_wasm_bindgen::from_value(dictionary.clone())
.map_err(|err| format!("[translator] Invalid dictionary.\nCaused by:\n\t{err}."))?;
pub fn new(dictionary: JsValue, auto_commit: bool) -> Result<Translator, String> {
let dictionary: IndexMap<String, Vec<String>> = serde_wasm_bindgen::from_value(dictionary)
.map_err(|err| format!("[translator] Invalid dictionary.\nCaused by:\n\t{err}."))?;

Ok(Self {
engine: NativeTranslator::new(dictionary, auto_commit),
Expand Down
35 changes: 21 additions & 14 deletions tests/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
extern crate wasm_bindgen_test;
use serde_wasm_bindgen::{self};
use std::collections::HashMap;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;

wasm_bindgen_test_configure!(run_in_browser);
Expand All @@ -19,7 +20,7 @@ fn test_process() {
let map = serde_wasm_bindgen::to_value(&data).unwrap();

// Process
let mut preprocessor = Preprocessor::new(&map, 32).unwrap();
let mut preprocessor = Preprocessor::new(map, 32).unwrap();
preprocessor.process("a", "keydown").unwrap();
preprocessor.process("Backspace", "keydown").unwrap();
assert_eq!(preprocessor.get_input(), "".to_owned());
Expand All @@ -29,17 +30,15 @@ fn test_process() {
assert_eq!(preprocessor.get_input(), "a1".to_owned());

// Get commands
assert_eq!(preprocessor.pop_queue(), "\"Pause\"".to_string());
assert_eq!(preprocessor.pop_queue(), "\"CleanDelete\"".to_string());
assert_eq!(preprocessor.pop_queue(), "\"Resume\"".to_string());
assert_eq!(preprocessor.pop_queue(), "\"Pause\"".to_string());
assert_eq!(preprocessor.pop_queue(), "\"Delete\"".to_string());
assert_eq!(preprocessor.pop_queue(), "\"Delete\"".to_string());
assert_eq!(
preprocessor.pop_queue(),
"{\"CommitText\":\"à\"}".to_string()
);
assert_eq!(preprocessor.pop_queue(), "\"Resume\"".to_string());
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Pause"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("CleanDelete"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Resume"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Pause"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Delete"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Delete"));
assert!(preprocessor.pop_queue().is_object());
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("Resume"));
assert_eq!(preprocessor.pop_queue(), JsValue::from_str("NOP"));
}

#[wasm_bindgen_test]
Expand All @@ -52,7 +51,7 @@ fn test_translate() {
let dictionary = serde_wasm_bindgen::to_value(&dictionary).unwrap();

// Translate
let translator = Translator::new(&dictionary, false).unwrap();
let translator = Translator::new(dictionary, false).unwrap();
let translations: Vec<(String, String, Vec<String>, bool)> =
serde_wasm_bindgen::from_value(translator.translate("hello")).unwrap();

Expand Down Expand Up @@ -97,7 +96,7 @@ fn test_transaltor() {

// Translate
let dictionary = serde_wasm_bindgen::to_value(&HashMap::<String, String>::new()).unwrap();
let mut translator = Translator::new(&dictionary, false).unwrap();
let mut translator = Translator::new(dictionary, false).unwrap();
translator
.register("count".to_owned(), count_script.to_owned())
.unwrap();
Expand All @@ -116,3 +115,11 @@ fn test_transaltor() {

translator.unregister("count");
}

#[wasm_bindgen_test]
fn test_toml() {
use afrim_js::convert_toml_to_json;

let data = convert_toml_to_json("[data]\nhi = \"hello\"");
assert!(data.unwrap().is_object());
}

0 comments on commit b83999a

Please sign in to comment.