#[macro_use] extern crate napi; #[macro_use] extern crate napi_derive; use std::convert::TryInto; use napi::{CallContext, JsObject, JsString, Module, Result}; mod mdiff; #[cfg(all(unix, not(target_env = "musl")))] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; register_module!(example, init); fn init(module: &mut Module) -> Result<()> { module.create_named_method("diffChars", diff_char)?; module.create_named_method("diffLines", diff_line)?; Ok(()) } #[js_function(2)] fn diff_char(ctx: CallContext) -> Result { let str1: String = ctx.get::(0)?.try_into()?; let str2: String = ctx.get::(1)?.try_into()?; let res = mdiff::diff_chars(str1.as_str(), str2.as_str()); let mut obj = ctx.env.create_array_with_length(res.len()).unwrap(); let mut idx = 0; for it in res.iter() { let mut item = ctx.env.create_object().unwrap(); item.set_named_property( "count", ctx.env.create_int64(it.count.try_into().unwrap()).unwrap(), )?; item.set_named_property("value", ctx.env.create_string(&it.value).unwrap())?; item.set_named_property("added", ctx.env.get_boolean(it.added).unwrap())?; item.set_named_property("removed", ctx.env.get_boolean(it.removed).unwrap())?; obj.set_element(idx, item)?; idx += 1; } Ok(obj) } #[js_function(2)] fn diff_line(ctx: CallContext) -> Result { let str1: String = ctx.get::(0)?.try_into()?; let str2: String = ctx.get::(1)?.try_into()?; let res = mdiff::diff_lines(str1.as_str(), str2.as_str()); let mut obj = ctx.env.create_array_with_length(res.len()).unwrap(); let mut idx = 0; for it in res.iter() { let mut item = ctx.env.create_object().unwrap(); item.set_named_property( "count", ctx.env.create_int64(it.count.try_into().unwrap()).unwrap(), )?; item.set_named_property("value", ctx.env.create_string(&it.value).unwrap())?; item.set_named_property("added", ctx.env.get_boolean(it.added).unwrap())?; item.set_named_property("removed", ctx.env.get_boolean(it.removed).unwrap())?; obj.set_element(idx, item)?; idx += 1; } Ok(obj) }