minify-html/java/src/main/rust/lib.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

2020-07-11 11:29:34 -04:00
use minify_html::{in_place as minify_html_native, Cfg};
2020-01-18 01:55:13 -05:00
use jni::JNIEnv;
use jni::objects::{JByteBuffer, JClass, JObject, JString};
use jni::sys::{jint, jstring};
use std::str::from_utf8_unchecked;
fn build_cfg(
env: &JNIEnv,
obj: &JObject,
) -> Cfg {
Cfg {
minify_js: env.get_field(*obj, "minifyJs", "Z").unwrap().z().unwrap(),
}
}
2020-01-18 01:55:13 -05:00
#[no_mangle]
2020-07-11 11:29:34 -04:00
pub extern "system" fn Java_in_wilsonl_minify_1html_MinifyHtml_minifyInPlace(
2020-01-18 01:55:13 -05:00
env: JNIEnv,
_class: JClass,
input: JByteBuffer,
cfg: JObject,
2020-01-18 01:55:13 -05:00
)
-> jint {
let source = match env.get_direct_buffer_address(input) {
Ok(ptr) => ptr,
Err(_) => {
env.throw_new("java/lang/IllegalArgumentException", "ByteBuffer is not direct").unwrap();
return 0;
}
};
2020-07-11 11:29:34 -04:00
(match minify_html_native(source, &build_cfg(&env, &cfg)) {
2020-01-18 01:55:13 -05:00
Ok(out_len) => out_len,
Err((err, pos)) => {
env.throw_new(
2020-07-11 11:29:34 -04:00
"in/wilsonl/minify_html/MinifyHtml$SyntaxException",
2020-01-18 01:55:13 -05:00
format!("{} [Character {}]", err.message(), pos),
).unwrap();
0
}
}) as jint
}
#[no_mangle]
2020-07-11 11:29:34 -04:00
pub extern "system" fn Java_in_wilsonl_minify_1html_MinifyHtml_minify(
2020-01-18 01:55:13 -05:00
env: JNIEnv,
_class: JClass,
input: JString,
cfg: JObject,
2020-01-18 01:55:13 -05:00
)
-> jstring {
let source: String = env.get_string(input).unwrap().into();
let mut code = source.into_bytes();
2020-01-18 01:55:13 -05:00
2020-07-11 11:29:34 -04:00
match minify_html_native(&mut code, &build_cfg(&env, &cfg)) {
2020-01-18 01:55:13 -05:00
Ok(out_len) => env.new_string(unsafe { from_utf8_unchecked(&code[0..out_len]) }).unwrap().into_inner(),
Err((err, pos)) => {
env.throw_new(
2020-07-11 11:29:34 -04:00
"in/wilsonl/minify_html/MinifyHtml$SyntaxException",
2020-01-18 01:55:13 -05:00
format!("{} [Character {}]", err.message(), pos),
).unwrap();
JObject::null().into_inner()
}
}
}