use std::collections::{HashMap, HashSet};
use serde::Serialize;
use crate::document_core::queries::grep::{CellRef, TextBoxRef};
use crate::document_core::DocumentCore;
use crate::model::control::Control;
use crate::model::paragraph::Paragraph;
use crate::model::shape::{DrawingObjAttr, ShapeObject, TextWrap};
use crate::model::style::{CharShape, FillType};
use crate::model::ColorRef;
use crate::renderer::pagination::PageItem;
use crate::renderer::render_tree::{RenderNode, RenderNodeType};
pub const DEFAULT_THRESHOLD_PT: f64 = 1.0;
pub const DEFAULT_EXCERPT_LIMIT: usize = 200;
const PAPER_WHITE: ColorRef = 0x00FF_FFFF;
const MAX_NEST_DEPTH: usize = 8;
#[derive(Debug, Clone, Copy)]
pub struct HiddenTextOptions {
pub include_off_page: bool,
pub threshold_pt: f64,
pub excerpt_limit: usize,
}
impl Default for HiddenTextOptions {
fn default() -> Self {
Self {
include_off_page: false,
threshold_pt: DEFAULT_THRESHOLD_PT,
excerpt_limit: DEFAULT_EXCERPT_LIMIT,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HiddenKind {
SameAsBackground,
NearInvisible,
ZeroSize,
OffPage,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BackgroundSource {
CharShade,
Paragraph,
TableCell,
TextBox,
Page,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Background {
Known {
color: ColorRef,
source: BackgroundSource,
},
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Verdict {
ZeroSize {
effective_pt: f64,
},
SameAsBackground {
text_color: ColorRef,
background: ColorRef,
source: BackgroundSource,
},
NearInvisible {
effective_pt: f64,
},
}
impl Verdict {
pub fn kind(&self) -> HiddenKind {
match self {
Verdict::ZeroSize { .. } => HiddenKind::ZeroSize,
Verdict::SameAsBackground { .. } => HiddenKind::SameAsBackground,
Verdict::NearInvisible { .. } => HiddenKind::NearInvisible,
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct HiddenDetail {
#[serde(rename = "textColor", skip_serializing_if = "Option::is_none")]
pub text_color: Option<String>,
#[serde(rename = "shadeColor", skip_serializing_if = "Option::is_none")]
pub shade_color: Option<String>,
#[serde(rename = "backgroundColor", skip_serializing_if = "Option::is_none")]
pub background_color: Option<String>,
#[serde(rename = "backgroundSource", skip_serializing_if = "Option::is_none")]
pub background_source: Option<BackgroundSource>,
#[serde(rename = "effectivePt", skip_serializing_if = "Option::is_none")]
pub effective_pt: Option<f64>,
#[serde(rename = "thresholdPt", skip_serializing_if = "Option::is_none")]
pub threshold_pt: Option<f64>,
#[serde(rename = "bbox", skip_serializing_if = "Option::is_none")]
pub bbox: Option<BBox>,
#[serde(rename = "pageSize", skip_serializing_if = "Option::is_none")]
pub page_size: Option<PageSize>,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub struct BBox {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub struct PageSize {
pub w: f64,
pub h: f64,
}
#[derive(Debug, Clone, Serialize)]
pub struct HiddenTextFinding {
pub kind: HiddenKind,
pub section: usize,
pub paragraph: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cell: Option<CellRef>,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbox: Option<TextBoxRef>,
pub excerpt: String,
#[serde(rename = "charCount")]
pub char_count: usize,
pub detail: HiddenDetail,
}
#[derive(Debug, Clone, Serialize)]
pub struct HiddenTextReport {
#[serde(rename = "hiddenText")]
pub hidden_text: Vec<HiddenTextFinding>,
#[serde(rename = "hiddenCharCount")]
pub hidden_char_count: usize,
pub clean: bool,
}
fn hex(color: ColorRef) -> String {
format!(
"#{:02X}{:02X}{:02X}",
color & 0xFF,
(color >> 8) & 0xFF,
(color >> 16) & 0xFF
)
}
use crate::model::color::{char_shade, opaque_rgb};
pub fn effective_pt(shape: &CharShape) -> f64 {
shape.base_size.max(0) as f64 / 100.0
}
pub fn classify_char(
shape: &CharShape,
container: Background,
threshold_pt: f64,
) -> Option<Verdict> {
let pt = effective_pt(shape);
if pt <= 0.0 {
return Some(Verdict::ZeroSize { effective_pt: pt });
}
let background = match char_shade(shape.shade_color) {
Some(color) => Background::Known {
color,
source: BackgroundSource::CharShade,
},
None => container,
};
if let (Some(text_color), Background::Known { color, source }) =
(opaque_rgb(shape.text_color), background)
{
if text_color == color {
return Some(Verdict::SameAsBackground {
text_color,
background: color,
source,
});
}
}
if pt < threshold_pt {
return Some(Verdict::NearInvisible { effective_pt: pt });
}
None
}
fn is_reportable(ch: char) -> bool {
!ch.is_control()
}
fn is_content(ch: char) -> bool {
!ch.is_control() && !ch.is_whitespace()
}
fn fill_background(
doc: &DocumentCore,
border_fill_id: u16,
source: BackgroundSource,
) -> Option<Background> {
if border_fill_id == 0 {
return None;
}
let idx = (border_fill_id as usize).saturating_sub(1);
let style = doc.styles.border_styles.get(idx)?;
if style.gradient.is_some() || style.image_fill.is_some() || style.pattern.is_some() {
return Some(Background::Unknown);
}
style
.fill_color
.and_then(opaque_rgb)
.map(|color| Background::Known { color, source })
}
fn shape_background(drawing: &DrawingObjAttr) -> Background {
match drawing.fill.fill_type {
FillType::Solid => match drawing.fill.solid.as_ref() {
Some(solid) if solid.pattern_type == 0 => match opaque_rgb(solid.background_color) {
Some(color) => Background::Known {
color,
source: BackgroundSource::TextBox,
},
None => Background::Unknown,
},
_ => Background::Unknown,
},
_ => Background::Unknown,
}
}
fn drawing_of(shape: &ShapeObject) -> Option<&DrawingObjAttr> {
match shape {
ShapeObject::Rectangle(s) => Some(&s.drawing),
ShapeObject::Ellipse(s) => Some(&s.drawing),
ShapeObject::Polygon(s) => Some(&s.drawing),
ShapeObject::Curve(s) => Some(&s.drawing),
_ => None,
}
}
impl DocumentCore {
fn page_background(&self, sec_idx: usize) -> Background {
let Some(section) = self.document.sections.get(sec_idx) else {
return Background::Unknown;
};
let def = §ion.section_def;
if !def.master_pages.is_empty() && !def.hide_master_page {
return Background::Unknown;
}
if section.paragraphs.iter().any(|para| {
para.controls.iter().any(|ctrl| match ctrl {
Control::Shape(shape) => shape.common().text_wrap == TextWrap::BehindText,
Control::Picture(pic) => pic.common.text_wrap == TextWrap::BehindText,
_ => false,
})
}) {
return Background::Unknown;
}
if def.hide_fill {
return Background::Known {
color: PAPER_WHITE,
source: BackgroundSource::Page,
};
}
fill_background(
self,
def.page_border_fill.border_fill_id,
BackgroundSource::Page,
)
.unwrap_or(Background::Known {
color: PAPER_WHITE,
source: BackgroundSource::Page,
})
}
fn image_bearing_pages(&self, pages_of: &HashMap<(usize, usize), Vec<u32>>) -> HashSet<u32> {
fn paints_over_text(ctrl: &Control) -> bool {
match ctrl {
Control::Picture(_) => true,
Control::Shape(shape) => match shape.as_ref() {
ShapeObject::Picture(_)
| ShapeObject::Chart(_)
| ShapeObject::Ole(_)
| ShapeObject::Group(_) => true,
other => drawing_of(other).is_some_and(|d| d.fill.fill_type != FillType::None),
},
_ => false,
}
}
fn hosts_graphic(para: &Paragraph, depth: usize) -> bool {
if depth >= MAX_NEST_DEPTH {
return false;
}
para.controls.iter().any(|ctrl| {
if paints_over_text(ctrl) {
return true;
}
match ctrl {
Control::Table(table) => table
.cells
.iter()
.any(|c| c.paragraphs.iter().any(|p| hosts_graphic(p, depth + 1))),
Control::Shape(shape) => drawing_of(shape)
.and_then(|d| d.text_box.as_ref())
.is_some_and(|tb| {
tb.paragraphs.iter().any(|p| hosts_graphic(p, depth + 1))
}),
_ => false,
}
})
}
let mut pages = HashSet::new();
for (sec_idx, section) in self.document.sections.iter().enumerate() {
for (para_idx, para) in section.paragraphs.iter().enumerate() {
if !hosts_graphic(para, 0) {
continue;
}
for page in pages_of
.get(&(sec_idx, para_idx))
.into_iter()
.flatten()
.copied()
{
pages.insert(page);
pages.insert(page + 1);
}
}
}
pages
}
fn hidden_text_paragraph_pages(&self) -> HashMap<(usize, usize), Vec<u32>> {
let mut index: HashMap<(usize, usize), Vec<u32>> = HashMap::new();
let mut global_offset = 0u32;
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for (local_i, page) in pr.pages.iter().enumerate() {
let global_page = global_offset + local_i as u32;
for col in &page.column_contents {
for item in &col.items {
let para_index = match item {
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => Some(*para_index),
_ => None,
};
if let Some(p) = para_index {
let slot = index.entry((sec_idx, p)).or_default();
if !slot.contains(&global_page) {
slot.push(global_page);
}
}
}
}
}
global_offset += pr.pages.len() as u32;
}
index
}
fn hidden_text_page_index(&self) -> HashMap<(usize, usize), u32> {
let mut index: HashMap<(usize, usize), u32> = HashMap::new();
let mut global_offset = 0u32;
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for (local_i, page) in pr.pages.iter().enumerate() {
let global_page = global_offset + local_i as u32;
for col in &page.column_contents {
for item in &col.items {
let para_index = match item {
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => Some(*para_index),
_ => None,
};
if let Some(p) = para_index {
index.entry((sec_idx, p)).or_insert(global_page);
}
}
}
}
global_offset += pr.pages.len() as u32;
}
index
}
fn off_page_paragraphs(&self) -> HashMap<(usize, usize), (u32, BBox, PageSize)> {
let mut found: HashMap<(usize, usize), (u32, BBox, PageSize)> = HashMap::new();
for page in 0..self.page_count() {
let Ok(tree) = self.build_page_render_tree(page) else {
continue;
};
let size = PageSize {
w: tree.root.bbox.width,
h: tree.root.bbox.height,
};
if size.w <= 0.0 || size.h <= 0.0 {
continue;
}
let mut stack: Vec<&RenderNode> = vec![&tree.root];
while let Some(node) = stack.pop() {
if !node.visible || node.editor_only {
continue;
}
stack.extend(node.children.iter());
let RenderNodeType::TextRun(run) = &node.node_type else {
continue;
};
if run.cell_context.is_some() || !run.text.chars().any(is_content) {
continue;
}
let (Some(sec), Some(para)) = (run.section_index, run.para_index) else {
continue;
};
let b = &node.bbox;
let outside =
b.x + b.width <= 0.0 || b.y + b.height <= 0.0 || b.x >= size.w || b.y >= size.h;
if !outside {
continue;
}
found.entry((sec, para)).or_insert((
page,
BBox {
x: b.x,
y: b.y,
w: b.width,
h: b.height,
},
size,
));
}
}
found
}
pub fn detect_hidden_text(&self, opts: &HiddenTextOptions) -> HiddenTextReport {
let page_index = self.hidden_text_page_index();
let off_page = if opts.include_off_page {
self.off_page_paragraphs()
} else {
HashMap::new()
};
let image_pages = self.image_bearing_pages(&self.hidden_text_paragraph_pages());
let mut out: Vec<HiddenTextFinding> = Vec::new();
for (sec_idx, section) in self.document.sections.iter().enumerate() {
let section_bg = self.page_background(sec_idx);
for (para_idx, para) in section.paragraphs.iter().enumerate() {
let page = page_index.get(&(sec_idx, para_idx)).copied();
let page_bg = match page {
Some(p) if !image_pages.contains(&p) => section_bg,
_ => Background::Unknown,
};
if let Some((off_page_num, bbox, size)) = off_page.get(&(sec_idx, para_idx)) {
let (excerpt, count) = excerpt_of(¶.text, opts.excerpt_limit);
if count > 0 {
out.push(HiddenTextFinding {
kind: HiddenKind::OffPage,
section: sec_idx,
paragraph: para_idx,
page: Some(*off_page_num),
cell: None,
textbox: None,
excerpt,
char_count: count,
detail: HiddenDetail {
bbox: Some(*bbox),
page_size: Some(*size),
..Default::default()
},
});
continue;
}
}
self.scan_paragraph(
sec_idx, para_idx, page, para, page_bg, None, None, opts, 0, &mut out,
);
}
}
let hidden_char_count = out.iter().map(|f| f.char_count).sum();
HiddenTextReport {
clean: out.is_empty(),
hidden_text: out,
hidden_char_count,
}
}
#[allow(clippy::too_many_arguments)]
fn scan_paragraph(
&self,
sec_idx: usize,
body_para_idx: usize,
page: Option<u32>,
para: &Paragraph,
container: Background,
cell: Option<CellRef>,
textbox: Option<TextBoxRef>,
opts: &HiddenTextOptions,
depth: usize,
out: &mut Vec<HiddenTextFinding>,
) {
let para_bg = self
.document
.doc_info
.para_shapes
.get(para.para_shape_id as usize)
.and_then(|ps| fill_background(self, ps.border_fill_id, BackgroundSource::Paragraph))
.unwrap_or(container);
for (verdict, text) in self.paragraph_runs(para, para_bg, opts.threshold_pt) {
let (excerpt, count) = excerpt_of(&text, opts.excerpt_limit);
if count == 0 {
continue;
}
out.push(HiddenTextFinding {
kind: verdict.kind(),
section: sec_idx,
paragraph: body_para_idx,
page,
cell: cell.clone(),
textbox: textbox.clone(),
excerpt,
char_count: count,
detail: detail_of(&verdict, opts.threshold_pt),
});
}
if depth >= MAX_NEST_DEPTH {
return;
}
for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
match ctrl {
Control::Table(table) => {
let table_bg =
fill_background(self, table.border_fill_id, BackgroundSource::TableCell);
for (cell_idx, table_cell) in table.cells.iter().enumerate() {
let zone_bg = table
.zones
.iter()
.filter(|z| {
(z.start_row..=z.end_row).contains(&table_cell.row)
&& (z.start_col..=z.end_col).contains(&table_cell.col)
})
.filter_map(|z| {
fill_background(self, z.border_fill_id, BackgroundSource::TableCell)
})
.next_back();
let cell_bg = fill_background(
self,
table_cell.border_fill_id,
BackgroundSource::TableCell,
)
.or(zone_bg)
.or(table_bg)
.unwrap_or(para_bg);
for (cp_idx, cp) in table_cell.paragraphs.iter().enumerate() {
self.scan_paragraph(
sec_idx,
body_para_idx,
page,
cp,
cell_bg,
Some(CellRef {
control: ctrl_idx,
cell: cell_idx,
paragraph: cp_idx,
}),
textbox.clone(),
opts,
depth + 1,
out,
);
}
}
}
Control::Shape(shape) => {
let Some(drawing) = drawing_of(shape) else {
continue;
};
let Some(tb) = drawing.text_box.as_ref() else {
continue;
};
let tb_bg = shape_background(drawing);
for (tp_idx, tp) in tb.paragraphs.iter().enumerate() {
self.scan_paragraph(
sec_idx,
body_para_idx,
page,
tp,
tb_bg,
cell.clone(),
Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
opts,
depth + 1,
out,
);
}
}
_ => {}
}
}
}
fn paragraph_runs(
&self,
para: &Paragraph,
container: Background,
threshold_pt: f64,
) -> Vec<(Verdict, String)> {
let chars: Vec<char> = para.text.chars().collect();
if chars.is_empty() || para.char_shapes.is_empty() {
return Vec::new();
}
let use_stored = para.char_offsets.len() == chars.len();
let mut runs: Vec<(Verdict, String)> = Vec::new();
let mut current: Option<(Verdict, String)> = None;
let mut utf16_pos: u32 = 0;
for (i, ch) in chars.iter().enumerate() {
let offset = if use_stored {
para.char_offsets[i]
} else {
utf16_pos
};
utf16_pos += ch.len_utf16() as u32;
let verdict = self
.char_shape_at(para, offset)
.and_then(|shape| classify_char(shape, container, threshold_pt));
match verdict {
Some(v) => match current.as_mut() {
Some((cur, buf)) if *cur == v => buf.push(*ch),
_ => {
if let Some(done) = current.take() {
runs.push(done);
}
current = Some((v, ch.to_string()));
}
},
None => {
if let Some(done) = current.take() {
runs.push(done);
}
}
}
}
if let Some(done) = current.take() {
runs.push(done);
}
runs
}
fn char_shape_at(&self, para: &Paragraph, utf16_offset: u32) -> Option<&CharShape> {
let mut chosen: Option<u32> = None;
for cs in ¶.char_shapes {
if cs.start_pos <= utf16_offset {
chosen = Some(cs.char_shape_id);
} else {
break;
}
}
let id = chosen?;
self.document.doc_info.char_shapes.get(id as usize)
}
}
fn detail_of(verdict: &Verdict, threshold_pt: f64) -> HiddenDetail {
match verdict {
Verdict::ZeroSize { effective_pt } => HiddenDetail {
effective_pt: Some(*effective_pt),
..Default::default()
},
Verdict::SameAsBackground {
text_color,
background,
source,
} => HiddenDetail {
text_color: Some(hex(*text_color)),
shade_color: matches!(source, BackgroundSource::CharShade).then(|| hex(*background)),
background_color: Some(hex(*background)),
background_source: Some(*source),
..Default::default()
},
Verdict::NearInvisible { effective_pt } => HiddenDetail {
effective_pt: Some(*effective_pt),
threshold_pt: Some(threshold_pt),
..Default::default()
},
}
}
fn excerpt_of(text: &str, limit: usize) -> (String, usize) {
if !text.chars().any(is_content) {
return (String::new(), 0);
}
let kept: Vec<char> = text.chars().filter(|c| is_reportable(*c)).collect();
let count = kept.len();
if count <= limit {
return (kept.into_iter().collect(), count);
}
let mut excerpt: String = kept.into_iter().take(limit).collect();
excerpt.push('…');
(excerpt, count)
}
#[cfg(test)]
mod tests {
use super::*;
const NO_SHADE: ColorRef = 0x00FF_FFFF;
fn shape(base_size: i32, text_color: ColorRef, shade_color: ColorRef) -> CharShape {
CharShape {
base_size,
text_color,
shade_color,
relative_sizes: [100; 7],
..Default::default()
}
}
const PAGE_WHITE: Background = Background::Known {
color: 0x00FF_FFFF,
source: BackgroundSource::Page,
};
#[test]
fn white_text_on_white_page_is_caught() {
let cs = shape(1000, 0x00FF_FFFF, NO_SHADE);
let v = classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT);
assert!(
matches!(v, Some(Verdict::SameAsBackground { source, .. }) if source == BackgroundSource::Page),
"{v:?}"
);
}
#[test]
fn black_text_on_white_page_is_clean() {
let cs = shape(1000, 0x0000_0000, NO_SHADE);
assert_eq!(classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT), None);
}
#[test]
fn black_shade_sentinel_is_not_a_black_background() {
let cs = shape(1000, 0x0000_0000, 0x0000_0000);
assert_eq!(char_shade(cs.shade_color), None);
assert_eq!(classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT), None);
}
#[test]
fn white_shade_sentinel_is_not_a_white_background() {
let cs = shape(1000, 0x00FF_FFFF, NO_SHADE);
assert_eq!(char_shade(cs.shade_color), None);
let v = classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT);
assert!(
matches!(v, Some(Verdict::SameAsBackground { source, .. }) if source == BackgroundSource::Page),
"{v:?}"
);
assert_eq!(
classify_char(&cs, Background::Unknown, DEFAULT_THRESHOLD_PT),
None
);
}
#[test]
fn text_equal_to_char_shade_is_caught_regardless_of_page() {
let cs = shape(1000, 0x0000_FFFF, 0x0000_FFFF);
let v = classify_char(&cs, Background::Unknown, DEFAULT_THRESHOLD_PT);
assert!(
matches!(v, Some(Verdict::SameAsBackground { source, .. }) if source == BackgroundSource::CharShade),
"{v:?}"
);
}
#[test]
fn white_text_on_unknown_background_is_not_judged() {
let cs = shape(1000, 0x00FF_FFFF, NO_SHADE);
assert_eq!(
classify_char(&cs, Background::Unknown, DEFAULT_THRESHOLD_PT),
None
);
}
#[test]
fn white_text_on_dark_cell_is_visible() {
let cs = shape(1000, 0x00FF_FFFF, NO_SHADE);
let dark = Background::Known {
color: 0x0000_0000,
source: BackgroundSource::TableCell,
};
assert_eq!(classify_char(&cs, dark, DEFAULT_THRESHOLD_PT), None);
}
#[test]
fn auto_color_is_never_judged_same_as_background() {
let cs = shape(1000, 0xFFFF_FFFF, NO_SHADE);
assert_eq!(classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT), None);
}
#[test]
fn tiny_and_zero_sizes_are_separated() {
let tiny = shape(50, 0x0000_0000, NO_SHADE); assert!(matches!(
classify_char(&tiny, PAGE_WHITE, DEFAULT_THRESHOLD_PT),
Some(Verdict::NearInvisible { .. })
));
let zero = shape(0, 0x0000_0000, NO_SHADE);
assert!(matches!(
classify_char(&zero, PAGE_WHITE, DEFAULT_THRESHOLD_PT),
Some(Verdict::ZeroSize { .. })
));
}
#[test]
fn effective_size_ignores_relative_sizes_like_the_renderer_does() {
let mut cs = shape(1000, 0x0000_0000, NO_SHADE);
cs.relative_sizes = [10; 7]; assert!((effective_pt(&cs) - 10.0).abs() < 1e-9);
assert_eq!(classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT), None);
assert_eq!(classify_char(&cs, PAGE_WHITE, 2.0), None);
}
#[test]
fn default_relative_sizes_can_never_cause_a_zero_size_misjudgment() {
let mut cs = shape(1000, 0x0000_0000, NO_SHADE);
cs.relative_sizes = [0; 7];
assert!((effective_pt(&cs) - 10.0).abs() < 1e-9);
assert_eq!(classify_char(&cs, PAGE_WHITE, DEFAULT_THRESHOLD_PT), None);
}
#[test]
fn excerpt_is_capped_and_reports_true_length() {
let long = "무".repeat(500);
let (excerpt, count) = excerpt_of(&long, DEFAULT_EXCERPT_LIMIT);
assert_eq!(count, 500);
assert_eq!(excerpt.chars().count(), DEFAULT_EXCERPT_LIMIT + 1);
assert!(excerpt.ends_with('…'));
}
#[test]
fn whitespace_only_run_is_dropped() {
assert_eq!(excerpt_of(" \t ", DEFAULT_EXCERPT_LIMIT).1, 0);
assert_eq!(excerpt_of("\u{0002}\u{0003}", DEFAULT_EXCERPT_LIMIT).1, 0);
}
#[test]
fn control_chars_are_excluded_from_excerpt() {
let (excerpt, count) = excerpt_of("가\u{0003}나", DEFAULT_EXCERPT_LIMIT);
assert_eq!(excerpt, "가나");
assert_eq!(count, 2);
}
#[test]
fn hex_follows_bgr_layout() {
assert_eq!(hex(0x0000_00FF), "#FF0000");
assert_eq!(hex(0x00FF_0000), "#0000FF");
assert_eq!(hex(0x00FF_FFFF), "#FFFFFF");
}
}