use serde::Serialize;
use crate::document_core::DocumentCore;
use crate::model::control::Control;
use super::grep::{CellRef, TextBoxRef};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DataKind {
Date,
Amount,
Number,
}
impl DataKind {
pub const ALL: [DataKind; 3] = [DataKind::Date, DataKind::Amount, DataKind::Number];
pub fn parse(value: &str) -> Option<Self> {
match value {
"date" => Some(Self::Date),
"amount" => Some(Self::Amount),
"number" => Some(Self::Number),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Date => "date",
Self::Amount => "amount",
Self::Number => "number",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Normalized {
Date(String),
Int(i64),
Float(f64),
}
#[derive(Debug, Clone, Serialize)]
pub struct DataItem {
pub kind: DataKind,
pub raw: String,
pub normalized: Option<Normalized>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
pub section: usize,
pub paragraph: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
#[serde(rename = "charOffset")]
pub char_offset: usize,
pub length: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub cell: Option<CellRef>,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbox: Option<TextBoxRef>,
}
#[derive(Debug, Clone)]
struct Address {
section: usize,
paragraph: usize,
page: Option<u32>,
cell: Option<CellRef>,
textbox: Option<TextBoxRef>,
}
#[derive(Debug, Clone)]
struct Extracted {
kind: DataKind,
raw: String,
normalized: Option<Normalized>,
currency: Option<&'static str>,
unit: Option<String>,
char_offset: usize,
length: usize,
}
const KRW_UNITS: &[(&str, u32)] = &[
("조원", 12),
("억원", 8),
("천만원", 7),
("백만원", 6),
("십만원", 5),
("만원", 4),
("천원", 3),
("백원", 2),
("원", 0),
];
const KRW_SCALES: &[(&str, u32)] = &[
("조", 12),
("억", 8),
("만", 4),
("천", 3),
("백", 2),
("십", 1),
];
const NUMERAL_CHARS: &str = "영일이삼사오육칠팔구십백천만억조\
零一二三四五六七八九十百千万萬億兆\
壹貳貮參参肆伍陸柒捌玖拾佰仟阡";
const NUMERAL_CURRENCY_END: &str = "원圓円元";
const KRW_SIGNS: [char; 2] = ['\u{20a9}', '\u{ffe6}'];
const MINUS_MARKS: [char; 5] = ['-', '\u{2212}', '\u{ff0d}', '\u{25b3}', '\u{25bd}'];
const YEAR_APOSTROPHES: [char; 3] = ['\'', '\u{2018}', '\u{2019}'];
const HANGUL_UNITS: &[&str] = &[
"개월",
"개소",
"개",
"명",
"건",
"매",
"부",
"회",
"권",
"점",
"대",
"인",
"곳",
"종",
"세",
"쪽",
"장",
"상자",
"시간",
"분",
"초",
"주",
"가구",
"세대",
"마리",
"그루",
"평",
"배",
"팀",
"톤",
"퍼센트",
"층",
"칸",
"석",
"가지",
"벌",
"쌍",
"분기",
"교시",
"학점",
];
const SYMBOL_UNITS: &[&str] = &[
"%", "%", "‰", "㎏", "kg", "㎡", "㎢", "㎥", "㎞", "km", "㎝", "cm", "㎜", "mm", "㎖", "mL",
"GB", "MB", "KB", "TB", "g", "t", "m", "L", "ℓ", "㏊", "ha", "㎾", "kW", "㎿", "MW", "dB", "℃",
"°C", "㎉", "kcal",
];
fn canonical_unit(unit: &str) -> String {
match unit {
"%" | "퍼센트" => "%".to_string(),
other => other.to_string(),
}
}
fn starts_with(chars: &[char], at: usize, needle: &str) -> bool {
let mut i = at;
for expected in needle.chars() {
if chars.get(i) != Some(&expected) {
return false;
}
i += 1;
}
true
}
fn longest_unit<'a>(units: &[&'a str], chars: &[char], at: usize) -> Option<&'a str> {
units
.iter()
.filter(|u| starts_with(chars, at, u))
.copied()
.max_by_key(|u| u.chars().count())
}
fn longest_krw_unit(chars: &[char], at: usize) -> Option<(&'static str, u32)> {
KRW_UNITS
.iter()
.filter(|(unit, _)| starts_with(chars, at, unit))
.max_by_key(|(unit, _)| unit.chars().count())
.copied()
}
fn unit_boundary_ok(unit: &str, chars: &[char], after: usize) -> bool {
if !unit.chars().all(|c| c.is_ascii_alphabetic()) {
return true;
}
!chars.get(after).is_some_and(|c| c.is_ascii_alphanumeric())
}
fn skip_spaces(chars: &[char], mut i: usize) -> usize {
while matches!(chars.get(i), Some(' ') | Some('\t') | Some('\u{a0}')) {
i += 1;
}
i
}
fn at_word_start(chars: &[char], at: usize) -> bool {
at == 0 || !chars[at - 1].is_alphanumeric()
}
fn read_sign(chars: &[char], at: usize) -> (usize, bool) {
if !chars.get(at).is_some_and(|c| MINUS_MARKS.contains(c)) {
return (at, false);
}
if at > 0 && (chars[at - 1].is_ascii_digit() || chars[at - 1] == ',') {
return (at, false);
}
match chars.get(at + 1) {
Some(c) if c.is_ascii_digit() => (at + 1, true),
_ => (at, false),
}
}
fn read_int(chars: &[char], start: usize) -> Option<(usize, String)> {
let mut i = start;
let mut digits = String::new();
while chars.get(i).is_some_and(|c| c.is_ascii_digit()) {
digits.push(chars[i]);
i += 1;
}
if digits.is_empty() {
return None;
}
if digits.len() <= 3 {
while i + 3 < chars.len()
&& chars[i] == ','
&& chars[i + 1].is_ascii_digit()
&& chars[i + 2].is_ascii_digit()
&& chars[i + 3].is_ascii_digit()
&& !chars.get(i + 4).is_some_and(|c| c.is_ascii_digit())
{
digits.push(chars[i + 1]);
digits.push(chars[i + 2]);
digits.push(chars[i + 3]);
i += 4;
}
}
Some((i, digits))
}
fn read_frac(chars: &[char], start: usize) -> Option<(usize, String)> {
if chars.get(start) != Some(&'.') {
return None;
}
let mut i = start + 1;
let mut digits = String::new();
while chars.get(i).is_some_and(|c| c.is_ascii_digit()) {
digits.push(chars[i]);
i += 1;
}
if digits.is_empty() {
None
} else {
Some((i, digits))
}
}
fn read_fixed_digits(chars: &[char], start: usize, min: usize, max: usize) -> Option<(usize, u32)> {
let mut i = start;
let mut value: u32 = 0;
let mut count = 0;
while count < max && chars.get(i).is_some_and(|c| c.is_ascii_digit()) {
value = value * 10 + chars[i].to_digit(10).unwrap_or(0);
i += 1;
count += 1;
}
if count < min || chars.get(i).is_some_and(|c| c.is_ascii_digit()) {
return None;
}
Some((i, value))
}
struct DateHit {
end: usize,
iso: Option<String>,
}
type MonthDay = (usize, u32, Option<u32>);
fn valid_day(day: u32) -> bool {
(1..=31).contains(&day)
}
fn date_body_korean(chars: &[char], at: usize) -> Option<MonthDay> {
let mut i = skip_spaces(chars, at + 1);
let (after, month) = read_fixed_digits(chars, i, 1, 2)?;
i = skip_spaces(chars, after);
if chars.get(i) != Some(&'월') {
return None;
}
i += 1;
let year_month_end = i;
let day_start = skip_spaces(chars, i);
if let Some((after_day, day)) = read_fixed_digits(chars, day_start, 1, 2) {
let mark = skip_spaces(chars, after_day);
if chars.get(mark) == Some(&'일') && valid_day(day) {
return Some((mark + 1, month, Some(day)));
}
}
Some((year_month_end, month, None))
}
fn date_body_dotted(chars: &[char], at: usize) -> Option<MonthDay> {
let mut i = skip_spaces(chars, at + 1);
let (after, month) = read_fixed_digits(chars, i, 1, 2)?;
i = skip_spaces(chars, after);
if chars.get(i) != Some(&'.') {
return None;
}
i += 1;
let year_month_end = i;
let day_start = skip_spaces(chars, i);
if let Some((after_day, day)) = read_fixed_digits(chars, day_start, 1, 2) {
if valid_day(day) {
let mark = skip_spaces(chars, after_day);
let end = if chars.get(mark) == Some(&'.') {
mark + 1
} else {
after_day
};
return Some((end, month, Some(day)));
}
}
Some((year_month_end, month, None))
}
fn date_body_separator(chars: &[char], at: usize, sep: char, width: usize) -> Option<MonthDay> {
let (after_month, month) = read_fixed_digits(chars, at + 1, width, 2)?;
if chars.get(after_month) != Some(&sep) {
return None;
}
let (after_day, day) = read_fixed_digits(chars, after_month + 1, width, 2)?;
if !valid_day(day) {
return None;
}
Some((after_day, month, Some(day)))
}
fn try_date(chars: &[char], start: usize) -> Option<DateHit> {
let (after_year, year, four_digit) = if chars
.get(start)
.is_some_and(|c| YEAR_APOSTROPHES.contains(c))
{
let (end, value) = read_fixed_digits(chars, start + 1, 2, 2)?;
(end, value, false)
} else {
let (end, value) = read_fixed_digits(chars, start, 4, 4)?;
(end, value, true)
};
let sep_at = skip_spaces(chars, after_year);
let (mut end, month, day) = match chars.get(sep_at) {
Some('년') => date_body_korean(chars, sep_at)?,
Some('.') => date_body_dotted(chars, sep_at)?,
Some('-') => date_body_separator(chars, sep_at, '-', 2)?,
Some('/') => date_body_separator(chars, sep_at, '/', 1)?,
_ => return None,
};
if !(1..=12).contains(&month) {
return None;
}
let paren = skip_spaces(chars, end);
if chars.get(paren) == Some(&'(')
&& chars
.get(paren + 1)
.is_some_and(|c| "월화수목금토일".contains(*c))
{
let mut close = paren + 2;
if starts_with(chars, close, "요일") {
close += 2;
}
if chars.get(close) == Some(&')') {
end = close + 1;
}
}
let iso = four_digit.then(|| match day {
Some(d) => format!("{year:04}-{month:02}-{d:02}"),
None => format!("{year:04}-{month:02}"),
});
Some(DateHit { end, iso })
}
struct AmountHit {
end: usize,
value: Option<i64>,
}
fn scaled_value(int_digits: &str, frac_digits: &str, pow10: u32) -> Option<i64> {
let mantissa: i128 = format!("{int_digits}{frac_digits}").parse().ok()?;
let exponent = pow10 as i32 - frac_digits.len() as i32;
let value = if exponent >= 0 {
mantissa.checked_mul(10i128.checked_pow(exponent.unsigned_abs())?)?
} else {
let divisor = 10i128.checked_pow(exponent.unsigned_abs())?;
if mantissa % divisor != 0 {
return None;
}
mantissa / divisor
};
i64::try_from(value).ok()
}
fn read_krw_chain(chars: &[char], start: usize) -> Option<(usize, Option<i64>)> {
let mut i = start;
let mut total: Option<i128> = Some(0);
let mut previous_scale: Option<u32> = None;
for _ in 0..=KRW_SCALES.len() {
let (after_int, int_digits) = read_int(chars, i)?;
let (after_number, frac_digits) =
read_frac(chars, after_int).unwrap_or_else(|| (after_int, String::new()));
let add = |total: Option<i128>, pow10: u32| -> Option<i128> {
match (total, scaled_value(&int_digits, &frac_digits, pow10)) {
(Some(sum), Some(term)) => sum.checked_add(i128::from(term)),
_ => None,
}
};
if let Some((unit, pow10)) = longest_krw_unit(chars, after_number) {
if previous_scale.is_some_and(|prev| prev <= pow10) {
return None;
}
let total = add(total, pow10);
let end = after_number + unit.chars().count();
return Some((end, total.and_then(|v| i64::try_from(v).ok())));
}
let (scale, pow10) = KRW_SCALES
.iter()
.filter(|(scale, _)| starts_with(chars, after_number, scale))
.max_by_key(|(scale, _)| scale.chars().count())
.copied()?;
if previous_scale.is_some_and(|prev| prev <= pow10) {
return None;
}
total = add(total, pow10);
previous_scale = Some(pow10);
i = skip_spaces(chars, after_number + scale.chars().count());
}
None
}
fn try_amount(chars: &[char], start: usize) -> Option<AmountHit> {
let (mut i, mut negative) = read_sign(chars, start);
let prefixed = if !at_word_start(chars, i) {
false
} else if let Some(prefix) = ["일금", "一金", "壹金", "금", "金"]
.into_iter()
.find(|prefix| starts_with(chars, i, prefix))
{
i += prefix.chars().count();
true
} else {
false
};
if prefixed {
i = skip_spaces(chars, i);
}
let signed = chars.get(i).is_some_and(|c| KRW_SIGNS.contains(c));
if signed {
i = skip_spaces(chars, i + 1);
if !negative {
let (after_sign, is_negative) = read_sign(chars, i);
i = after_sign;
negative = is_negative;
}
}
let apply = |value: Option<i64>| value.map(|v| if negative { -v } else { v });
if let Some((mut end, value)) = read_krw_chain(chars, i) {
if chars.get(end) == Some(&'정') {
end += 1;
}
return Some(AmountHit {
end,
value: apply(value),
});
}
if signed {
if let Some((after_int, int_digits)) = read_int(chars, i) {
let (end, frac_digits) =
read_frac(chars, after_int).unwrap_or_else(|| (after_int, String::new()));
return Some(AmountHit {
end,
value: apply(scaled_value(&int_digits, &frac_digits, 0)),
});
}
}
if prefixed || signed {
let mut end = i;
while chars.get(end).is_some_and(|c| NUMERAL_CHARS.contains(*c)) {
end += 1;
}
if end > i
&& chars
.get(end)
.is_some_and(|c| NUMERAL_CURRENCY_END.contains(*c))
{
end += 1;
if chars.get(end) == Some(&'정') {
end += 1;
}
return Some(AmountHit { end, value: None });
}
}
None
}
struct NumberHit {
end: usize,
value: Option<Normalized>,
unit: String,
}
fn try_number(chars: &[char], start: usize) -> Option<NumberHit> {
if start > 0 && chars[start - 1] == '제' {
return None;
}
let (num_start, negative) = read_sign(chars, start);
let (after_int, int_digits) = read_int(chars, num_start)?;
let (after_number, frac_digits) =
read_frac(chars, after_int).unwrap_or_else(|| (after_int, String::new()));
let spaced = skip_spaces(chars, after_number);
let (unit, end) = match longest_unit(HANGUL_UNITS, chars, after_number) {
Some(unit) => (unit, after_number + unit.chars().count()),
None => {
let unit = longest_unit(SYMBOL_UNITS, chars, spaced)?;
let end = spaced + unit.chars().count();
if !unit_boundary_ok(unit, chars, end) {
return None;
}
(unit, end)
}
};
let sign = if negative { "-" } else { "" };
let value = if frac_digits.is_empty() {
format!("{sign}{int_digits}")
.parse::<i64>()
.ok()
.map(Normalized::Int)
} else {
format!("{sign}{int_digits}.{frac_digits}")
.parse::<f64>()
.ok()
.map(Normalized::Float)
};
Some(NumberHit {
end,
value,
unit: canonical_unit(unit),
})
}
fn scan_text(text: &str) -> Vec<Extracted> {
let chars: Vec<char> = text.chars().collect();
let mut out: Vec<Extracted> = Vec::new();
let mut i = 0usize;
while i < chars.len() {
if chars[i].is_ascii_digit()
&& i > 0
&& (chars[i - 1].is_ascii_digit() || chars[i - 1] == ',' || chars[i - 1] == '.')
{
i += 1;
continue;
}
if let Some(hit) = try_date(&chars, i) {
out.push(Extracted {
kind: DataKind::Date,
raw: chars[i..hit.end].iter().collect(),
normalized: hit.iso.map(Normalized::Date),
currency: None,
unit: None,
char_offset: i,
length: hit.end - i,
});
i = hit.end;
continue;
}
if let Some(hit) = try_amount(&chars, i) {
out.push(Extracted {
kind: DataKind::Amount,
raw: chars[i..hit.end].iter().collect(),
normalized: hit.value.map(Normalized::Int),
currency: Some("KRW"),
unit: None,
char_offset: i,
length: hit.end - i,
});
i = hit.end;
continue;
}
if let Some(hit) = try_number(&chars, i) {
out.push(Extracted {
kind: DataKind::Number,
raw: chars[i..hit.end].iter().collect(),
normalized: hit.value,
currency: None,
unit: Some(hit.unit),
char_offset: i,
length: hit.end - i,
});
i = hit.end;
continue;
}
i += 1;
}
out
}
fn collect_into(out: &mut Vec<DataItem>, text: &str, at: &Address) {
if text.is_empty() {
return;
}
for found in scan_text(text) {
out.push(DataItem {
kind: found.kind,
raw: found.raw,
normalized: found.normalized,
currency: found.currency,
unit: found.unit,
section: at.section,
paragraph: at.paragraph,
page: at.page,
char_offset: found.char_offset,
length: found.length,
cell: at.cell.clone(),
textbox: at.textbox.clone(),
});
}
}
impl DocumentCore {
pub fn extract_data(&self, kinds: &[DataKind]) -> Vec<DataItem> {
let page_index = self.build_paragraph_page_index();
let table_row_pages = self.build_table_row_page_index();
let mut out: Vec<DataItem> = Vec::new();
for (sec_idx, section) in self.document.sections.iter().enumerate() {
for (para_idx, para) in section.paragraphs.iter().enumerate() {
let page = page_index.get(&(sec_idx, para_idx)).copied();
let body = Address {
section: sec_idx,
paragraph: para_idx,
page,
cell: None,
textbox: None,
};
collect_into(&mut out, ¶.text, &body);
for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
match ctrl {
Control::Table(table) => {
for (cell_idx, cell) in table.cells.iter().enumerate() {
let cell_page = table_row_pages
.get(&(sec_idx, para_idx, ctrl_idx))
.and_then(|ranges| {
ranges
.iter()
.find(|(start, end, _)| {
(cell.row as usize) >= *start
&& (cell.row as usize) < *end
})
.map(|(_, _, page)| *page)
})
.or(page);
for (cp_idx, cp) in cell.paragraphs.iter().enumerate() {
let at = Address {
section: sec_idx,
paragraph: para_idx,
page: cell_page,
cell: Some(CellRef {
control: ctrl_idx,
cell: cell_idx,
paragraph: cp_idx,
}),
textbox: None,
};
collect_into(&mut out, &cp.text, &at);
}
}
}
Control::Shape(shape) => {
if let Some(tb) =
crate::document_core::helpers::get_textbox_from_shape(shape)
{
for (tp_idx, tp) in tb.paragraphs.iter().enumerate() {
let at = Address {
section: sec_idx,
paragraph: para_idx,
page,
cell: None,
textbox: Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
};
collect_into(&mut out, &tp.text, &at);
}
}
}
_ => {}
}
}
}
}
if kinds.is_empty() {
out
} else {
out.retain(|item| kinds.contains(&item.kind));
out
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn one(text: &str) -> Extracted {
let found = scan_text(text);
assert_eq!(found.len(), 1, "{text:?} → {found:?}");
found.into_iter().next().expect("항목 1건")
}
fn iso(text: &str) -> Option<String> {
match one(text).normalized {
Some(Normalized::Date(s)) => Some(s),
None => None,
other => panic!("{text:?} 는 날짜가 아님: {other:?}"),
}
}
fn amount(text: &str) -> Option<i64> {
let item = one(text);
assert_eq!(item.kind, DataKind::Amount, "{text:?}");
assert_eq!(item.currency, Some("KRW"), "{text:?}");
match item.normalized {
Some(Normalized::Int(v)) => Some(v),
None => None,
other => panic!("{text:?} 금액 정규화 형태 오류: {other:?}"),
}
}
#[test]
fn dates_in_real_notations() {
assert_eq!(iso("2026년 8월 2일").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026년 8월 2일(월)").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026. 8. 2.").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026.8.2").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026-08-02").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026/8/2").as_deref(), Some("2026-08-02"));
assert_eq!(iso("1949. 7. 15.").as_deref(), Some("1949-07-15"));
assert_eq!(iso("2026. 1.").as_deref(), Some("2026-01"));
assert_eq!(iso("2025년 12월").as_deref(), Some("2025-12"));
}
#[test]
fn two_digit_year_is_not_guessed() {
let item = one("'26.8.2");
assert_eq!(item.kind, DataKind::Date);
assert_eq!(item.raw, "'26.8.2");
assert!(item.normalized.is_none(), "{item:?}");
}
#[test]
fn invalid_dates_are_rejected() {
assert!(
scan_text("2026년 13월 2일").is_empty(),
"13월은 날짜가 아님"
);
assert!(scan_text("2026-02-32").is_empty(), "32일은 날짜가 아님");
assert!(scan_text("1. 개요").is_empty());
assert!(scan_text("제3조 제1항").is_empty());
}
#[test]
fn amounts_in_real_notations() {
assert_eq!(amount("1,234,567원"), Some(1_234_567));
assert_eq!(amount("금113,560원"), Some(113_560));
assert_eq!(amount("금 1,234,567원"), Some(1_234_567));
assert_eq!(amount("\u{20a9}1,234,567"), Some(1_234_567));
assert_eq!(amount("3,180백만원"), Some(3_180_000_000));
assert_eq!(amount("21,345천원"), Some(21_345_000));
assert_eq!(amount("57억원"), Some(5_700_000_000));
assert_eq!(amount("1.5억원"), Some(150_000_000));
assert_eq!(amount("금 1,234,567원정"), Some(1_234_567));
}
#[test]
fn more_date_notations() {
assert_eq!(iso("2026.08.02").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026년8월2일").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026 . 8 . 2 .").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026. 8. 2.(월요일)").as_deref(), Some("2026-08-02"));
assert_eq!(iso("2026년 8월 2일 (일)").as_deref(), Some("2026-08-02"));
for text in ["'26. 8. 2.", "\u{2018}26. 8. 2.", "\u{2019}26. 8. 2."] {
let item = one(text);
assert_eq!(item.kind, DataKind::Date, "{text}");
assert!(item.normalized.is_none(), "{text} → {item:?}");
}
}
#[test]
fn ambiguous_date_shapes_are_not_extracted() {
assert!(scan_text("20260802").is_empty());
assert!(scan_text("8/2").is_empty());
assert!(scan_text("8. 2.").is_empty());
assert!(scan_text("26. 8. 2.").is_empty());
}
#[test]
fn korean_and_hanja_numeral_amounts_are_raw_only() {
for text in [
"일금 백이십삼만원",
"금일십일만삼천오백육십원",
"金壹百貳拾參萬圓",
"一金 百二十三萬圓",
"일금 백이십삼만원정",
] {
let item = one(text);
assert_eq!(item.kind, DataKind::Amount, "{text}");
assert_eq!(item.raw, text, "{text}");
assert_eq!(item.currency, Some("KRW"), "{text}");
assert!(item.normalized.is_none(), "{text} → {item:?}");
}
assert!(scan_text("백이십삼만원").is_empty());
}
#[test]
fn compound_amounts_sum_by_descending_scale() {
assert_eq!(amount("3억5천만원"), Some(350_000_000));
assert_eq!(amount("1억 2천만원"), Some(120_000_000));
assert_eq!(amount("3만5천원"), Some(35_000));
assert_eq!(amount("1,234만원"), Some(12_340_000));
assert_eq!(amount("5백원"), Some(500));
}
#[test]
fn malformed_compound_amounts_are_not_guessed() {
let found = scan_text("3만 5억원");
assert!(
!found
.iter()
.any(|f| f.normalized == Some(Normalized::Int(350_000_000))),
"뒤집힌 자릿수를 합산했습니다: {found:?}"
);
assert!(
scan_text("2천억원").is_empty(),
"{:?}",
scan_text("2천억원")
);
}
#[test]
fn negative_markers_flip_the_sign() {
assert_eq!(amount("-1,234,567원"), Some(-1_234_567));
assert_eq!(amount("\u{25b3}1,234,567원"), Some(-1_234_567));
assert_eq!(amount("\u{2212}1,234,567원"), Some(-1_234_567));
let item = one("\u{25b3}12.3%");
assert_eq!(item.kind, DataKind::Number);
assert_eq!(item.normalized, Some(Normalized::Float(-12.3)));
assert_eq!(item.raw, "\u{25b3}12.3%");
}
#[test]
fn direction_arrows_are_not_signs() {
let item = one("\u{25b2}12.3%");
assert_eq!(item.normalized, Some(Normalized::Float(12.3)));
assert_eq!(item.raw, "12.3%", "화살표는 표기에 포함하지 않는다");
}
#[test]
fn bullets_and_ranges_are_not_signs() {
let item = one("- 1,234,567원");
assert_eq!(item.normalized, Some(Normalized::Int(1_234_567)));
let found = scan_text("3-5개");
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].normalized, Some(Normalized::Int(5)), "{found:?}");
}
#[test]
fn parentheses_are_not_read_as_a_minus() {
assert!(scan_text("(1,234,567)원").is_empty());
assert!(scan_text("(3)원칙").is_empty());
let item = one("(1,234,567원)");
assert_eq!(item.normalized, Some(Normalized::Int(1_234_567)));
assert_eq!(item.raw, "1,234,567원");
}
#[test]
fn currency_symbols_and_foreign_currency() {
assert_eq!(amount("\u{20a9}1,234,567"), Some(1_234_567));
assert_eq!(amount("\u{ffe6}1,234,567"), Some(1_234_567));
assert_eq!(amount("\u{20a9} 1,234,567"), Some(1_234_567));
assert_eq!(amount("\u{20a9}1,234,567원"), Some(1_234_567));
assert!(scan_text("$1,234").is_empty());
assert!(scan_text("USD 1,234").is_empty());
assert!(scan_text("\u{20ac}1,234").is_empty());
assert!(scan_text("\u{00a5}1,234").is_empty());
}
#[test]
fn measurement_units_are_recognized() {
for (text, unit) in [
("35\u{2103}", "\u{2103}"),
("30kW", "kW"),
("120\u{33a5}", "\u{33a5}"),
("3\u{33ca}", "\u{33ca}"),
("12개월", "개월"),
("3분기", "분기"),
("5층", "층"),
] {
assert_eq!(one(text).unit.as_deref(), Some(unit), "{text}");
}
}
#[test]
fn amount_prefix_is_not_a_syllable_of_another_word() {
let found = scan_text("지금 5명");
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].kind, DataKind::Number);
assert_eq!(found[0].raw, "5명");
}
#[test]
fn quantities_carry_a_unit() {
let item = one("12개");
assert_eq!(item.kind, DataKind::Number);
assert_eq!(item.unit.as_deref(), Some("개"));
assert_eq!(item.normalized, Some(Normalized::Int(12)));
let item = one("3.5%");
assert_eq!(item.unit.as_deref(), Some("%"));
assert_eq!(item.normalized, Some(Normalized::Float(3.5)));
let item = one("1,000명");
assert_eq!(item.unit.as_deref(), Some("명"));
assert_eq!(item.normalized, Some(Normalized::Int(1000)));
assert!(scan_text("표에 1234 가 있다").is_empty());
}
#[test]
fn hangul_unit_must_be_adjacent() {
assert!(
scan_text("표 3 개요").is_empty(),
"{:?}",
scan_text("표 3 개요")
);
assert_eq!(one("62.9 %").unit.as_deref(), Some("%"));
}
#[test]
fn latin_unit_needs_a_boundary() {
assert_eq!(one("210mm").unit.as_deref(), Some("mm"));
assert!(
scan_text("3gb").is_empty(),
"라틴 단위 뒤 영숫자는 단위가 아님"
);
}
#[test]
fn items_do_not_overlap() {
let found = scan_text("2026년 8월 2일 예산 1,234,567원 집행률 62.9%");
let kinds: Vec<DataKind> = found.iter().map(|f| f.kind).collect();
assert_eq!(
kinds,
vec![DataKind::Date, DataKind::Amount, DataKind::Number],
"{found:?}"
);
for pair in found.windows(2) {
assert!(
pair[0].char_offset + pair[0].length <= pair[1].char_offset,
"구간이 겹침: {pair:?}"
);
}
}
#[test]
fn char_offsets_are_character_based() {
let found = scan_text("지급액은 1,000원");
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].char_offset, 5, "{found:?}");
assert_eq!(found[0].length, "1,000원".chars().count(), "{found:?}");
}
#[test]
fn long_digit_runs_do_not_blow_up() {
let text = "1".repeat(200_000);
let started = std::time::Instant::now();
let found = scan_text(&text);
assert!(found.is_empty(), "단위 없는 숫자는 항목이 아니다");
assert!(
started.elapsed().as_secs() < 2,
"20만 자 숫자 열 스캔이 {:?} 걸렸습니다 — 선형이어야 합니다",
started.elapsed()
);
}
}