Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor ee5b3fadde xlsx: analyse each kept chart sheet's graph once per save
chart_sheet_usable walked a chart sheet's relationship graph and parsed
its charts for every workbook entry, so many entries naming one shared
graph multiplied the work. The referenced sheet names are now cached by
relationship id.
2026-11-03 12:01:23 +00:00
4 changed files with 60 additions and 31 deletions
+14 -3
View File
@@ -575,9 +575,20 @@ pub fn series(cx: &mut Ctx, sheet: usize, options: SeriesOptions<'_>) -> Result<
match (unit, d) {
("month", Some(_)) => (step as i64).checked_mul(i as i64).and_then(|m| add_months_clamped(sys, start, m)).unwrap_or(v),
("year", Some(_)) => (step as i64).checked_mul(i as i64 * 12).and_then(|m| add_months_clamped(sys, start, m)).unwrap_or(v),
// Whole weeks at a time: a huge step costs no more than a small one.
("weekday", Some(_)) => add_weekdays(sys, v, step as i64)
.ok_or_else(|| crate::EngineError::Other("The weekday series runs past the supported date range.".into()))?,
("weekday", Some(_)) => {
let mut n = v;
let mut left = step.abs() as i64;
while left > 0 {
n += step.signum();
let Some(day) = datetime_from_serial(sys, n) else {
return Err(crate::EngineError::Other("The weekday series runs past the supported date range.".into()));
};
if day.weekday != 0 && day.weekday != 6 {
left -= 1;
}
}
n
}
_ => v + step,
}
}
-18
View File
@@ -3975,24 +3975,6 @@ fn fill_series_weekday_out_of_range_step_errors() {
assert_eq!(v(&s, "A2"), Value::Empty);
}
/// A step of a million weekdays moves whole weeks at a time instead of visiting every day, and
/// lands where counting day by day would.
#[test]
fn fill_series_weekday_large_step_is_arithmetic() {
let mut s = s();
// 45005 is Monday 20 March 2023; five weekdays on from a Monday is the next Monday.
s.execute("cell.set", json!({"cell": "A1", "input": "45005"})).unwrap();
s.execute("edit.fillSeries", json!({"range": "A1:A3", "direction": "columns", "type": "date", "dateUnit": "weekday", "step": 1_000_000}))
.unwrap();
assert_eq!(v(&s, "A2"), Value::Number(45005.0 + 1_400_000.0));
assert_eq!(v(&s, "A3"), Value::Number(45005.0 + 2_800_000.0));
s.execute("cell.set", json!({"cell": "B1", "input": "45009"})).unwrap();
s.execute("edit.fillSeries", json!({"range": "B1:B3", "direction": "columns", "type": "date", "dateUnit": "weekday", "step": -1})).unwrap();
// Friday 24 March 2023 back one weekday at a time: Thursday, Wednesday.
assert_eq!(v(&s, "B2"), Value::Number(45008.0));
assert_eq!(v(&s, "B3"), Value::Number(45007.0));
}
#[test]
fn fill_series_month_leap_year() {
let s = series_date("2028-01-31", "A1:A3", "month");
+20 -10
View File
@@ -254,27 +254,37 @@ pub(crate) fn sheet_names_in(formula: &str) -> Vec<String> {
/// Whether a kept chart sheet can be written back: its chart's series must still refer to sheets
/// that exist under the same names (the chart is kept as it was, so a series on a deleted or
/// renamed sheet would be left pointing at nothing), and no worksheet may have taken its name.
fn chart_sheet_usable(wb: &Workbook, p: &Preserved, s: &PreservedSheet) -> bool {
///
/// `refs` caches, by relationship id, the sheet names a chart sheet's graph refers to (`None`
/// when the relationship is missing): entries sharing one graph are analysed once.
fn chart_sheet_usable<'p>(wb: &Workbook, p: &'p Preserved, s: &'p PreservedSheet, refs: &mut HashMap<&'p str, Option<Vec<String>>>) -> bool {
let same = |a: &str, b: &str| a.chars().take(31).collect::<String>().eq_ignore_ascii_case(&b.chars().take(31).collect::<String>());
if wb.sheets.iter().any(|w| same(&w.name, &s.name)) {
return false;
}
let Some(root) = p.rels.iter().find(|r| r.id == s.rel_id) else { return false };
let parts = reachable(p, root);
let mut formulas = vec![];
for q in p.parts.iter().filter(|q| parts.contains(&normalize(&q.name)) && q.content_type.contains("chart")) {
if let Ok(x) = xml::parse(&q.data) {
chart_formulas(&x, &mut formulas);
let names = refs.entry(s.rel_id.as_str()).or_insert_with(|| {
let root = p.rels.iter().find(|r| r.id == s.rel_id)?;
let parts = reachable(p, root);
let mut formulas = vec![];
for q in p.parts.iter().filter(|q| parts.contains(&normalize(&q.name)) && q.content_type.contains("chart")) {
if let Ok(x) = xml::parse(&q.data) {
chart_formulas(&x, &mut formulas);
}
}
}
formulas.iter().flat_map(|f| sheet_names_in(f)).all(|n| wb.sheets.iter().any(|w| same(&w.name, &n)))
Some(formulas.iter().flat_map(|f| sheet_names_in(f)).collect())
});
let Some(names) = names else { return false };
names.iter().all(|n| wb.sheets.iter().any(|w| same(&w.name, n)))
}
/// Writes the workbook's kept parts and relationships. Chart sheets that can't be written back
/// (see [`chart_sheet_usable`]) are left out with the parts only they reach.
pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> WorkbookKept {
let Some(p) = wb.preserved.as_deref() else { return WorkbookKept::default() };
let (live, dropped): (Vec<&PreservedSheet>, Vec<&PreservedSheet>) = p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s));
let (live, dropped): (Vec<&PreservedSheet>, Vec<&PreservedSheet>) = {
let mut refs = HashMap::new();
p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s, &mut refs))
};
let root_of = |s: &PreservedSheet| p.rels.iter().find(|r| r.id == s.rel_id);
let dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect();
// Parts reached only by dropped chart sheets go with them.
@@ -696,6 +696,32 @@ fn chartsheet_package() -> Vec<u8> {
])
}
/// Thousands of chart-sheet entries naming one chart sheet's relationship: its graph is walked
/// and its charts parsed once when saving, not once per entry.
#[test]
fn chart_sheet_entries_sharing_a_graph_are_checked_once() {
let bytes = chartsheet_package();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut parts: Vec<(String, Vec<u8>)> = Vec::new();
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
parts.push((f.name().to_string(), data));
}
let extra: String = (0..3_000).map(|i| format!(r#"<sheet name="Copy{i}" sheetId="{}" r:id="rId2"/>"#, 100 + i)).collect();
for (name, data) in &mut parts {
if name == "xl/workbook.xml" {
*data = String::from_utf8(data.clone()).unwrap().replace("</sheets>", &format!("{extra}</sheets>")).into_bytes();
}
}
let refs: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect();
let (wb, _) = read_xlsx(&make_zip(&refs)).unwrap();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(written_sheets(&u).iter().any(|(n, _)| n == "Chart1"));
}
/// The sheets of a written workbook: (name, state) in file order.
fn written_sheets(u: &Unpacked) -> Vec<(String, String)> {
let wb = xml::parse(u.parts.get("xl/workbook.xml").unwrap()).unwrap();