mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-03 08:51:30 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89cf961a2f |
+65
-4
@@ -1,7 +1,7 @@
|
||||
//! Conditional formatting evaluation: what extra style, data bar, colour scale or icon a cell
|
||||
//! gets.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value, compare};
|
||||
use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds};
|
||||
@@ -70,15 +70,31 @@ thread_local! {
|
||||
static SCANNED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Most cells one rule's statistics visit, across all of its ranges together: a rule repeating
|
||||
/// the same range many times must not multiply the scan.
|
||||
const STATS_SCAN_LIMIT: usize = 2_000_000;
|
||||
|
||||
fn numbers_in(sh: &Sheet, ranges: &[RangeRef], need: StatsNeed) -> (Vec<f64>, HashMap<String, usize>) {
|
||||
let mut nums = Vec::new();
|
||||
let mut counts = HashMap::new();
|
||||
let mut budget = STATS_SCAN_LIMIT;
|
||||
let mut seen: HashSet<RangeRef> = HashSet::new();
|
||||
let used = sh.used_range();
|
||||
for r in ranges {
|
||||
let r = match sh.used_range().and_then(|u| r.intersection(&u)) {
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
let r = match used.and_then(|u| r.intersection(&u)) {
|
||||
Some(x) => x,
|
||||
None => continue,
|
||||
};
|
||||
for c in r.iter().take(2_000_000) {
|
||||
// The same range listed twice counts its cells once.
|
||||
if !seen.insert(r) {
|
||||
continue;
|
||||
}
|
||||
let cells = r.iter().take(budget);
|
||||
for c in cells {
|
||||
budget -= 1;
|
||||
#[cfg(test)]
|
||||
SCANNED.with(|n| n.set(n.get() + 1));
|
||||
let v = sh.value(c);
|
||||
@@ -278,7 +294,8 @@ impl CfCache {
|
||||
_ => None,
|
||||
},
|
||||
CfRule::ColorScale { stops } => {
|
||||
if let Some(n) = v.as_f64() {
|
||||
// Only two- and three-colour scales paint: evaluate no thresholds for others.
|
||||
if let Some(n) = v.as_f64().filter(|_| matches!(stops.len(), 2 | 3)) {
|
||||
let pts: Vec<(f64, [u8; 3])> = stops
|
||||
.iter()
|
||||
.map(|(k, col)| (threshold(wb, sheet, c, st, k), col.resolve(&wb.theme).unwrap_or([255, 255, 255])))
|
||||
@@ -560,6 +577,50 @@ mod tests {
|
||||
assert_eq!(SCANNED.with(|n| n.get()), 10_000);
|
||||
}
|
||||
|
||||
/// A rule listing the same range many times scans it once, and never more than the shared
|
||||
/// limit however many ranges it holds.
|
||||
#[test]
|
||||
fn repeated_ranges_share_one_scan_budget() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "XFD1048576", "values": [[4]]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.sheet(0).unwrap();
|
||||
let dense = RangeRef::parse("A1:XFD1048576").unwrap();
|
||||
let small = RangeRef::parse("A1:A3").unwrap();
|
||||
SCANNED.with(|n| n.set(0));
|
||||
let st = RuleStats::build(sh, &vec![small; 1000], StatsNeed::Numbers);
|
||||
assert_eq!(st.sorted, vec![1.0, 2.0, 3.0]);
|
||||
assert_eq!(SCANNED.with(|n| n.get()), 3);
|
||||
let shifted: Vec<RangeRef> = (0..50).map(|i| RangeRef::new(CellRef::new(i, 0), dense.end)).collect();
|
||||
SCANNED.with(|n| n.set(0));
|
||||
RuleStats::build(sh, &shifted, StatsNeed::Numbers);
|
||||
assert!(SCANNED.with(|n| n.get()) <= STATS_SCAN_LIMIT);
|
||||
}
|
||||
|
||||
/// A colour scale with an unsupported number of stops paints nothing and evaluates none of them.
|
||||
#[test]
|
||||
fn colour_scales_with_other_stop_counts_paint_nothing() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1], [5]]})).unwrap();
|
||||
let mut wb: Workbook = (*s.doc().unwrap().wb).clone();
|
||||
let stop = (CfValueKind::Formula("=1".into()), Color::default());
|
||||
let rule = |n: usize| CondFormat {
|
||||
ranges: vec![RangeRef::parse("A1:A2").unwrap()],
|
||||
rule: CfRule::ColorScale { stops: vec![stop.clone(); n] },
|
||||
priority: 1,
|
||||
stop_if_true: false,
|
||||
};
|
||||
wb.sheet_mut(0).unwrap().cond_formats.push(rule(4));
|
||||
let mut cache = CfCache::new();
|
||||
assert_eq!(cache.look(&wb, 0, CellRef::parse("A1").unwrap()).and_then(|l| l.scale_fill), None);
|
||||
wb.sheet_mut(0).unwrap().cond_formats = vec![rule(2)];
|
||||
let mut cache = CfCache::new();
|
||||
assert!(cache.look(&wb, 0, CellRef::parse("A1").unwrap()).and_then(|l| l.scale_fill).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_value_operator_names() {
|
||||
let mut s = crate::Session::new();
|
||||
|
||||
@@ -14,13 +14,8 @@ fn matches(hay: &str, what: &str, case: bool, whole: bool) -> bool {
|
||||
}
|
||||
|
||||
/// `*`/`?` wildcard match with `~` escapes.
|
||||
///
|
||||
/// The pattern runs as a bit-parallel automaton over the text: one pass, each character costing
|
||||
/// one step per 64 pattern positions. Backtracking to the last `*` after a mismatch rescans the
|
||||
/// text and costs text × pattern comparisons on a long, repetitive cell, for every cell a
|
||||
/// filter or Find visits.
|
||||
pub(crate) fn wildcard(text: &str, pat: &str) -> bool {
|
||||
// The pattern as (character, escaped) items, runs of `*` folded into one.
|
||||
let t: Vec<char> = text.chars().collect();
|
||||
let mut p: Vec<(char, bool)> = Vec::new();
|
||||
let mut it = pat.chars();
|
||||
while let Some(c) = it.next() {
|
||||
@@ -28,56 +23,32 @@ pub(crate) fn wildcard(text: &str, pat: &str) -> bool {
|
||||
if let Some(n) = it.next() {
|
||||
p.push((n, true));
|
||||
}
|
||||
} else if c != '*' || p.last() != Some(&('*', false)) {
|
||||
} else {
|
||||
p.push((c, false));
|
||||
}
|
||||
}
|
||||
let words = (p.len() + 1).div_ceil(64);
|
||||
let bit = |set: &mut [u64], i: usize| set[i / 64] |= 1 << (i % 64);
|
||||
// Positions holding a `*`, a `?`, and each literal character.
|
||||
let mut stars = vec![0u64; words];
|
||||
let mut any = vec![0u64; words];
|
||||
let mut lits: std::collections::HashMap<char, Vec<u64>> = std::collections::HashMap::new();
|
||||
for (i, item) in p.iter().enumerate() {
|
||||
match item {
|
||||
('*', false) => bit(&mut stars, i),
|
||||
('?', false) => bit(&mut any, i),
|
||||
(c, _) => bit(lits.entry(*c).or_insert_with(|| vec![0u64; words]), i),
|
||||
}
|
||||
}
|
||||
// A set bit i: the text read so far matches the first i pattern items. A `*` matches nothing
|
||||
// as well, so a state at a `*` is also at the item after it.
|
||||
let close = |set: &mut Vec<u64>| {
|
||||
let mut carry = 0u64;
|
||||
for w in 0..words {
|
||||
let s = set[w] & stars[w];
|
||||
let next = (s << 1) | carry;
|
||||
carry = s >> 63;
|
||||
set[w] |= next;
|
||||
}
|
||||
};
|
||||
let mut state = vec![0u64; words];
|
||||
bit(&mut state, 0);
|
||||
close(&mut state);
|
||||
let mut next = vec![0u64; words];
|
||||
for ch in text.chars() {
|
||||
let lit = lits.get(&ch);
|
||||
let mut carry = 0u64;
|
||||
let mut alive = 0u64;
|
||||
for w in 0..words {
|
||||
// Items that read `ch` advance; a `*` reads it and stays.
|
||||
let m = state[w] & (any[w] | lit.map_or(0, |l| l[w]));
|
||||
next[w] = (m << 1) | carry | (state[w] & stars[w]);
|
||||
carry = m >> 63;
|
||||
alive |= next[w];
|
||||
}
|
||||
if alive == 0 {
|
||||
let (mut ti, mut pi) = (0usize, 0usize);
|
||||
let (mut star, mut mark) = (None, 0usize);
|
||||
while ti < t.len() {
|
||||
if pi < p.len() && (p[pi] == ('?', false) || (p[pi].0 == t[ti] && p[pi] != ('*', false))) {
|
||||
ti += 1;
|
||||
pi += 1;
|
||||
} else if pi < p.len() && p[pi] == ('*', false) {
|
||||
star = Some(pi);
|
||||
mark = ti;
|
||||
pi += 1;
|
||||
} else if let Some(sp) = star {
|
||||
pi = sp + 1;
|
||||
mark += 1;
|
||||
ti = mark;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
std::mem::swap(&mut state, &mut next);
|
||||
close(&mut state);
|
||||
}
|
||||
state[p.len() / 64] & (1 << (p.len() % 64)) != 0
|
||||
while pi < p.len() && p[pi] == ('*', false) {
|
||||
pi += 1;
|
||||
}
|
||||
pi == p.len()
|
||||
}
|
||||
|
||||
pub(super) fn find(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
@@ -302,79 +302,6 @@ fn wildcards() {
|
||||
assert!(wildcard("", "*"));
|
||||
}
|
||||
|
||||
/// The backtracking matcher `wildcard` replaced, as the reference for its results.
|
||||
fn wildcard_backtracking(text: &str, pat: &str) -> bool {
|
||||
let t: Vec<char> = text.chars().collect();
|
||||
let mut p: Vec<(char, bool)> = Vec::new();
|
||||
let mut it = pat.chars();
|
||||
while let Some(c) = it.next() {
|
||||
if c == '~' {
|
||||
if let Some(n) = it.next() {
|
||||
p.push((n, true));
|
||||
}
|
||||
} else {
|
||||
p.push((c, false));
|
||||
}
|
||||
}
|
||||
let (mut ti, mut pi) = (0usize, 0usize);
|
||||
let (mut star, mut mark) = (None, 0usize);
|
||||
while ti < t.len() {
|
||||
if pi < p.len() && (p[pi] == ('?', false) || (p[pi].0 == t[ti] && p[pi] != ('*', false))) {
|
||||
ti += 1;
|
||||
pi += 1;
|
||||
} else if pi < p.len() && p[pi] == ('*', false) {
|
||||
star = Some(pi);
|
||||
mark = ti;
|
||||
pi += 1;
|
||||
} else if let Some(sp) = star {
|
||||
pi = sp + 1;
|
||||
mark += 1;
|
||||
ti = mark;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while pi < p.len() && p[pi] == ('*', false) {
|
||||
pi += 1;
|
||||
}
|
||||
pi == p.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard_agrees_with_backtracking() {
|
||||
// Every text up to 5 characters over a small alphabet against every pattern up to 4 items.
|
||||
let alphabet = ['a', 'b', '*', '?', '~'];
|
||||
let all = |n: usize, chars: &[char]| -> Vec<String> {
|
||||
let mut out = vec![String::new()];
|
||||
let mut level = vec![String::new()];
|
||||
for _ in 0..n {
|
||||
level = level.iter().flat_map(|s| chars.iter().map(move |c| format!("{s}{c}"))).collect();
|
||||
out.extend(level.iter().cloned());
|
||||
}
|
||||
out
|
||||
};
|
||||
let texts = all(5, &['a', 'b', '*']);
|
||||
for pat in all(4, &alphabet) {
|
||||
for text in &texts {
|
||||
assert_eq!(wildcard(text, &pat), wildcard_backtracking(text, &pat), "{text:?} ~ {pat:?}");
|
||||
}
|
||||
}
|
||||
// Patterns longer than one 64-bit word.
|
||||
let long = format!("*{}*b?", "a".repeat(70));
|
||||
for text in [format!("x{}yb1", "a".repeat(70)), format!("{}b", "a".repeat(71)), "a".repeat(200)] {
|
||||
assert_eq!(wildcard(&text, &long), wildcard_backtracking(&text, &long), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard_on_long_repetitive_text_is_linear() {
|
||||
// The backtracking matcher compared about text × pattern characters here (10^8).
|
||||
let text = "a".repeat(20_000);
|
||||
let pat = format!("*{}b", "a".repeat(5_000));
|
||||
assert!(!wildcard(&text, &pat));
|
||||
assert!(wildcard(&format!("{text}b"), &pat));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsv() {
|
||||
assert_eq!(parse_tsv("a\tb\n1\t2\n"), vec![vec!["a", "b"], vec!["1", "2"]]);
|
||||
|
||||
Reference in New Issue
Block a user