use crate::parser::hwp3::johab::{decode_johab, decode_johab_araea_jamo};
pub fn decode_hwp3_string(bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let b1 = bytes[i];
if b1 == 0 {
break; }
if b1 < 0x80 {
result.push(b1 as char);
i += 1;
} else {
if i + 1 < bytes.len() {
let b2 = bytes[i + 1];
let ch = ((b1 as u16) << 8) | (b2 as u16);
result.push(decode_johab(ch));
i += 2;
} else {
result.push('?');
i += 1;
}
}
}
result
}
pub fn decode_hchar_array(bytes: &[u8]) -> String {
let mut result = String::new();
for pair in bytes.chunks_exact(2) {
let ch = u16::from_le_bytes([pair[0], pair[1]]);
if ch == 0 {
break;
}
if let Some((leading, araea, trailing)) = decode_johab_araea_jamo(ch) {
result.extend([leading, Some(araea), trailing].into_iter().flatten());
continue;
}
let c = decode_johab(ch);
if c == '?' && ch >= 0x0080 {
continue;
}
result.push(c);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_hwp3_string() {
let ascii_bytes = b"Hello\0World";
assert_eq!(decode_hwp3_string(ascii_bytes), "Hello");
let johab_bytes = [0x88, 0x61, 0x00];
assert_eq!(decode_hwp3_string(&johab_bytes), "가");
let mixed_bytes = [0x41, 0x88, 0x61, 0x42, 0x00];
assert_eq!(decode_hwp3_string(&mixed_bytes), "A가B");
}
}