use std::borrow::Cow;
use super::model::{DiffOptions, DocumentDiff, Finding, FindingKind, NodePath, PathStep};
use crate::model::control::Control;
use crate::model::document::Document;
use crate::model::paragraph::Paragraph;
use crate::model::style::Style;
use crate::model::table::Table;
const LCS_CELL_BUDGET: usize = 1_000_000;
const MAX_DEPTH: usize = 32;
const PREVIEW_CHARS: usize = 40;
pub fn diff_documents(a: &Document, b: &Document, opts: &DiffOptions) -> DocumentDiff {
let mut collector = Collector::new(opts.max_findings);
let root = NodePath::root();
if a.sections.len() != b.sections.len() {
collector.push(
&root,
FindingKind::SectionCountChanged,
format!("구역 수: A={} B={}", a.sections.len(), b.sections.len()),
);
}
for (i, (sa, sb)) in a.sections.iter().zip(b.sections.iter()).enumerate() {
let path = root.child(PathStep::Section(i));
compare_paragraph_list(
&mut collector,
&path,
&sa.paragraphs,
&sb.paragraphs,
opts,
0,
);
}
compare_styles(
&mut collector,
&root,
&a.doc_info.styles,
&b.doc_info.styles,
);
let truncated = collector.truncated;
DocumentDiff {
identical: collector.findings.is_empty() && !truncated,
findings: collector.findings,
truncated,
}
}
struct Collector {
findings: Vec<Finding>,
max: Option<usize>,
truncated: bool,
}
impl Collector {
fn new(max: Option<usize>) -> Self {
Self {
findings: Vec::new(),
max,
truncated: false,
}
}
fn push(&mut self, path: &NodePath, kind: FindingKind, detail: String) {
if let Some(max) = self.max {
if self.findings.len() >= max {
self.truncated = true;
return;
}
}
self.findings.push(Finding {
path: path.clone(),
kind,
detail,
});
}
}
fn normalize(text: &str, ignore_whitespace: bool) -> Cow<'_, str> {
if !ignore_whitespace {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut pending_space = false;
for ch in text.chars() {
if ch.is_whitespace() {
pending_space = !out.is_empty();
continue;
}
if pending_space {
out.push(' ');
pending_space = false;
}
out.push(ch);
}
Cow::Owned(out)
}
fn preview(text: &str) -> String {
let mut out: String = text.chars().take(PREVIEW_CHARS).collect();
if text.chars().nth(PREVIEW_CHARS).is_some() {
out.push('…');
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AlignOp {
Pair(usize, usize),
Added(usize),
Removed(usize),
}
fn compare_paragraph_list(
collector: &mut Collector,
base: &NodePath,
a: &[Paragraph],
b: &[Paragraph],
opts: &DiffOptions,
depth: usize,
) {
let keys_a: Vec<Cow<'_, str>> = a
.iter()
.map(|p| normalize(&p.text, opts.ignore_whitespace))
.collect();
let keys_b: Vec<Cow<'_, str>> = b
.iter()
.map(|p| normalize(&p.text, opts.ignore_whitespace))
.collect();
for op in align(&keys_a, &keys_b) {
match op {
AlignOp::Pair(i, j) => {
let path = base.child(PathStep::Paragraph(i));
compare_paragraph(collector, &path, &a[i], &b[j], opts, depth);
}
AlignOp::Added(j) => {
let path = base.child(PathStep::Paragraph(j));
collector.push(
&path,
FindingKind::ParagraphAdded,
format!("B 에만 있는 문단: {:?}", preview(&b[j].text)),
);
}
AlignOp::Removed(i) => {
let path = base.child(PathStep::Paragraph(i));
collector.push(
&path,
FindingKind::ParagraphRemoved,
format!("A 에만 있는 문단: {:?}", preview(&a[i].text)),
);
}
}
}
}
fn compare_paragraph(
collector: &mut Collector,
path: &NodePath,
a: &Paragraph,
b: &Paragraph,
opts: &DiffOptions,
depth: usize,
) {
if normalize(&a.text, opts.ignore_whitespace) != normalize(&b.text, opts.ignore_whitespace) {
collector.push(
path,
FindingKind::TextChanged,
format!("A={:?} B={:?}", preview(&a.text), preview(&b.text)),
);
}
if a.para_shape_id != b.para_shape_id || a.style_id != b.style_id {
collector.push(
path,
FindingKind::ParagraphStyleChanged,
format!(
"para_shape_id: A={} B={}, style_id: A={} B={}",
a.para_shape_id, b.para_shape_id, a.style_id, b.style_id
),
);
}
if a.controls.len() != b.controls.len() {
collector.push(
path,
FindingKind::ControlCountChanged,
format!("컨트롤 수: A={} B={}", a.controls.len(), b.controls.len()),
);
}
for (k, (ca, cb)) in a.controls.iter().zip(b.controls.iter()).enumerate() {
let ctrl_path = path.child(PathStep::Control(k));
let (label_a, label_b) = (control_label(ca), control_label(cb));
if label_a != label_b {
collector.push(
&ctrl_path,
FindingKind::ControlKindChanged,
format!("컨트롤 종류: A={} B={}", label_a, label_b),
);
continue;
}
if let (Control::Table(ta), Control::Table(tb)) = (ca, cb) {
compare_table(collector, &ctrl_path, ta, tb, opts, depth);
}
}
}
fn compare_table(
collector: &mut Collector,
path: &NodePath,
a: &Table,
b: &Table,
opts: &DiffOptions,
depth: usize,
) {
if a.row_count != b.row_count || a.col_count != b.col_count {
collector.push(
path,
FindingKind::TableShapeChanged,
format!(
"행렬: A={}x{} B={}x{}",
a.row_count, a.col_count, b.row_count, b.col_count
),
);
}
if a.cells.len() != b.cells.len() {
collector.push(
path,
FindingKind::TableShapeChanged,
format!("셀 수: A={} B={}", a.cells.len(), b.cells.len()),
);
}
if depth >= MAX_DEPTH {
return;
}
for (ca, cb) in a.cells.iter().zip(b.cells.iter()) {
let cell_path = path.child(PathStep::TableCell {
row: ca.row,
col: ca.col,
});
if ca.row != cb.row || ca.col != cb.col {
collector.push(
&cell_path,
FindingKind::TableShapeChanged,
format!(
"셀 주소: A=(r{},c{}) B=(r{},c{})",
ca.row, ca.col, cb.row, cb.col
),
);
}
if ca.row_span != cb.row_span || ca.col_span != cb.col_span {
collector.push(
&cell_path,
FindingKind::TableShapeChanged,
format!(
"셀 병합: A={}x{} B={}x{}",
ca.row_span, ca.col_span, cb.row_span, cb.col_span
),
);
}
compare_paragraph_list(
collector,
&cell_path,
&ca.paragraphs,
&cb.paragraphs,
opts,
depth + 1,
);
}
}
fn compare_styles(collector: &mut Collector, root: &NodePath, a: &[Style], b: &[Style]) {
if a.len() != b.len() {
collector.push(
root,
FindingKind::StyleCountChanged,
format!("스타일 수: A={} B={}", a.len(), b.len()),
);
}
for (i, (sa, sb)) in a.iter().zip(b.iter()).enumerate() {
let mut parts: Vec<String> = Vec::new();
if sa.local_name != sb.local_name {
parts.push(format!(
"이름: A={:?} B={:?}",
preview(&sa.local_name),
preview(&sb.local_name)
));
}
if sa.english_name != sb.english_name {
parts.push(format!(
"영문이름: A={:?} B={:?}",
preview(&sa.english_name),
preview(&sb.english_name)
));
}
if sa.style_type != sb.style_type {
parts.push(format!("종류: A={} B={}", sa.style_type, sb.style_type));
}
if sa.para_shape_id != sb.para_shape_id {
parts.push(format!(
"para_shape_id: A={} B={}",
sa.para_shape_id, sb.para_shape_id
));
}
if sa.char_shape_id != sb.char_shape_id {
parts.push(format!(
"char_shape_id: A={} B={}",
sa.char_shape_id, sb.char_shape_id
));
}
if !parts.is_empty() {
collector.push(
&root.child(PathStep::Style(i)),
FindingKind::StyleChanged,
parts.join("; "),
);
}
}
}
fn control_label(c: &Control) -> &'static str {
match c {
Control::SectionDef(_) => "sectionDef",
Control::ColumnDef(_) => "columnDef",
Control::Table(_) => "table",
Control::Shape(_) => "shape",
Control::Picture(_) => "picture",
Control::Header(_) => "header",
Control::Footer(_) => "footer",
Control::Footnote(_) => "footnote",
Control::Endnote(_) => "endnote",
Control::AutoNumber(_) => "autoNumber",
Control::NewNumber(_) => "newNumber",
Control::PageNumberPos(_) => "pageNumberPos",
Control::Bookmark(_) => "bookmark",
Control::IndexMark(_) => "indexMark",
Control::PageNumCtrl(_) => "pageNumCtrl",
Control::Hyperlink(_) => "hyperlink",
Control::Ruby(_) => "ruby",
Control::CharOverlap(_) => "charOverlap",
Control::PageHide(_) => "pageHide",
Control::HiddenComment(_) => "hiddenComment",
Control::Equation(_) => "equation",
Control::Field(_) => "field",
Control::Form(_) => "form",
Control::Unknown(_) => "unknown",
}
}
fn align(a: &[Cow<'_, str>], b: &[Cow<'_, str>]) -> Vec<AlignOp> {
let mut ops = Vec::with_capacity(a.len().max(b.len()));
let max_prefix = a.len().min(b.len());
let mut prefix = 0;
while prefix < max_prefix && a[prefix] == b[prefix] {
prefix += 1;
}
let max_suffix = max_prefix - prefix;
let mut suffix = 0;
while suffix < max_suffix && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] {
suffix += 1;
}
for i in 0..prefix {
ops.push(AlignOp::Pair(i, i));
}
let mid_a = &a[prefix..a.len() - suffix];
let mid_b = &b[prefix..b.len() - suffix];
ops.extend(align_middle(mid_a, mid_b, prefix, prefix));
for k in 0..suffix {
ops.push(AlignOp::Pair(a.len() - suffix + k, b.len() - suffix + k));
}
ops
}
fn align_middle(
a: &[Cow<'_, str>],
b: &[Cow<'_, str>],
off_a: usize,
off_b: usize,
) -> Vec<AlignOp> {
if a.is_empty() && b.is_empty() {
return Vec::new();
}
if a.is_empty() {
return (0..b.len()).map(|j| AlignOp::Added(off_b + j)).collect();
}
if b.is_empty() {
return (0..a.len()).map(|i| AlignOp::Removed(off_a + i)).collect();
}
let raw = if (a.len() + 1).saturating_mul(b.len() + 1) > LCS_CELL_BUDGET {
positional_ops(a.len(), b.len(), off_a, off_b)
} else {
lcs_ops(a, b, off_a, off_b)
};
pair_adjacent(raw)
}
fn positional_ops(len_a: usize, len_b: usize, off_a: usize, off_b: usize) -> Vec<AlignOp> {
let pairs = len_a.min(len_b);
let mut ops: Vec<AlignOp> = (0..pairs)
.map(|k| AlignOp::Pair(off_a + k, off_b + k))
.collect();
ops.extend((pairs..len_a).map(|i| AlignOp::Removed(off_a + i)));
ops.extend((pairs..len_b).map(|j| AlignOp::Added(off_b + j)));
ops
}
fn lcs_ops(a: &[Cow<'_, str>], b: &[Cow<'_, str>], off_a: usize, off_b: usize) -> Vec<AlignOp> {
let n = a.len();
let m = b.len();
let stride = m + 1;
let mut dp = vec![0u32; (n + 1) * stride];
for i in (0..n).rev() {
for j in (0..m).rev() {
dp[i * stride + j] = if a[i] == b[j] {
dp[(i + 1) * stride + j + 1] + 1
} else {
dp[(i + 1) * stride + j].max(dp[i * stride + j + 1])
};
}
}
let mut ops = Vec::with_capacity(n.max(m));
let (mut i, mut j) = (0usize, 0usize);
while i < n && j < m {
if a[i] == b[j] {
ops.push(AlignOp::Pair(off_a + i, off_b + j));
i += 1;
j += 1;
} else if dp[(i + 1) * stride + j] >= dp[i * stride + j + 1] {
ops.push(AlignOp::Removed(off_a + i));
i += 1;
} else {
ops.push(AlignOp::Added(off_b + j));
j += 1;
}
}
ops.extend((i..n).map(|i| AlignOp::Removed(off_a + i)));
ops.extend((j..m).map(|j| AlignOp::Added(off_b + j)));
ops
}
fn pair_adjacent(raw: Vec<AlignOp>) -> Vec<AlignOp> {
let mut out = Vec::with_capacity(raw.len());
let mut idx = 0;
while idx < raw.len() {
if !matches!(raw[idx], AlignOp::Removed(_)) {
out.push(raw[idx]);
idx += 1;
continue;
}
let mut removed = Vec::new();
while let Some(AlignOp::Removed(i)) = raw.get(idx) {
removed.push(*i);
idx += 1;
}
let mut added = Vec::new();
while let Some(AlignOp::Added(j)) = raw.get(idx) {
added.push(*j);
idx += 1;
}
let paired = removed.len().min(added.len());
for k in 0..paired {
out.push(AlignOp::Pair(removed[k], added[k]));
}
out.extend(removed.iter().skip(paired).map(|i| AlignOp::Removed(*i)));
out.extend(added.iter().skip(paired).map(|j| AlignOp::Added(*j)));
}
out
}