jsonpath/wasm/src/lib.rs

283 lines
8.3 KiB
Rust
Raw Normal View History

2019-03-03 00:33:27 +09:00
extern crate cfg_if;
extern crate js_sys;
2019-03-06 18:44:39 +09:00
extern crate jsonpath_lib as jsonpath;
2019-03-11 17:35:15 +09:00
#[macro_use]
extern crate lazy_static;
extern crate serde;
2019-03-11 17:35:15 +09:00
extern crate serde_json;
extern crate wasm_bindgen;
extern crate web_sys;
2019-03-03 00:33:27 +09:00
2019-03-11 17:35:15 +09:00
use std::collections::HashMap;
use std::ops::Deref;
2019-04-13 22:27:33 +09:00
use std::result;
2019-03-11 17:35:15 +09:00
use std::result::Result;
use std::sync::Mutex;
2019-03-03 00:33:27 +09:00
use cfg_if::cfg_if;
2019-03-24 21:18:58 +09:00
use jsonpath::filter::value_filter::JsonValueFilter;
use jsonpath::parser::parser::{Node, NodeVisitor, Parser};
use jsonpath::ref_value::model::{RefValue, RefValueWrapper};
use jsonpath::Selector as _Selector;
use serde_json::Value;
use wasm_bindgen::*;
use wasm_bindgen::prelude::*;
use web_sys::console;
2019-03-03 00:33:27 +09:00
cfg_if! {
if #[cfg(feature = "wee_alloc")] {
extern crate wee_alloc;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
}
}
2019-04-08 14:44:18 +09:00
cfg_if! {
if #[cfg(feature = "console_error_panic_hook")] {
extern crate console_error_panic_hook;
pub use self::console_error_panic_hook::set_once as set_panic_hook;
} else {
#[inline]
pub fn set_panic_hook() {}
}
}
2019-03-11 17:35:15 +09:00
fn filter_ref_value(json: RefValueWrapper, node: Node) -> JsValue {
let mut jf = JsonValueFilter::new_from_value(json);
2019-03-03 00:33:27 +09:00
jf.visit(node);
let taken = &jf.take_value();
match JsValue::from_serde(taken.deref()) {
2019-03-03 00:33:27 +09:00
Ok(js_value) => js_value,
Err(e) => JsValue::from_str(&format!("Json deserialize error: {:?}", e))
}
}
fn into_serde_json<D>(js_value: &JsValue) -> Result<D, String>
where D: for<'a> serde::de::Deserialize<'a>
{
2019-03-03 00:33:27 +09:00
if js_value.is_string() {
match serde_json::from_str(js_value.as_string().unwrap().as_str()) {
Ok(json) => Ok(json),
Err(e) => Err(e.to_string())
2019-03-03 00:33:27 +09:00
}
} else {
match js_value.into_serde() {
Ok(json) => Ok(json),
Err(e) => Err(e.to_string())
2019-03-03 00:33:27 +09:00
}
}
}
2019-03-11 17:35:15 +09:00
fn into_ref_value(js_value: &JsValue, node: Node) -> JsValue {
let result: result::Result<RefValue, String> = into_serde_json::<RefValue>(js_value);
match result {
Ok(json) => filter_ref_value(json.into(), node),
2019-03-03 00:33:27 +09:00
Err(e) => JsValue::from_str(&format!("Json serialize error: {}", e))
}
}
2019-03-11 17:35:15 +09:00
fn get_ref_value(js_value: JsValue, node: Node) -> JsValue {
match js_value.as_f64() {
Some(val) => {
match CACHE_JSON.lock().unwrap().get(&(val as usize)) {
Some(json) => filter_ref_value(json.clone(), node),
_ => JsValue::from_str("Invalid pointer")
}
}
_ => into_ref_value(&js_value, node)
}
}
lazy_static! {
static ref CACHE_JSON: Mutex<HashMap<usize, RefValueWrapper>> = Mutex::new(HashMap::new());
static ref CACHE_JSON_IDX: Mutex<usize> = Mutex::new(0);
}
#[wasm_bindgen(js_name = allocJson)]
pub extern fn alloc_json(js_value: JsValue) -> usize {
let result: result::Result<RefValue, String> = into_serde_json(&js_value);
match result {
2019-03-11 17:35:15 +09:00
Ok(json) => {
let mut map = CACHE_JSON.lock().unwrap();
if map.len() >= std::u8::MAX as usize {
return 0;
}
let mut idx = CACHE_JSON_IDX.lock().unwrap();
*idx += 1;
map.insert(*idx, json.into());
2019-03-11 17:35:15 +09:00
*idx
}
Err(e) => {
console::error_1(&e.into());
2019-03-11 17:35:15 +09:00
0
}
}
}
#[wasm_bindgen(js_name = deallocJson)]
pub extern fn dealloc_json(ptr: usize) -> bool {
2019-03-11 17:35:15 +09:00
let mut map = CACHE_JSON.lock().unwrap();
map.remove(&ptr).is_some()
}
2019-03-03 00:33:27 +09:00
#[wasm_bindgen]
pub fn compile(path: &str) -> JsValue {
let mut parser = Parser::new(path);
let node = parser.compile();
let cb = Closure::wrap(Box::new(move |js_value: JsValue| {
match &node {
2019-03-11 17:35:15 +09:00
Ok(node) => get_ref_value(js_value, node.clone()),
2019-03-03 00:33:27 +09:00
Err(e) => JsValue::from_str(&format!("Json path error: {:?}", e))
}
}) as Box<Fn(JsValue) -> JsValue>);
let ret = cb.as_ref().clone();
cb.forget();
ret
}
2019-03-11 17:35:15 +09:00
#[wasm_bindgen]
pub fn selector(js_value: JsValue) -> JsValue {
let json = match js_value.as_f64() {
Some(val) => {
match CACHE_JSON.lock().unwrap().get(&(val as usize)) {
Some(json) => json.clone(),
_ => return JsValue::from_str("Invalid pointer")
}
}
_ => {
match into_serde_json::<RefValue>(&js_value) {
Ok(json) => json.into(),
2019-03-11 17:35:15 +09:00
Err(e) => return JsValue::from_str(e.as_str())
}
}
};
2019-03-03 00:33:27 +09:00
let cb = Closure::wrap(Box::new(move |path: String| {
let mut parser = Parser::new(path.as_str());
match parser.compile() {
2019-03-11 17:35:15 +09:00
Ok(node) => filter_ref_value(json.clone(), node),
2019-03-03 00:33:27 +09:00
Err(e) => return JsValue::from_str(e.as_str())
}
}) as Box<Fn(String) -> JsValue>);
let ret = cb.as_ref().clone();
cb.forget();
ret
}
#[wasm_bindgen]
2019-03-11 17:35:15 +09:00
pub fn select(js_value: JsValue, path: &str) -> JsValue {
2019-03-03 00:33:27 +09:00
let mut parser = Parser::new(path);
match parser.compile() {
2019-03-11 17:35:15 +09:00
Ok(node) => get_ref_value(js_value, node),
2019-03-03 00:33:27 +09:00
Err(e) => return JsValue::from_str(e.as_str())
}
2019-03-07 18:44:06 +09:00
}
///
/// `wasm_bindgen` 제약으로 builder-pattern을 구사 할 수 없다.
///
#[wasm_bindgen]
pub struct Selector {
selector: _Selector
}
#[wasm_bindgen]
impl Selector {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Selector { selector: _Selector::new() }
}
#[wasm_bindgen(catch)]
pub fn path(&mut self, path: &str) -> result::Result<(), JsValue> {
let _ = self.selector.path(path)?;
Ok(())
}
#[wasm_bindgen(catch)]
pub fn value(&mut self, value: JsValue) -> result::Result<(), JsValue> {
let ref ref_value = into_serde_json(&value)?;
let _ = self.selector.value(ref_value)?;
Ok(())
}
#[wasm_bindgen(catch, js_name = selectToStr)]
pub fn select_to_str(&mut self) -> result::Result<JsValue, JsValue> {
self.select_as_str()
}
#[wasm_bindgen(catch, js_name = selectAsStr)]
pub fn select_as_str(&mut self) -> result::Result<JsValue, JsValue> {
let json_str = self.selector.select_as_str()?;
Ok(JsValue::from_str(&json_str))
}
#[wasm_bindgen(catch, js_name = selectTo)]
pub fn select_to(&mut self) -> result::Result<JsValue, JsValue> {
self.select_as()
}
#[wasm_bindgen(catch, js_name = selectAs)]
pub fn select_as(&mut self) -> result::Result<JsValue, JsValue> {
let ref_value = self.selector.select_as::<RefValue>()
.map_err(|e| JsValue::from_str(&e))?;
Ok(JsValue::from_serde(&ref_value)
.map_err(|e| JsValue::from_str(&e.to_string()))?)
}
#[wasm_bindgen(catch)]
pub fn map(&mut self, func: JsValue) -> result::Result<(), JsValue> {
if !func.is_function() {
return Err(JsValue::from_str("Not a function argument"));
}
let cb: &js_sys::Function = JsCast::unchecked_ref(func.as_ref());
self.selector.map(|v| {
let str_value = match JsValue::from_serde(&v) {
Ok(str_value) => str_value,
Err(e) => return {
console::error_1(&JsValue::from_str(&e.to_string()));
None
}
};
match cb.call1(&func, &str_value) {
Ok(ret) => {
match into_serde_json::<Value>(&ret) {
Ok(value) => Some(value),
Err(e) => {
console::error_1(&JsValue::from_str(&e.to_string()));
None
}
}
}
Err(e) => {
console::error_1(&e);
None
}
}
}).map_err(|e| JsValue::from_str(&e))?;
Ok(())
}
#[wasm_bindgen(catch)]
pub fn get(&mut self) -> result::Result<JsValue, JsValue> {
2019-05-15 18:19:00 +09:00
let v = self.selector.get().map_err(|e| JsValue::from_str(&e.to_string()))?;
JsValue::from_serde(&v).map_err(|e| JsValue::from_str(&e.to_string()))
}
}
2019-04-13 22:27:33 +09:00
#[wasm_bindgen(catch)]
pub fn testa(js_value: JsValue, path: &str, iter: usize) -> result::Result<(), JsValue> {
for _ in 0..iter {
let mut parser = Parser::new(path);
let node = parser.compile().unwrap();
into_ref_value(&js_value, node);
}
Ok(())
}