1use crate::{break_allowed, decode_utf8_bmp, is_cjk};
6use std::panic::{catch_unwind, AssertUnwindSafe};
7
8pub const HPL_CJK_ABI_VERSION: u32 = 1;
10
11pub const HPL_CJK_OK: i32 = 0;
13pub const HPL_CJK_BUFFER_TOO_SMALL: i32 = 1;
15pub const HPL_CJK_NULL_POINTER: i32 = -1;
17pub const HPL_CJK_PANIC: i32 = -2;
19
20#[repr(C)]
22#[derive(Clone, Copy, Debug, Default)]
23pub struct HplCjkDecodeResult {
24 pub len: u32,
26 pub invalid: u32,
28 pub astral: u32,
30}
31
32#[no_mangle]
33pub extern "C" fn hpl_cjk_abi_version() -> u32 {
34 HPL_CJK_ABI_VERSION
35}
36
37#[no_mangle]
43pub unsafe extern "C" fn hpl_cjk_decode_utf8(
44 src: *const u8,
45 src_len: u32,
46 dst: *mut u16,
47 dst_cap: u32,
48 out: *mut HplCjkDecodeResult,
49) -> i32 {
50 if out.is_null() || (src.is_null() && src_len > 0) || (dst.is_null() && dst_cap > 0) {
51 return HPL_CJK_NULL_POINTER;
52 }
53 let bytes: &[u8] = if src_len == 0 { &[] } else { std::slice::from_raw_parts(src, src_len as usize) };
54 let decoded = catch_unwind(AssertUnwindSafe(|| decode_utf8_bmp(bytes)));
55 let Ok((units, stats)) = decoded else {
56 return HPL_CJK_PANIC;
57 };
58 let result = HplCjkDecodeResult { len: units.len() as u32, invalid: stats.invalid, astral: stats.astral };
59 *out = result;
60 if units.len() > dst_cap as usize {
61 return HPL_CJK_BUFFER_TOO_SMALL;
62 }
63 if !units.is_empty() {
64 std::ptr::copy_nonoverlapping(units.as_ptr(), dst, units.len());
65 }
66 HPL_CJK_OK
67}
68
69fn to_char(unit: u32) -> Option<char> {
70 char::from_u32(unit)
71}
72
73#[no_mangle]
75pub extern "C" fn hpl_cjk_break_allowed(prev: u32, next: u32) -> u32 {
76 match (to_char(prev), to_char(next)) {
77 (Some(a), Some(b)) => catch_unwind(|| break_allowed(a, b)).unwrap_or(false) as u32,
78 _ => 0,
79 }
80}
81
82#[no_mangle]
84pub extern "C" fn hpl_cjk_is_cjk(c: u32) -> u32 {
85 to_char(c).map(|ch| catch_unwind(|| is_cjk(ch)).unwrap_or(false)).unwrap_or(false) as u32
86}