From 8a78afffcd11305f34822a638804e6bb4582e651 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 21:59:50 -0600 Subject: [PATCH 1/7] fix(data): write large values, shapes and zip entries within the download limit A browser download is written into a sink that stops at its size limit, but some writers still built one large item whole first, a few times its size, before the sink could refuse it. KML names, descriptions and extended data, GPX names, and CSV and WKT-CSV cells are now written a piece at a time from the value itself, and counting what a file loses, and a dBase column, no longer copy a text value. A Shapefile shape whose record can't fit is refused from its vertex count, before its points are copied. A zip entry is deflated into the archive a piece at a time instead of into a buffer of its own. Output is unchanged. --- crates/data/src/capped.rs | 104 +++++++++++ crates/data/src/interop.rs | 219 ++++++++++++++++------- crates/data/src/io.rs | 228 +++++++++++++++++++++--- crates/data/src/value.rs | 18 ++ crates/data/src/zip.rs | 95 ++++++++-- crates/data/tests/large_value_memory.rs | 108 +++++++++++ 6 files changed, 671 insertions(+), 101 deletions(-) create mode 100644 crates/data/tests/large_value_memory.rs diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 98435d5368..0deef610ae 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -6,6 +6,15 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use crate::{DataError, Result}; +/// The most bytes of one value or zip entry a writer hands its output at once, so a capped one +/// refuses a large value without being offered it whole. +pub(crate) const PIECE: usize = 8 << 10; + +/// `bytes` written to `out`, [`PIECE`] at a time. +pub(crate) fn write_pieces(out: &mut (impl Write + ?Sized), bytes: &[u8]) -> std::io::Result<()> { + bytes.chunks(PIECE).try_for_each(|piece| out.write_all(piece)) +} + /// The most bytes the buffers a file is made in may hold in all (a Shapefile's parts share one). #[derive(Debug)] pub struct Limit { @@ -30,6 +39,21 @@ impl Limit { self.passed.load(Ordering::Relaxed) } + /// Whether there is a limit to pass: false for [`Limit::none`]. + pub(crate) fn bounded(&self) -> bool { + self.max != usize::MAX + } + + /// Refuses, and notes the limit passed, when files that come to `bytes` can't be held: for a + /// writer to ask before it builds a large piece of them that would then be refused. + pub(crate) fn fits(&self, bytes: usize) -> Result<()> { + if bytes <= self.max { + return Ok(()); + } + self.passed.store(true, Ordering::Relaxed); + self.whole(Ok(())) + } + /// An empty buffer counted against this limit. pub(crate) fn buffer(&self) -> Buffer<'_> { Buffer { file: Vec::new(), at: 0, limit: self, charged: 0 } @@ -320,6 +344,86 @@ mod tests { } } + impl Seek for Pieces<'_> { + fn seek(&mut self, to: SeekFrom) -> std::io::Result { + self.to.seek(to) + } + } + + /// One value or zip entry that alone passes the limit is handed over a piece at a time: KML + /// and GPX text, a CSV or WKT cell, guarded or not, and an entry deflated or stored. + #[test] + fn one_large_value_stops_at_the_limit_without_it_offered_whole() { + const MAX: usize = 40_000; + let long = "a long \"value\" & more, ".repeat(20_000); + let formula = format!("={long}"); + let at = crate::Coord::new(1.0, 2.0); + let layer = |geometry: Geometry, field: &str, value: &str| { + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new(field, FieldType::Text)]); + ds.push(Some(geometry), vec![Value::Text(value.to_string())]); + ds + }; + // Bytes with no pattern to deflate, which are stored as they are. + let mut state = 7u32; + let noise: Vec = std::iter::repeat_with(|| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .take(500_000) + .collect(); + // Deflated to well past a piece, yet smaller than they are. + let halves: Vec = noise.iter().map(|b| b & 0x0f).collect(); + type Make<'a> = Box) -> Result<()> + 'a>; + let zipped = |data: &[u8]| -> Make<'_> { + let entries = vec![("e".to_string(), data.to_vec())]; + Box::new(move |out| crate::zip::write_to(&entries, out).map_err(crate::DataError::Format)) + }; + let point = || Geometry::Point(at); + let mut cases: Vec<(&str, Make<'_>)> = Vec::new(); + for (name, field, value) in [("KML description", "description", &long), ("KML attribute", "note", &long)] { + let ds = layer(point(), field, value); + cases.push((name, Box::new(move |out| crate::interop::write_kml(&ds, None, out)))); + } + for (name, geometry) in [ + ("GPX waypoint name", point()), + ("GPX multipoint name", Geometry::MultiPoint(vec![at, at])), + ("GPX track name", Geometry::Line(vec![vec![at, at]])), + ] { + let ds = layer(geometry, "note", &long); + cases.push((name, Box::new(move |out| crate::interop::write_gpx(&ds, Some(0), out)))); + } + for (name, value) in [("WKT cell", &long), ("WKT guarded cell", &formula)] { + let ds = layer(point(), "note", value); + cases.push((name, Box::new(move |out| crate::interop::write_wkt_csv(&ds, out)))); + } + for (name, value) in [("CSV cell", &long), ("CSV guarded cell", &formula)] { + let ds = layer(point(), "note", value); + cases.push(( + name, + Box::new(move |out| { + let mut w = crate::io::CsvWriter::new(out, &ds.fields, ds.geometry_type, Crs::LonLat)?; + w.write(&ds.features)?; + w.finish().map(drop) + }), + )); + } + cases.push(("deflated entry", zipped(&halves))); + cases.push(("stored entry", zipped(&noise))); + let mut failed = Vec::new(); + for (name, make) in cases { + let limit = Limit::new(MAX); + let mut out = Pieces { to: limit.buffer(), largest: 0 }; + let made = make(&mut out); + let (largest, held) = (out.largest, out.to.file.capacity()); + if largest > PIECE || held > MAX { + failed.push(format!("{name}: a piece of {largest} bytes, {held} held")); + } + let e = limit.whole(made).unwrap_err().to_string(); + assert!(limit.passed() && e.contains("passes the 40000 bytes"), "{name}: {e}"); + } + assert!(failed.is_empty(), "{failed:#?}"); + } + /// A buffer dropped without being handed over, as a refused write or a writer's error leaves /// one, no longer counts against the limit, and a file handed over is released only once. #[test] diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 76802e85c7..8f2ce46cd1 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -1,17 +1,19 @@ //! Writers for exchange formats: KML, GPX and CSV with WKT geometry. Geometry text goes to the -//! output a coordinate at a time, so a large feature's is never held whole. +//! output a coordinate at a time and values a piece at a time, escaped as they go, so a large +//! feature's text is never held a second time. use std::io::Write; use rustgis_geom::Coord; +use crate::capped::write_pieces; use crate::{Dataset, Geometry}; -/// Text for XML, special characters escaped: kept exactly or refused, never cleaned without -/// reporting its loss. `place` says where in the file of `format` the text goes, for the refusal. +/// Refuses text XML can't hold: it is kept exactly or refused, never cleaned without reporting its +/// loss. `place` says where in the file of `format` the text goes, for the refusal. /// /// XML 1.0 Char production: https://www.w3.org/TR/xml/#charsets. -fn xml(text: &str, format: &str, place: impl FnOnce() -> String) -> crate::Result { +fn check_xml(text: &str, format: &str, place: impl FnOnce() -> String) -> crate::Result<()> { let mut invalid = text.chars().filter(|c| { !matches!(*c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}' @@ -25,14 +27,34 @@ fn xml(text: &str, format: &str, place: impl FnOnce() -> String) -> crate::Resul first as u32 ))); } - Ok(escaped_xml(text)) + Ok(()) } -fn escaped_xml(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\r', " ") +/// Text [`check_xml`] has passed, written with its special characters escaped. In an `attribute`, +/// where a reader turns tabs and line breaks into spaces, they are written as references too. +fn write_xml(out: &mut impl Write, text: &str, attribute: bool) -> std::io::Result<()> { + let bytes = text.as_bytes(); + // Where the run not yet written, with nothing to escape, starts. + let mut plain = 0; + for (i, b) in bytes.iter().enumerate() { + let reference: &[u8] = match b { + b'&' => b"&", + b'<' => b"<", + b'>' => b">", + b'"' => b""", + b'\r' => b" ", + b'\t' if attribute => b" ", + b'\n' if attribute => b" ", + _ => continue, + }; + write_pieces(out, bytes.get(plain..i).unwrap_or_default())?; + out.write_all(reference)?; + plain = i + 1; + } + write_pieces(out, bytes.get(plain..).unwrap_or_default()) } -/// Where in a layer's file a feature's text goes, for [`xml`]'s refusal. +/// Where in a layer's file a feature's text goes, for [`check_xml`]'s refusal. fn feature_place(layer: &str, feature: u64, what: &str) -> String { format!("{layer}, feature id {feature}, {what}") } @@ -112,49 +134,57 @@ fn text(out: Vec) -> crate::Result { /// [`to_kml`]'s document, written to `out` as it is made. pub(crate) fn write_kml(ds: &Dataset, name_field: Option, out: &mut impl Write) -> crate::Result<()> { - write!( - out, - "\n{}\n", - xml(&ds.name, "KML", || "layer name".to_string())? - )?; + check_xml(&ds.name, "KML", || "layer name".to_string())?; + out.write_all(b"\n")?; + write_xml(out, &ds.name, false)?; + out.write_all(b"\n")?; // KML's description is text. Other types and differently-cased columns stay in // ExtendedData, where the reader preserves their values and reports name collisions. let description = ds.fields.iter().position(|f| f.name == "description" && f.ty == crate::FieldType::Text); for (r, f) in ds.features.iter().enumerate() { crate::progress::step(1)?; let Some(g) = &f.geometry else { continue }; - let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string()); + let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| ds.value(r, fi).file_text()); let description = match description.map(|fi| ds.value(r, fi)) { - Some(crate::Value::Text(text)) => { - format!("{}", xml(text, "KML", || feature_place(&ds.name, f.id, "description"))?) - } - _ => String::new(), + Some(crate::Value::Text(text)) => Some(text), + _ => None, }; - let data: String = ds - .fields - .iter() - .zip(&f.attrs) - .filter(|(_, v)| !v.is_null()) - .map(|(fd, v)| { - let value = match v { - crate::Value::Text(text) if fd.name == "description" && fd.ty == crate::FieldType::Text => { - xml(text, "KML", || feature_place(&ds.name, f.id, "description"))? + let data = || ds.fields.iter().zip(&f.attrs).filter(|(_, v)| !v.is_null()); + // All the placemark's text is checked before any of it is written. + if let Some(text) = description { + check_xml(text, "KML", || feature_place(&ds.name, f.id, "description"))?; + } + for (fd, v) in data() { + // Only text can hold what XML can't. + if let crate::Value::Text(text) = v { + check_xml(text, "KML", || { + if fd.name == "description" && fd.ty == crate::FieldType::Text { + feature_place(&ds.name, f.id, "description") + } else { + feature_place(&ds.name, f.id, &format!("field '{}'", fd.name.escape_debug())) } - _ => xml(&v.to_file_text(), "KML", || feature_place(&ds.name, f.id, &format!("field '{}'", fd.name.escape_debug())))?, - }; - // In an attribute, where a reader turns tabs and line breaks into spaces unless - // they are written as references. - let name = xml(&fd.name, "KML", || format!("{}, field name '{}'", ds.name, fd.name.escape_debug()))? - .replace('\t', " ") - .replace('\n', " "); - Ok(format!("{value}")) - }) - .collect::>()?; - write!( - out, - "{}{description}{data}", - xml(&name, "KML", || feature_place(&ds.name, f.id, "name"))? - )?; + })?; + } + check_xml(&fd.name, "KML", || format!("{}, field name '{}'", ds.name, fd.name.escape_debug()))?; + } + check_xml(&name, "KML", || feature_place(&ds.name, f.id, "name"))?; + out.write_all(b"")?; + write_xml(out, &name, false)?; + out.write_all(b"")?; + if let Some(text) = description { + out.write_all(b"")?; + write_xml(out, text, false)?; + out.write_all(b"")?; + } + out.write_all(b"")?; + for (fd, v) in data() { + out.write_all(b"")?; + write_xml(out, &v.file_text(), false)?; + out.write_all(b"")?; + } + out.write_all(b"")?; write_kml_geometry(out, g)?; out.write_all(b"\n")?; } @@ -171,6 +201,20 @@ fn write_gpx_segment(out: &mut impl Write, pts: &[Coord]) -> std::io::Result<()> out.write_all(b"") } +/// A GPX waypoint named `name`, which [`check_xml`] has passed. +fn write_gpx_waypoint(out: &mut impl Write, c: &Coord, name: &str) -> std::io::Result<()> { + write!(out, "", c.y, c.x)?; + write_xml(out, name, false)?; + out.write_all(b"\n") +} + +/// The start of a GPX track named `name`, which [`check_xml`] has passed. +fn write_gpx_track_start(out: &mut impl Write, name: &str) -> std::io::Result<()> { + out.write_all(b"")?; + write_xml(out, name, false)?; + out.write_all(b"") +} + /// A GPX file: points become waypoints, lines tracks (polygon outlines too). /// A cancelled run ([`crate::progress`]) stops it with [`crate::DataError::Cancelled`]. pub fn to_gpx(ds: &Dataset, name_field: Option) -> crate::Result { @@ -185,7 +229,6 @@ pub(crate) fn write_gpx(ds: &Dataset, name_field: Option, out: &mut impl out.write_all( b"\n\n", )?; - let pt = |c: &Coord| format!("lat=\"{}\" lon=\"{}\"", c.y, c.x); for tracks in [false, true] { for (r, f) in ds.features.iter().enumerate() { // Each feature counts once, in the first pass. @@ -204,24 +247,24 @@ pub(crate) fn write_gpx(ds: &Dataset, name_field: Option, out: &mut impl if !written { continue; } - let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string()); - let name = xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?; + let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| ds.value(r, fi).file_text()); + check_xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?; match g { - Geometry::Point(c) if !tracks => writeln!(out, "{name}", pt(c))?, + Geometry::Point(c) if !tracks => write_gpx_waypoint(out, c, &name)?, Geometry::MultiPoint(v) if !tracks => { for c in v { - writeln!(out, "{name}", pt(c))?; + write_gpx_waypoint(out, c, &name)?; } } Geometry::Line(parts) if tracks => { - write!(out, "{name}")?; + write_gpx_track_start(out, &name)?; for p in parts { write_gpx_segment(out, p)?; } out.write_all(b"\n")?; } Geometry::Polygon(polys) if tracks => { - write!(out, "{name}")?; + write_gpx_track_start(out, &name)?; for ring in polys.iter().filter_map(|r| r.first()) { write_gpx_segment(out, ring)?; } @@ -606,10 +649,29 @@ impl WktParser { } } -/// A [`to_wkt_csv`] cell's text before quoting: text starting like a formula is prefixed with `'` -/// so spreadsheets show it rather than run it. -pub(crate) fn wkt_csv_text(s: &str) -> String { - if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { format!("'{s}") } else { s.to_string() } +/// What goes before a [`to_wkt_csv`] cell's text: `'` before text starting like a formula, so +/// spreadsheets show it rather than run it, else nothing. +pub(crate) fn wkt_csv_guard(s: &str) -> &'static str { + if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { "'" } else { "" } +} + +/// One CSV cell of `text`, `guard` before it: quoted when the text holds a comma, a quote or a +/// line break, its quotes doubled, as the `csv` crate writes a field of a record with others. +pub(crate) fn write_csv_cell(out: &mut (impl Write + ?Sized), guard: &str, text: &str) -> std::io::Result<()> { + let quote: &[u8] = if text.contains([',', '"', '\n', '\r']) { b"\"" } else { b"" }; + out.write_all(quote)?; + out.write_all(guard.as_bytes())?; + if quote.is_empty() { + write_pieces(out, text.as_bytes())?; + } else { + for (i, part) in text.split('"').enumerate() { + if i > 0 { + out.write_all(b"\"\"")?; + } + write_pieces(out, part.as_bytes())?; + } + } + out.write_all(quote) } /// CSV with a `wkt` geometry column and every attribute; cancellable between features. @@ -621,27 +683,28 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { /// [`to_wkt_csv`]'s text, written to `out` as it is made. pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result<()> { - let q = |s: &str| { - let s = wkt_csv_text(s); - if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } - }; + /// A comma, then `text` as a CSV cell with its formula guard. + fn cell(out: &mut impl Write, text: &str) -> std::io::Result<()> { + out.write_all(b",")?; + write_csv_cell(out, wkt_csv_guard(text), text) + } out.write_all(b"wkt")?; for f in &ds.fields { - write!(out, ",{}", q(&f.name))?; + cell(out, &f.name)?; } out.write_all(b"\n")?; for f in &ds.features { crate::progress::step(1)?; if let Some(g) = &f.geometry { - // As `q` would: WKT holds no quote or line break and starts like no formula, so its - // cell is quoted for a comma alone, with nothing in it to escape. + // As `write_csv_cell` would: WKT holds no quote or line break and starts like no + // formula, so its cell is quoted for a comma alone, with nothing in it to escape. let quote: &[u8] = if write_wkt(&mut NoComma, g).is_err() { b"\"" } else { b"" }; out.write_all(quote)?; write_wkt(out, g)?; out.write_all(quote)?; } for v in &f.attrs { - write!(out, ",{}", q(&v.to_file_text()))?; + cell(out, &v.file_text())?; } out.write_all(b"\n")?; } @@ -708,6 +771,40 @@ mod tests { assert!(c.contains("POINT (1 2),,0.1234567891\n") && c.contains(",B,0.000000001\n"), "{c}"); } + /// Values longer than a piece, with every character that is escaped, a quote or the formula + /// guard, are written whole in KML, GPX and a WKT cell. + #[test] + fn long_values_are_escaped_whole_in_kml_gpx_and_wkt_csv() { + let long = "é & \"q\"\r\n\t', ".repeat(2_000); + let formula = format!("={long}"); + let escaped = + |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\r', " "); + let quoted = |s: &str| format!("\"{}\"", s.replace('"', "\"\"")); + let odd = "a\tb\nc\"d"; + let fields = + vec![Field::new("name", FieldType::Text), Field::new("description", FieldType::Text), Field::new(odd, FieldType::Text)]; + let mut ds = Dataset::new("t & u", GeometryType::Point, fields); + let values = [&formula, &long, &long].map(|s| Value::Text(s.to_string())); + ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), values.to_vec()); + let (name, text) = (escaped(&formula), escaped(&long)); + let k = to_kml(&ds, Some(0)).unwrap(); + let field = escaped(odd).replace('\t', " ").replace('\n', " "); + let data = |field: &str, value: &str| format!("{value}"); + let placemark = format!( + "{name}{text}{}{}{}1,2\n", + data("name", &name), + data("description", &text), + data(&field, &text), + ); + assert!(k.contains("t & u\n") && k.contains(&placemark)); + let x = to_gpx(&ds, Some(0)).unwrap(); + assert!(x.contains(&format!("{name}\n\n"))); + let c = to_wkt_csv(&ds).unwrap(); + let guarded = quoted(&format!("'{formula}")); + let row = format!("POINT (1 2),{guarded},{},{}\n", quoted(&long), quoted(&long)); + assert_eq!(c, format!("wkt,name,description,{}\n{row}", quoted(odd))); + } + /// Each geometry shape's text in KML, GPX and a WKT cell, the empty and one-coordinate ones /// too: a cell is quoted only when its text holds a comma. #[test] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 3d840583c7..a4256bcb56 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1,5 +1,6 @@ //! Vector readers and writers: GeoJSON, CSV (with longitude/latitude columns) and Shapefile. +use std::borrow::Cow; use std::collections::BTreeMap; use std::path::Path; @@ -1136,7 +1137,7 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R /// A zip of `entries`, which were held to `limit` as they were made: they stay counted against it /// while the archive is made, and the archive is written within what they leave, so the two -/// together never pass it (besides one entry's compressed bytes at a time). +/// together never pass it. fn zipped(entries: &[(String, Vec)], limit: &Limit) -> Result> { let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum(); let _parts = limit.hold(parts)?; @@ -3595,9 +3596,13 @@ pub fn double_holds(v: &str) -> bool { let digits = if digits.is_empty() { "0" } else { digits }; return digits.len() <= 309 && v.parse::().is_ok_and(|x| x.is_finite() && format!("{:.0}", x.abs()) == digits); } - let want = digits(v); - v.parse::() - .is_ok_and(|x| x.is_finite() && (want.is_empty() || want.len() <= 767 && digits(&format!("{x:.*e}", want.len() - 1)) == want)) + // Parsed first, so the digits of text that is no number aren't copied. + v.parse::().is_ok_and(|x| { + x.is_finite() && { + let want = digits(v); + want.is_empty() || want.len() <= 767 && digits(&format!("{x:.*e}", want.len() - 1)) == want + } + }) } /// Types a dataset's Text columns from their values (see [`text_type`]), for readers whose @@ -3671,12 +3676,14 @@ fn csv_needs_guard(text: &str) -> bool { && double_holds(text)) } -/// A cell's file text, with an apostrophe when the spreadsheet guard applies. -fn csv_cell(v: &Value) -> String { - match v { - Value::Text(t) if csv_needs_guard(t) => format!("'{t}"), - other => other.to_file_text(), - } +/// What goes before a cell's file text, an apostrophe when the spreadsheet guard applies, and +/// that text. +fn csv_cell(v: &Value) -> (&'static str, Cow<'_, str>) { + let guard = match v { + Value::Text(t) if csv_needs_guard(t) => "'", + _ => "", + }; + (guard, v.file_text()) } /// The names of a point layer's longitude and latitude columns in CSV: the first of the names @@ -3735,8 +3742,12 @@ fn write_csv(ds: &Dataset, crs: Crs, out: &mut impl std::io::Write) -> Result<() /// Writes CSV a run of features at a time: a header of the fields, and for a point layer /// longitude and latitude columns before them. pub(crate) struct CsvWriter { - w: csv::Writer, + /// Absent only while a row is written past it ([`CsvWriter::write_past`]), or after that + /// failed. + w: Option>, point: bool, + /// The cells of each row: the header's. + columns: usize, } impl CsvWriter { @@ -3752,31 +3763,67 @@ impl CsvWriter { } head.extend(fields.iter().map(|f| f.name.clone())); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; - Ok(CsvWriter { w, point }) + Ok(CsvWriter { w: Some(w), point, columns: head.len() }) } /// Writes the next features, a row each. pub(crate) fn write(&mut self, features: &[crate::Feature]) -> Result<()> { for f in features { crate::progress::step(1)?; - let mut row = Vec::with_capacity(f.attrs.len() + 2); + let mut row: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(f.attrs.len() + 2); if self.point { let c = f.geometry.as_ref().and_then(|g| g.label_point()); - row.push(c.map(|c| c.x.to_string()).unwrap_or_default()); - row.push(c.map(|c| c.y.to_string()).unwrap_or_default()); + row.push(("", c.map(|c| c.x.to_string()).unwrap_or_default().into())); + row.push(("", c.map(|c| c.y.to_string()).unwrap_or_default().into())); } row.extend(f.attrs.iter().map(csv_cell)); - self.w.write_record(&row).map_err(|e| DataError::Format(e.to_string()))?; + if row.len() != self.columns { + return Err(DataError::Format(format!("CSV: a row of {} cells under {} columns", row.len(), self.columns))); + } + // The `csv` crate takes a cell whole, so a guarded one is first joined to its + // apostrophe: a row with a long one is written without it. + if row.iter().any(|(guard, text)| !guard.is_empty() && text.len() > crate::capped::PIECE) { + self.write_past(&row)?; + continue; + } + let w = self.w.as_mut().ok_or_else(csv_stopped)?; + for (guard, text) in &row { + let written = if guard.is_empty() { w.write_field(text.as_bytes()) } else { w.write_field(format!("{guard}{text}")) }; + written.map_err(|e| DataError::Format(e.to_string()))?; + } + // Ends the row. + w.write_record(None::<&[u8]>).map_err(|e| DataError::Format(e.to_string()))?; } Ok(()) } + /// Writes `row` straight to the output, a long cell a piece at a time, once the rows before + /// it are out of the `csv` writer. + fn write_past(&mut self, row: &[(&str, Cow<'_, str>)]) -> Result<()> { + let w = self.w.take().ok_or_else(csv_stopped)?; + let mut out = w.into_inner().map_err(|e| DataError::Format(e.to_string()))?; + for (i, (guard, text)) in row.iter().enumerate() { + if i > 0 { + out.write_all(b",")?; + } + crate::interop::write_csv_cell(&mut out, guard, text)?; + } + out.write_all(b"\n")?; + self.w = Some(csv::Writer::from_writer(out)); + Ok(()) + } + /// Flushes the rows and gives the writer back. pub(crate) fn finish(self) -> Result { - self.w.into_inner().map_err(|e| DataError::Format(e.to_string())) + self.w.ok_or_else(csv_stopped)?.into_inner().map_err(|e| DataError::Format(e.to_string())) } } +/// The error of a CSV writer used after a write of its failed. +fn csv_stopped() -> DataError { + DataError::Format("CSV: writing stopped at an earlier error".into()) +} + // --------------------------------------------------------------------------------------------- // Shapefile @@ -5264,7 +5311,7 @@ pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec 254 => loss.text += 1, + FieldType::Text | FieldType::DateTime if value.shown_text().len() > 254 => loss.text += 1, FieldType::Date if !value.asks_null() && dbf_date(value).is_none() => loss.empty += 1, FieldType::Integer | FieldType::Double => { let d = decimals.get(k).copied().unwrap_or(0); @@ -5748,14 +5795,17 @@ impl TextLosses { if let Some(column) = &mut loss.column && !column.is_text() { - let text = match ext { - "csv" => csv_cell(v), - "wkt" => crate::interop::wkt_csv_text(&v.to_file_text()), - _ => v.to_file_text(), + let (guard, cell) = if ext == "csv" { + csv_cell(v) + } else { + let cell = v.file_text(); + (if ext == "wkt" { crate::interop::wkt_csv_guard(&cell) } else { "" }, cell) }; + // Guarded text types its column as text, as its apostrophe alone does. + let text = if guard.is_empty() { cell.as_ref() } else { guard }; // CSV's `` reads as null, so it types a column no more than an empty cell. - if !(csv && Value::is_null_marker(&text)) { - column.add(&text); + if !(csv && Value::is_null_marker(text)) { + column.add(text); } } let Value::Text(s) = v else { continue }; @@ -6288,7 +6338,7 @@ fn new_column(ds: &Dataset, k: usize) -> Spec { FieldType::Date => Spec { ty: b'D', len: 8, decimals: 0 }, // A `.dbf` has no date-time field that other programs read, so they're ISO text. FieldType::Text | FieldType::DateTime => { - let longest = ds.features.iter().filter_map(|r| r.attrs.get(k)).map(|v| v.to_string().len()).max().unwrap_or(0); + let longest = ds.features.iter().filter_map(|r| r.attrs.get(k)).map(|v| v.shown_text().len()).max().unwrap_or(0); Spec { ty: b'C', len: u8::try_from(longest.clamp(1, 254)).unwrap_or(254), decimals: 0 } } } @@ -6415,8 +6465,8 @@ fn shapefile_parts_within( shapefile::dbase::Date::new(u32::try_from(d).ok()?, u32::try_from(m).ok()?, u32::try_from(y).ok()?).ok() })), FieldType::Text | FieldType::DateTime => FieldValue::Character((!v.is_null()).then(|| match style { - Some(style) => cut_encoded(&v.to_string(), 254, &style.encoding).to_string(), - None => cut(&v.to_string(), 254).to_string(), + Some(style) => cut_encoded(&v.shown_text(), 254, &style.encoding).to_string(), + None => cut(&v.shown_text(), 254).to_string(), })), }; rec.insert(n.clone(), value); @@ -6433,8 +6483,18 @@ fn shapefile_parts_within( let shapes = shapefile::ShapeWriter::with_shx(&mut shp, &mut shx); let mut w = shapefile::Writer::new(shapes, table.build_with_dest(&mut dbf)); let multi_points = ds.features.iter().any(|f| matches!(f.geometry, Some(Geometry::MultiPoint(_)))); + // What the `.shp` and `.shx` come to with each shape: their headers, then the records. + let mut shape_bytes = 2 * SHAPEFILE_HEADER; for f in &ds.features { crate::progress::step(1)?; + // A shape is copied to be written: one whose record can't fit is refused first. + if limit.bounded() + && let Some(g) = &f.geometry + && let Some(bytes) = shapefile_record_bytes(g, ds.geometry_type, multi_points) + { + shape_bytes = shape_bytes.saturating_add(bytes); + limit.fits(shape_bytes)?; + } let ok = match (&f.geometry, ds.geometry_type) { (Some(Geometry::Point(c)), GeometryType::Point) if !multi_points && finite(&c) => { w.write_shape_and_record(&pt(c), &record(f)).map_err(fmt)?; @@ -6514,6 +6574,51 @@ fn shapefile_parts_within( Ok((parts, left_out, widened)) } +/// The bytes of a `.shp` file's header, and of a `.shx` file's. +const SHAPEFILE_HEADER: usize = 100; + +/// The bytes `g`'s record adds to a `.shp` and its `.shx` in a layer of type `gt`, counted from +/// the vertices [`shapefile_parts_within`] keeps, without copying them; `None` for one it leaves +/// out. `multi_points` says the layer's points are written as multipoints. +fn shapefile_record_bytes(g: &Geometry, gt: GeometryType, multi_points: bool) -> Option { + if !shapefile_keeps(Some(g), gt) { + return None; + } + let finite = |c: &&Coord| c.x.is_finite() && c.y.is_finite(); + // A box, the part and point counts, where each part starts, and the points. + let parts = |parts: usize, points: usize| 32 + 8 + 4 * parts + 16 * points; + let content = match g { + Geometry::Point(_) if !multi_points => 16, + Geometry::Point(_) | Geometry::MultiPoint(_) => { + let mut points = 0usize; + g.for_each_coord(|c| points += usize::from(finite(&&c))); + // A box, the count and the points. + 32 + 4 + 16 * points + } + Geometry::Line(lines) => { + let (n, points) = + lines.iter().map(|p| p.iter().filter(finite).count()).filter(|n| *n >= 2).fold((0, 0), |(p, v), n| (p + 1, v + n)); + parts(n, points) + } + Geometry::Polygon(polys) => { + let (mut rings, mut points) = (0, 0); + for poly in polys.iter().filter(|p| p.first().is_some_and(|r| r.iter().filter(finite).count() >= 3)) { + for ring in poly { + let n = ring.iter().filter(finite).count(); + if n >= 3 { + rings += 1; + // A ring left open is closed with its first point. + points += n + usize::from(ring.iter().find(finite) != ring.iter().rev().find(finite)); + } + } + } + parts(rings, points) + } + }; + // The record's header and shape type in the `.shp`, and its entry in the `.shx`. + Some(8 + 4 + content + 8) +} + fn is_outer

(r: &shapefile::PolygonRing

) -> bool { matches!(r, shapefile::PolygonRing::Outer(_)) } @@ -6573,6 +6678,75 @@ mod tests { ); } + /// The bytes counted for each shape before it is built are the bytes its record takes: with + /// the two headers they come to the `.shp` and `.shx` written, whatever is filtered out, + /// closed or left out, so no shape that fits is refused. + #[test] + fn shapefile_record_bytes_are_what_is_written() { + let c = Coord::new; + let nan = c(f64::NAN, 1.0); + let closed = vec![c(0.0, 0.0), c(4.0, 0.0), c(4.0, 4.0), c(0.0, 0.0)]; + let open = vec![c(0.0, 0.0), nan, c(0.0, 4.0), c(4.0, 4.0), nan]; + let short = vec![c(1.0, 1.0), c(2.0, 2.0), nan]; + let layers = [ + (GeometryType::Point, vec![Geometry::Point(c(1.0, 2.0)), Geometry::Point(nan), Geometry::Line(vec![closed.clone()])]), + (GeometryType::Point, vec![Geometry::Point(c(1.0, 2.0)), Geometry::MultiPoint(open.clone()), Geometry::MultiPoint(vec![nan])]), + ( + GeometryType::Polyline, + vec![ + Geometry::Line(vec![short.clone(), vec![c(1.0, 1.0), nan], open.clone()]), + Geometry::Line(vec![vec![c(1.0, 1.0)]]), + Geometry::Line(vec![closed.clone()]), + ], + ), + ( + GeometryType::Polygon, + vec![ + Geometry::Polygon(vec![vec![closed.clone(), open.clone(), short.clone()]]), + Geometry::Polygon(vec![vec![short.clone(), closed.clone()], vec![open.clone()], vec![]]), + Geometry::Polygon(vec![vec![vec![nan, nan, c(1.0, 1.0)]]]), + ], + ), + ]; + for (kind, shapes) in layers { + let mut ds = Dataset::new("t", kind, vec![]); + let multi_points = shapes.iter().any(|g| matches!(g, Geometry::MultiPoint(_))); + let counted: usize = shapes.iter().filter_map(|g| shapefile_record_bytes(g, kind, multi_points)).sum(); + for g in shapes { + ds.push(Some(g), vec![]); + } + let (parts, _) = shapefile_parts_in(&ds, Crs::LonLat).unwrap(); + let written: usize = parts.iter().filter(|(e, _)| matches!(*e, "shp" | "shx")).map(|(_, b)| b.len()).sum(); + assert_eq!(2 * SHAPEFILE_HEADER + counted, written, "{kind:?}"); + } + } + + /// A CSV row holding a long cell the formula guard applies to reads as every other row: the + /// same text the `csv` crate makes of the whole cells, with the rows either side of it. + #[test] + fn csv_rows_around_a_long_guarded_cell_are_written_as_whole_cells() { + let long = format!("={}", "a \"b\", c\r\n".repeat(3_000)); + // Guarded, with nothing to quote. + let bare = format!("@{}", "x".repeat(20_000)); + let fields = vec![Field::new("a", FieldType::Text), Field::new("b", FieldType::Text)]; + let rows = [["x", ""], [long.as_str(), "y,z"], ["", ""], [bare.as_str(), long.as_str()], ["=1+1", bare.as_str()], ["end", "q\""]]; + for kind in [GeometryType::Point, GeometryType::None] { + let mut ds = Dataset::new("t", kind, fields.clone()); + let mut whole = csv::Writer::from_writer(Vec::new()); + let point = kind == GeometryType::Point; + let coordinates = |x: &str, y: &str| if point { vec![x.to_string(), y.to_string()] } else { Vec::new() }; + let header = coordinates("longitude", "latitude").into_iter().chain(["a".to_string(), "b".to_string()]); + whole.write_record(header).unwrap(); + for row in rows { + let geometry = point.then(|| Geometry::Point(Coord::new(1.5, 2.0))); + ds.push(geometry, row.iter().map(|s| Value::Text(s.to_string())).collect()); + let guarded = row.iter().map(|s| if s.starts_with(['=', '@']) { format!("'{s}") } else { s.to_string() }); + whole.write_record(coordinates("1.5", "2").into_iter().chain(guarded)).unwrap(); + } + assert_eq!(to_csv(&ds).unwrap().into_bytes(), whole.into_inner().unwrap()); + } + } + /// A write to a name nothing holds reserves it first: a second write to it is refused before /// anything is written, and dropping the write removes the reservation and the folder made for /// it; once installed, both stay (#2865). diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 0d73521ce8..d6133b7470 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -1,5 +1,7 @@ //! Attribute values and field definitions. +use std::borrow::Cow; + use crate::date::{Date, DateTime}; use serde::{Deserialize, Serialize}; @@ -129,6 +131,22 @@ impl Value { other => other.to_string(), } } + /// [`to_file_text`](Value::to_file_text), a text value's own text borrowed rather than + /// copied. + pub(crate) fn file_text(&self) -> Cow<'_, str> { + match self { + Value::Text(t) => Cow::Borrowed(t), + other => Cow::Owned(other.to_file_text()), + } + } + /// The value as it is shown ([`Display`](std::fmt::Display)), a text value's own text + /// borrowed rather than copied. + pub(crate) fn shown_text(&self) -> Cow<'_, str> { + match self { + Value::Text(t) => Cow::Borrowed(t), + other => Cow::Owned(other.to_string()), + } + } /// How a date or date-time compares: microseconds since 1970, a date at its midnight and a /// time without a zone as if it were UTC. `None` for other values. pub fn temporal_key(&self) -> Option { diff --git a/crates/data/src/zip.rs b/crates/data/src/zip.rs index d2ccff7880..7f7edb869d 100644 --- a/crates/data/src/zip.rs +++ b/crates/data/src/zip.rs @@ -1,5 +1,9 @@ //! Zip archives (Deflate or stored): packages bundle a project or map with its data files. +use std::io::{Seek, SeekFrom, Write}; + +use crate::capped::{PIECE, write_pieces}; + /// Most entries read from an archive (plain zip holds at most 65,535; ZIP64 isn't read). const MAX_ENTRIES: usize = 65_535; /// Largest entry inflated (1 GiB). @@ -36,14 +40,15 @@ fn crc32(data: &[u8]) -> u32 { /// holds at most 65,535 entries and 4 GiB, and names of up to 65,535 bytes; beyond that it's an /// error rather than a damaged archive. pub fn write(entries: &[(String, Vec)]) -> Result, String> { - let mut out = Vec::new(); + let mut out = std::io::Cursor::new(Vec::new()); write_to(entries, &mut out)?; - Ok(out) + Ok(out.into_inner()) } -/// [`write`]'s archive, written to `out` as it is made (a buffer held to a limit stops it there). -/// Besides `out`, it holds the central directory and one entry's compressed bytes at a time. -pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Write) -> Result<(), String> { +/// [`write`]'s archive, written to `out`, empty as it starts, as it is made (a buffer held to a +/// limit stops it there). Each entry is deflated into `out` a piece at a time, so besides `out` +/// it holds the central directory, a piece and the compressor. +pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut (impl Write + Seek)) -> Result<(), String> { let too_big = || "the archive is too large for a zip file".to_string(); let failed = |e: std::io::Error| e.to_string(); let count = u16::try_from(entries.len()).map_err(|_| too_big())?; @@ -55,11 +60,8 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Wr let name_len = u16::try_from(n.len()).map_err(|_| too_big())?; let data_len = u32::try_from(data.len()).map_err(|_| too_big())?; let crc = crc32(data); - let z = miniz_oxide::deflate::compress_to_vec(data, 6); - let (method, body): (u16, &[u8]) = if z.len() < data.len() { (8, &z) } else { (0, data) }; let offset = u32::try_from(written).map_err(|_| too_big())?; - let body_len = u32::try_from(body.len()).map_err(|_| too_big())?; - let header = |sig: u32, central: bool| { + let header = |sig: u32, central: bool, method: u16, body_len: u32| { let mut h = Vec::new(); h.extend_from_slice(&sig.to_le_bytes()); if central { @@ -85,11 +87,27 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Wr h.extend_from_slice(n); h }; - let local = header(0x0403_4B50, false); + // The header goes before the body, whose method and length are known only after it: its + // place is taken, then it is written again. + let local = header(0x0403_4B50, false, 0, 0); out.write_all(&local).map_err(failed)?; - out.write_all(body).map_err(failed)?; - written = written.saturating_add(local.len()).saturating_add(body.len()); - central.extend_from_slice(&header(0x0201_4B50, true)); + let body_at = written.saturating_add(local.len()) as u64; + let (method, body_len) = match deflate_to(data, out).map_err(failed)? { + Some(len) => (8, len), + None => { + // Over what was deflated, which is shorter. + out.seek(SeekFrom::Start(body_at)).map_err(failed)?; + write_pieces(out, data).map_err(failed)?; + (0, data.len()) + } + }; + let body_len_32 = u32::try_from(body_len).map_err(|_| too_big())?; + let end = body_at.saturating_add(body_len as u64); + out.seek(SeekFrom::Start(written as u64)).map_err(failed)?; + out.write_all(&header(0x0403_4B50, false, method, body_len_32)).map_err(failed)?; + out.seek(SeekFrom::Start(end)).map_err(failed)?; + written = written.saturating_add(local.len()).saturating_add(body_len); + central.extend_from_slice(&header(0x0201_4B50, true, method, body_len_32)); } let cd_offset = u32::try_from(written).map_err(|_| too_big())?; let cd_len = u32::try_from(central.len()).map_err(|_| too_big())?; @@ -104,6 +122,28 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Wr out.write_all(&end).map_err(failed) } +/// `data` deflated into `out` at level 6, the bytes `compress_to_vec` makes: its length when that +/// is less than `data`'s, else `None` once it would come to as much, with less than that written. +fn deflate_to(data: &[u8], out: &mut impl Write) -> std::io::Result> { + use miniz_oxide::deflate::core::{CompressorOxide, TDEFLFlush, TDEFLStatus, compress, create_comp_flags_from_zip_params}; + let mut compressor = CompressorOxide::new(create_comp_flags_from_zip_params(6, 0, 0)); + let mut piece = [0; PIECE]; + let (mut input, mut len) = (data, 0usize); + loop { + let (status, taken, made) = compress(&mut compressor, input, &mut piece, TDEFLFlush::Finish); + len = len.saturating_add(made); + if len >= data.len() { + return Ok(None); + } + out.write_all(piece.get(..made).unwrap_or_default())?; + match status { + TDEFLStatus::Done => return Ok(Some(len)), + TDEFLStatus::Okay if taken > 0 || made > 0 => input = input.get(taken..).unwrap_or_default(), + _ => return Err(std::io::Error::other("the entry couldn't be compressed")), + } + } +} + fn u16_at(b: &[u8], i: usize) -> Option { let s = b.get(i..i.checked_add(2)?)?; Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]) as usize) @@ -353,6 +393,35 @@ fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreads mod tests { use super::*; + /// An entry's body is what deflating it in one call at level 6 gives when that is smaller, + /// else the entry as it is, with the next record straight after: for entries shorter and + /// longer than a piece, that deflate or not. + #[test] + fn entries_are_deflated_as_in_one_call_or_stored() { + let mut state = 7u32; + let noise: Vec = std::iter::repeat_with(|| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .take(200_000) + .collect(); + let halves: Vec = noise.iter().map(|b| b & 0x0f).collect(); + let text: Vec = b"the same words again. ".repeat(9_000); + let whole = [Vec::new(), vec![7], b"abc".repeat(3), vec![0; 100_000], text, noise, halves]; + for data in &whole { + let archive = write(&[("e".into(), data.clone())]).unwrap(); + let deflated = miniz_oxide::deflate::compress_to_vec(data, 6); + let (method, body) = if deflated.len() < data.len() { (8, &deflated) } else { (0, data) }; + let end = 31 + body.len(); + assert_eq!(u16_at(&archive, 8), Some(method), "{} bytes", data.len()); + assert_eq!(u32_at(&archive, 18), Some(body.len())); + assert_eq!(archive.get(31..end), Some(body.as_slice())); + assert_eq!(u32_at(&archive, end), Some(0x0201_4B50)); + } + let entries: Vec<(String, Vec)> = whole.into_iter().enumerate().map(|(i, d)| (i.to_string(), d)).collect(); + assert_eq!(read(&write(&entries).unwrap()).unwrap(), entries); + } + #[test] fn spreadsheet_members_use_unicode_path_names() { let raw = "legacy.txt"; diff --git a/crates/data/tests/large_value_memory.rs b/crates/data/tests/large_value_memory.rs new file mode 100644 index 0000000000..4872891124 --- /dev/null +++ b/crates/data/tests/large_value_memory.rs @@ -0,0 +1,108 @@ +//! The memory a download's writers take for one large value or shape: it is neither copied nor +//! built into a record before the limit refuses it. A test binary of its own, as the peak it +//! reads is the whole process's. +#![cfg(target_os = "linux")] + +use rustgis_data::capped::Limit; +use rustgis_data::raster::Crs; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, Value}; + +/// The bytes of each large value or shape. +const ITEM: usize = 32 << 20; +/// The room its file is held to. +const ROOM: usize = 1 << 20; +/// The most the peak may grow while an item is written: a quarter of the item. +const MOST: u64 = 8 << 20; + +/// The most memory this process has held since the peak was last reset, in bytes. +fn peak_bytes() -> u64 { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let line = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).unwrap(); + line.trim().trim_end_matches("kB").trim().parse::().unwrap() * 1024 +} + +/// How far `run` takes the peak past what is held as it starts. +fn growth(run: impl FnOnce()) -> u64 { + // Linux sets the peak back to what is held now. + std::fs::write("/proc/self/clear_refs", "5").unwrap(); + let before = peak_bytes(); + run(); + peak_bytes().saturating_sub(before) +} + +/// A one-feature layer of `geometry` with the text `value` in a field. +fn layer(geometry: Geometry, field: &str, value: String) -> Dataset { + let mut ds = Dataset::new("large", geometry.kind(), vec![Field::new(field, FieldType::Text)]); + ds.push(Some(geometry), vec![Value::Text(value)]); + ds +} + +#[test] +fn a_large_value_or_shape_is_not_copied_for_a_download() { + let point = || Geometry::Point(Coord::new(1.0, 2.0)); + let plain = || "x".repeat(ITEM); + let formula = || format!("={}", "\"x".repeat(ITEM / 2)); + // Text holding numbers, as a JSON document in a cell does. + let digits = || "{\"a\": 1.5} ".repeat(ITEM / 11); + let vertices = || (0..ITEM / 16).map(|i| Coord::new((i % 360) as f64 - 180.0, 1.5)).collect::>(); + let mut over = Vec::new(); + let mut check = |name: &str, grew: u64| { + if grew >= MOST { + over.push(format!("{name}: the peak grew {} MiB", grew >> 20)); + } + }; + + // Each text format stops a file at the room without a copy of the value. + for (name, format, name_field, field, value) in [ + ("KML description", "kml", None, "description", plain()), + ("KML attribute", "kml", None, "note", plain()), + ("GPX name", "gpx", Some(0), "note", plain()), + ("WKT cell", "wkt", None, "note", plain()), + ("WKT guarded cell", "wkt", None, "note", formula()), + ("CSV cell", "csv", None, "note", plain()), + ("CSV guarded cell", "csv", None, "note", formula()), + ] { + let ds = layer(point(), field, value); + let limit = Limit::new(ROOM); + let grew = growth(|| assert!(rustgis_data::io::text_bytes_within(&ds, format, name_field, &limit).is_err(), "{name}")); + assert!(limit.passed(), "{name}"); + check(name, grew); + } + + // The counting of what a file loses runs before it is written. + for (name, ext, value) in + [("CSV notices", "csv", digits()), ("CSV guarded notices", "csv", formula()), ("KML notices", "kml", digits())] + { + let ds = layer(point(), "note", value); + let grew = growth(|| { + rustgis_data::io::export_losses_notes_in(&ds, ext, None, "t", Crs::LonLat).unwrap(); + }); + check(name, grew); + } + + // A dBase column keeps 254 bytes of a value, so the Shapefile fits. + let ds = layer(point(), "note", plain()); + let grew = growth(|| { + rustgis_data::io::write_bytes_noted_within(&ds, "shp", Crs::LonLat, "t", &Limit::new(ROOM)).unwrap(); + }); + check("dBase value", grew); + let grew = growth(|| assert_eq!(rustgis_data::io::shapefile_values_notes(&ds, "t").len(), 1)); + check("dBase notices", grew); + + // A shape whose record can't fit is refused before its points are copied. + for (name, geometry) in [ + ("Shapefile line", Geometry::Line(vec![vertices()])), + ("Shapefile polygon", Geometry::Polygon(vec![vec![vertices()]])), + ("Shapefile multipoint", Geometry::MultiPoint(vertices())), + ] { + let ds = layer(geometry, "note", String::new()); + let limit = Limit::new(ROOM); + let grew = growth(|| { + assert!(rustgis_data::io::write_bytes_noted_within(&ds, "shp", Crs::LonLat, "t", &limit).is_err(), "{name}"); + }); + assert!(limit.passed(), "{name}"); + check(name, grew); + } + + assert!(over.is_empty(), "{over:#?}"); +} From 10bfa842b57852305887081fd1c89501fd5b9264 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 23:05:45 -0600 Subject: [PATCH 2/7] fix(data): trim a finished file only when it is held to a limit A download gives its spare room back because the queue counts what it holds; a file to be written (no limit) is no longer reallocated to drop it. --- crates/data/src/capped.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 0deef610ae..41389df36f 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -118,7 +118,11 @@ impl Buffer<'_> { /// The file made, its spare room given back, no longer counted against the limit. pub(crate) fn into_inner(mut self) -> Vec { let mut file = std::mem::take(&mut self.file); - file.shrink_to_fit(); + // Only a file held to a limit (a download, which waits counted by what it holds) gives + // back its spare room: a file to be written isn't reallocated for it. + if self.limit.max != usize::MAX { + file.shrink_to_fit(); + } self.release(); file } @@ -203,6 +207,24 @@ mod tests { use crate::raster::{ColorHint, Crs, GeoTransform, Raster, cogwrite, geotiff}; use crate::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + /// A file made under no limit (one to be written) keeps its allocation when finished, so it + /// isn't reallocated; one held to a limit gives its spare room back. + #[test] + fn only_a_limited_file_is_trimmed_when_finished() { + let unlimited = Limit::none(); + let mut b = unlimited.buffer(); + b.write_all(&[1; 5]).unwrap(); + let room = b.file.capacity(); + assert!(room > 5, "{room}"); + assert_eq!(b.into_inner().capacity(), room); + let limit = Limit::new(1000); + let mut b = limit.buffer(); + b.write_all(&[1; 5]).unwrap(); + b.write_all(&[1; 5]).unwrap(); + let file = b.into_inner(); + assert_eq!(file.capacity(), file.len()); + } + /// A request past the limit, however large, is refused without changing what is counted. #[test] fn a_request_past_the_limit_leaves_the_count_as_it_was() { From f33ddb560e87756ede7f96ee6911011f35c6115a Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 23:23:45 -0600 Subject: [PATCH 3/7] test(data): give the trim test a buffer with spare room A first write allocates exactly what it holds, so the test now writes five bytes and then one, leaving ten allocated for six. --- crates/data/src/capped.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 41389df36f..f11cdedee6 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -211,18 +211,20 @@ mod tests { /// isn't reallocated; one held to a limit gives its spare room back. #[test] fn only_a_limited_file_is_trimmed_when_finished() { + // Five bytes, then one more: the allocation doubles to ten for six. let unlimited = Limit::none(); let mut b = unlimited.buffer(); b.write_all(&[1; 5]).unwrap(); - let room = b.file.capacity(); - assert!(room > 5, "{room}"); - assert_eq!(b.into_inner().capacity(), room); + b.write_all(&[1]).unwrap(); + assert_eq!(b.file.capacity(), 10); + assert_eq!(b.into_inner().capacity(), 10); let limit = Limit::new(1000); let mut b = limit.buffer(); b.write_all(&[1; 5]).unwrap(); - b.write_all(&[1; 5]).unwrap(); + b.write_all(&[1]).unwrap(); + assert_eq!(b.file.capacity(), 10); let file = b.into_inner(); - assert_eq!(file.capacity(), file.len()); + assert_eq!((file.len(), file.capacity()), (6, 6)); } /// A request past the limit, however large, is refused without changing what is counted. From a2ae378ea0b19efe9a1f2cfc8041be9846e51fd9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 00:47:22 -0600 Subject: [PATCH 4/7] fix(data): count a number's significant digits without copying them The CSV guard and the precision check collected every digit of a number cell before counting them, so one long number (a run of zeros after the point) was copied whole. They now find the significant digits in place, and copy only those, past which no Double holds. --- crates/data/src/io.rs | 39 +++++++++++++++++++------ crates/data/tests/large_value_memory.rs | 12 ++++++-- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a4256bcb56..f76fafa4e9 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3581,11 +3581,29 @@ impl TextColumn { /// exactly) are; `12345678901234567891` and `0.12345678901234567891` aren't. No Double's exact /// value has more than 767 significant digits, so longer text isn't one, and isn't formatted. pub fn double_holds(v: &str) -> bool { - /// The digits of a number's mantissa without leading or trailing zeros. + /// Where a number's significant digits run among its mantissa's digits: from the first to + /// the last that isn't zero. Found in place, so a long mantissa isn't copied. + fn span(s: &str) -> Option<(usize, usize)> { + let mantissa = s.split(['e', 'E']).next().unwrap_or_default(); + let (mut first, mut last) = (None, 0); + for (i, b) in mantissa.bytes().filter(u8::is_ascii_digit).enumerate() { + if b != b'0' { + first.get_or_insert(i); + last = i; + } + } + first.map(|first| (first, last)) + } + /// How many significant digits a number has. + fn significant(s: &str) -> usize { + span(s).map_or(0, |(first, last)| last - first + 1) + } + /// The digits of a number's mantissa without leading or trailing zeros: only those are + /// copied. fn digits(s: &str) -> String { + let Some((first, last)) = span(s) else { return String::new() }; let mantissa = s.split(['e', 'E']).next().unwrap_or_default(); - let all: String = mantissa.chars().filter(char::is_ascii_digit).collect(); - all.trim_start_matches('0').trim_end_matches('0').to_string() + mantissa.chars().filter(char::is_ascii_digit).skip(first).take(last - first + 1).collect() } // A whole number written as one is held only exactly: `12345678901234567000` is a Double's // 17 digits and zeros, but that Double is 12345678901234567168. @@ -3599,8 +3617,13 @@ pub fn double_holds(v: &str) -> bool { // Parsed first, so the digits of text that is no number aren't copied. v.parse::().is_ok_and(|x| { x.is_finite() && { - let want = digits(v); - want.is_empty() || want.len() <= 767 && digits(&format!("{x:.*e}", want.len() - 1)) == want + // Past what any Double holds, refused before its digits are copied. + let n = significant(v); + n == 0 + || n <= 767 && { + let want = digits(v); + digits(&format!("{x:.*e}", want.len() - 1)) == want + } } }) } @@ -3645,10 +3668,8 @@ fn is_long_number(v: &str) -> bool { let mantissa = v.split(['e', 'E']).next().unwrap_or_default(); let (whole, frac) = mantissa.split_once('.').unwrap_or((mantissa, "")); let frac = frac.trim_end_matches('0'); - let mut digits = String::new(); - digits.extend(whole.chars().filter(char::is_ascii_digit)); - digits.extend(frac.chars().filter(char::is_ascii_digit)); - digits.trim_start_matches('0').len() > 15 + // Counted in place, stopping at the sixteenth: a long number isn't copied. + whole.bytes().chain(frac.bytes()).filter(u8::is_ascii_digit).skip_while(|b| *b == b'0').nth(15).is_some() } /// Undoes the export formula guard: `'=x` reads back as `=x`. diff --git a/crates/data/tests/large_value_memory.rs b/crates/data/tests/large_value_memory.rs index 4872891124..d45ac0214d 100644 --- a/crates/data/tests/large_value_memory.rs +++ b/crates/data/tests/large_value_memory.rs @@ -44,6 +44,8 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { let formula = || format!("={}", "\"x".repeat(ITEM / 2)); // Text holding numbers, as a JSON document in a cell does. let digits = || "{\"a\": 1.5} ".repeat(ITEM / 11); + // One enormous finite number, whose digits the guard and precision checks count. + let number = || format!("+0.{}1", "0".repeat(ITEM)); let vertices = || (0..ITEM / 16).map(|i| Coord::new((i % 360) as f64 - 180.0, 1.5)).collect::>(); let mut over = Vec::new(); let mut check = |name: &str, grew: u64| { @@ -61,6 +63,7 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { ("WKT guarded cell", "wkt", None, "note", formula()), ("CSV cell", "csv", None, "note", plain()), ("CSV guarded cell", "csv", None, "note", formula()), + ("CSV number cell", "csv", None, "note", number()), ] { let ds = layer(point(), field, value); let limit = Limit::new(ROOM); @@ -70,9 +73,12 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { } // The counting of what a file loses runs before it is written. - for (name, ext, value) in - [("CSV notices", "csv", digits()), ("CSV guarded notices", "csv", formula()), ("KML notices", "kml", digits())] - { + for (name, ext, value) in [ + ("CSV notices", "csv", digits()), + ("CSV guarded notices", "csv", formula()), + ("CSV number notices", "csv", number()), + ("KML notices", "kml", digits()), + ] { let ds = layer(point(), "note", value); let grew = growth(|| { rustgis_data::io::export_losses_notes_in(&ds, ext, None, "t", Crs::LonLat).unwrap(); From 00fc80d9a3f19a9d88153bba1da262337875e9d4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 11:10:31 -0600 Subject: [PATCH 5/7] fix(data): count what the .dbf holds before copying a Shapefile shape The check that refuses a shape too large for a download counted only the .shp and .shx records. With a .dbf already holding much of the limit, a shape could pass it and be copied before the writer refused it. The check now adds what the shape would grow the .shp and .shx by to what the three buffers already hold. Room the .shp and .shx hold already is not counted twice, so a shape that fits is still written. --- crates/data/src/capped.rs | 20 +++++++- crates/data/src/io.rs | 61 ++++++++++++++++++++----- crates/data/tests/large_value_memory.rs | 36 ++++++++++++++- 3 files changed, 104 insertions(+), 13 deletions(-) diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index f11cdedee6..5186de460a 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -54,9 +54,22 @@ impl Limit { self.whole(Ok(())) } + /// Refuses as [`Limit::fits`] does when `more` bytes can't be held beside what is counted now. + pub(crate) fn fits_more(&self, more: usize) -> Result<()> { + self.fits(self.held.load(Ordering::Relaxed).saturating_add(more)) + } + /// An empty buffer counted against this limit. pub(crate) fn buffer(&self) -> Buffer<'_> { - Buffer { file: Vec::new(), at: 0, limit: self, charged: 0 } + Buffer { file: Vec::new(), at: 0, limit: self, charged: 0, room: None } + } + + /// [`Limit::buffer`], which also keeps `room` at the bytes counted for it as it grows: for a + /// caller to ask while a writer has the buffer. + pub(crate) fn watched_buffer<'a>(&'a self, room: &'a AtomicUsize) -> Buffer<'a> { + let mut buffer = self.buffer(); + buffer.room = Some(room); + buffer } /// Counts `bytes` held apart from the buffers (files made in them and taken out, while an @@ -112,6 +125,8 @@ pub(crate) struct Buffer<'a> { limit: &'a Limit, /// The allocation counted against the limit: what the system holds, not the file's length. charged: usize, + /// Told `charged` as it grows ([`Limit::watched_buffer`]). + room: Option<&'a AtomicUsize>, } impl Buffer<'_> { @@ -145,6 +160,9 @@ impl Buffer<'_> { let room = old.saturating_mul(2).max(end).min(old.saturating_add(left)).max(end); self.limit.take(room - old)?; self.charged += room - old; + if let Some(told) = self.room { + told.store(self.charged, Ordering::Relaxed); + } // For bytes, `try_reserve_exact` allocates what is asked. self.file.try_reserve_exact(room - self.file.len()).map_err(|_| Error::from(ErrorKind::OutOfMemory))?; Ok(()) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 7144f10678..a1ddf2d400 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3,6 +3,7 @@ use std::borrow::Cow; use std::collections::BTreeMap; use std::path::Path; +use std::sync::atomic::AtomicUsize; use serde::ser::{Serialize, SerializeMap, Serializer}; use serde_json::{Map, Value as Json, json}; @@ -6523,7 +6524,9 @@ fn shapefile_parts_within( let pt = |c: &Coord| shapefile::Point::new(c.x, c.y); let finite = |c: &&Coord| c.x.is_finite() && c.y.is_finite(); - let (mut shp, mut shx, mut dbf) = (limit.buffer(), limit.buffer(), limit.buffer()); + // The room the `.shp` and `.shx` hold of the limit, asked while the writer has them. + let (shp_room, shx_room) = (AtomicUsize::new(0), AtomicUsize::new(0)); + let (mut shp, mut shx, mut dbf) = (limit.watched_buffer(&shp_room), limit.watched_buffer(&shx_room), limit.buffer()); let mut left_out = 0; let mut written = 0; { @@ -6531,16 +6534,20 @@ fn shapefile_parts_within( let mut w = shapefile::Writer::new(shapes, table.build_with_dest(&mut dbf)); let multi_points = ds.features.iter().any(|f| matches!(f.geometry, Some(Geometry::MultiPoint(_)))); // What the `.shp` and `.shx` come to with each shape: their headers, then the records. - let mut shape_bytes = 2 * SHAPEFILE_HEADER; + let (mut shp_bytes, mut shx_bytes) = (SHAPEFILE_HEADER, SHAPEFILE_HEADER); for f in &ds.features { crate::progress::step(1)?; - // A shape is copied to be written: one whose record can't fit is refused first. + // A shape is copied to be written: one whose record can't fit beside what the three + // files hold is refused first. if limit.bounded() && let Some(g) = &f.geometry && let Some(bytes) = shapefile_record_bytes(g, ds.geometry_type, multi_points) { - shape_bytes = shape_bytes.saturating_add(bytes); - limit.fits(shape_bytes)?; + shp_bytes = shp_bytes.saturating_add(bytes); + shx_bytes = shx_bytes.saturating_add(SHX_RECORD); + // Only what passes the room the `.shp` and `.shx` already hold is more to hold. + let more = |bytes: usize, room: &AtomicUsize| bytes.saturating_sub(room.load(std::sync::atomic::Ordering::Relaxed)); + limit.fits_more(more(shp_bytes, &shp_room).saturating_add(more(shx_bytes, &shx_room)))?; } let ok = match (&f.geometry, ds.geometry_type) { (Some(Geometry::Point(c)), GeometryType::Point) if !multi_points && finite(&c) => { @@ -6624,7 +6631,11 @@ fn shapefile_parts_within( /// The bytes of a `.shp` file's header, and of a `.shx` file's. const SHAPEFILE_HEADER: usize = 100; -/// The bytes `g`'s record adds to a `.shp` and its `.shx` in a layer of type `gt`, counted from +/// The bytes of a record's entry in a `.shx`. +const SHX_RECORD: usize = 8; + +/// The bytes `g`'s record adds to a `.shp` in a layer of type `gt` (its `.shx` entry is +/// [`SHX_RECORD`] more), counted from /// the vertices [`shapefile_parts_within`] keeps, without copying them; `None` for one it leaves /// out. `multi_points` says the layer's points are written as multipoints. fn shapefile_record_bytes(g: &Geometry, gt: GeometryType, multi_points: bool) -> Option { @@ -6662,8 +6673,8 @@ fn shapefile_record_bytes(g: &Geometry, gt: GeometryType, multi_points: bool) -> parts(rings, points) } }; - // The record's header and shape type in the `.shp`, and its entry in the `.shx`. - Some(8 + 4 + content + 8) + // The record's header and shape type, then its content. + Some(8 + 4 + content) } fn is_outer

(r: &shapefile::PolygonRing

) -> bool { @@ -6758,13 +6769,41 @@ mod tests { for (kind, shapes) in layers { let mut ds = Dataset::new("t", kind, vec![]); let multi_points = shapes.iter().any(|g| matches!(g, Geometry::MultiPoint(_))); - let counted: usize = shapes.iter().filter_map(|g| shapefile_record_bytes(g, kind, multi_points)).sum(); + let counted: Vec = shapes.iter().filter_map(|g| shapefile_record_bytes(g, kind, multi_points)).collect(); for g in shapes { ds.push(Some(g), vec![]); } let (parts, _) = shapefile_parts_in(&ds, Crs::LonLat).unwrap(); - let written: usize = parts.iter().filter(|(e, _)| matches!(*e, "shp" | "shx")).map(|(_, b)| b.len()).sum(); - assert_eq!(2 * SHAPEFILE_HEADER + counted, written, "{kind:?}"); + let written = |ext: &str| parts.iter().find(|(e, _)| *e == ext).unwrap().1.len(); + assert_eq!(SHAPEFILE_HEADER + counted.iter().sum::(), written("shp"), "{kind:?}"); + assert_eq!(SHAPEFILE_HEADER + SHX_RECORD * counted.len(), written("shx"), "{kind:?}"); + } + } + + /// A shape is counted with what the three files already hold: it is written where they fit + /// together, with a `.dbf` holding most of the room, and where it fits in room the `.shp` + /// and `.shx` hold already, though nothing is left of the limit. + #[test] + fn a_shape_that_fits_beside_what_the_three_files_hold_is_written() { + let line = |points: u32| Geometry::Line(vec![(0..points).map(|i| Coord::new(f64::from(i), 1.0)).collect()]); + let layer = |shapes: Vec, rows: usize, width: usize| { + let mut ds = Dataset::new("t", GeometryType::Polyline, vec![Field::new("n", FieldType::Text)]); + for _ in 0..rows { + ds.push(Some(line(2)), vec![Value::Text("x".repeat(width))]); + } + for g in shapes { + ds.push(Some(g), vec![Value::Text("x".to_string())]); + } + ds + }; + for (ds, max) in [ + (layer(vec![line(1_000)], 200, 254), 100_000), + // A short line's growth of the `.shp` takes all that is left, and the rest fit in it. + (layer(std::iter::once(line(900)).chain(std::iter::repeat_n(line(2), 30)).collect(), 0, 1), 17_500), + ] { + let unlimited = shapefile_parts_in(&ds, Crs::LonLat).unwrap().0; + let (parts, ..) = shapefile_parts_within(&ds, Crs::LonLat, None, &Limit::new(max)).unwrap(); + assert_eq!(parts, unlimited, "{max}"); } } diff --git a/crates/data/tests/large_value_memory.rs b/crates/data/tests/large_value_memory.rs index d45ac0214d..e936ea2906 100644 --- a/crates/data/tests/large_value_memory.rs +++ b/crates/data/tests/large_value_memory.rs @@ -5,7 +5,7 @@ use rustgis_data::capped::Limit; use rustgis_data::raster::Crs; -use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, Value}; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; /// The bytes of each large value or shape. const ITEM: usize = 32 << 20; @@ -14,6 +14,14 @@ const ROOM: usize = 1 << 20; /// The most the peak may grow while an item is written: a quarter of the item. const MOST: u64 = 8 << 20; +/// The rows before the large shape that fills a `.dbf`, and the columns of 254 bytes in each. +const ROWS: usize = 10_000; +const COLUMNS: usize = 10; +/// The bytes those rows take in the `.dbf`: each its columns and a deletion flag. +const TABLE: usize = ROWS * (COLUMNS * 254 + 1); +/// Room that holds the table or the large shape after them, not both. +const SHARED_ROOM: usize = ITEM + TABLE / 2; + /// The most memory this process has held since the peak was last reset, in bytes. fn peak_bytes() -> u64 { let status = std::fs::read_to_string("/proc/self/status").unwrap(); @@ -30,6 +38,20 @@ fn growth(run: impl FnOnce()) -> u64 { peak_bytes().saturating_sub(before) } +/// [`ROWS`] short lines with a wide table, then one line of `ITEM` bytes of points. +fn large_shape_after_a_large_table(last: Vec) -> Dataset { + let fields = (0..COLUMNS).map(|k| Field::new(format!("c{k}"), FieldType::Text)).collect(); + let mut ds = Dataset::new("after", GeometryType::Polyline, fields); + let short = || Geometry::Line(vec![vec![Coord::new(1.0, 2.0), Coord::new(3.0, 4.0)]]); + // The first row's values give each column its width; the rest are padded to it. + for row in 0..ROWS { + let value = if row == 0 { "x".repeat(254) } else { String::new() }; + ds.push(Some(short()), vec![Value::Text(value); COLUMNS]); + } + ds.push(Some(Geometry::Line(vec![last])), vec![Value::Null; COLUMNS]); + ds +} + /// A one-feature layer of `geometry` with the text `value` in a field. fn layer(geometry: Geometry, field: &str, value: String) -> Dataset { let mut ds = Dataset::new("large", geometry.kind(), vec![Field::new(field, FieldType::Text)]); @@ -110,5 +132,17 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { check(name, grew); } + // So is a shape that would fit only if what the `.dbf` holds weren't counted: the peak grows + // by little more than the table. + let ds = large_shape_after_a_large_table(vertices()); + let limit = Limit::new(SHARED_ROOM); + let grew = growth(|| { + assert!(rustgis_data::io::write_bytes_noted_within(&ds, "shp", Crs::LonLat, "t", &limit).is_err()); + }); + assert!(limit.passed()); + if grew >= TABLE as u64 + MOST { + over.push(format!("Shapefile line after a table: the peak grew {} MiB", grew >> 20)); + } + assert!(over.is_empty(), "{over:#?}"); } From 3e402f832afbadc989f133509be20fdba39ff74d Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 13:27:21 -0600 Subject: [PATCH 6/7] test(data): give the Shapefile room test limits its layers can fit Neither case could pass on any machine. The limit counts what each file's buffer has allocated, which doubles as it grows: the first layer needs 118,748 bytes against a limit of 100,000, with or without the early check, and the second layer's files alone came to 17,672 bytes against 17,500. Raise the first limit to 130,000, and write some short lines before the long one in the second so the .shx and .dbf have their room before the .shp takes what is left of 18,000. Both cases are still refused by a check that counts the room the .shp and .shx hold a second time. --- crates/data/src/io.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a1ddf2d400..f6931989dd 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6796,10 +6796,16 @@ mod tests { } ds }; + let short = |n| std::iter::repeat_n(line(2), n); + // The limit counts what each file's buffer has allocated, which doubles as it grows, so + // a layer needs more than its files' lengths. Both are refused if the room the `.shp` and + // `.shx` hold is counted again. for (ds, max) in [ - (layer(vec![line(1_000)], 200, 254), 100_000), - // A short line's growth of the `.shp` takes all that is left, and the rest fit in it. - (layer(std::iter::once(line(900)).chain(std::iter::repeat_n(line(2), 30)).collect(), 0, 1), 17_500), + // Files of 87 KB that need 119 KB of room, the `.dbf` holding over half of the limit. + (layer(vec![line(1_000)], 200, 254), 130_000), + // The long line's growth of the `.shp` takes all that is left, and the short lines + // after it fit in it. Those before it give the `.shx` and `.dbf` their room first. + (layer(short(12).chain([line(900)]).chain(short(18)).collect(), 0, 1), 18_000), ] { let unlimited = shapefile_parts_in(&ds, Crs::LonLat).unwrap().0; let (parts, ..) = shapefile_parts_within(&ds, Crs::LonLat, None, &Limit::new(max)).unwrap(); From 8052f60b3ac65652337fe696792483532dfbb986 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:13:14 -0600 Subject: [PATCH 7/7] fix(data): don't copy a multipoint's unwritten points for a Shapefile --- crates/data/src/io.rs | 8 ++++++-- crates/data/tests/large_value_memory.rs | 17 ++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index f6931989dd..ac7d972048 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6556,8 +6556,12 @@ fn shapefile_parts_within( } (Some(g @ (Geometry::Point(_) | Geometry::MultiPoint(_))), GeometryType::Point) => { let mut pts = Vec::new(); - g.for_each_coord(|c| pts.push(c)); - let pts: Vec = pts.iter().filter(finite).map(pt).collect(); + // The finite ones alone, whose record the limit has been checked for. + g.for_each_coord(|c| { + if finite(&&c) { + pts.push(pt(&c)); + } + }); if pts.is_empty() { false } else { diff --git a/crates/data/tests/large_value_memory.rs b/crates/data/tests/large_value_memory.rs index e936ea2906..0d1e830122 100644 --- a/crates/data/tests/large_value_memory.rs +++ b/crates/data/tests/large_value_memory.rs @@ -132,7 +132,22 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { check(name, grew); } - // So is a shape that would fit only if what the `.dbf` holds weren't counted: the peak grows + // A shape with no vertex to write is left out without copying its points, though the layer's + // other shape makes the file. + let nowhere = || vec![Coord::new(f64::NAN, 1.5); ITEM / 16]; + for (name, empty, drawn) in [ + ("empty Shapefile line", Geometry::Line(vec![nowhere()]), Geometry::Line(vec![vec![Coord::new(1.0, 2.0), Coord::new(3.0, 4.0)]])), + ("empty Shapefile multipoint", Geometry::MultiPoint(nowhere()), Geometry::MultiPoint(vec![Coord::new(1.0, 2.0)])), + ] { + let mut ds = layer(empty, "note", String::new()); + ds.push(Some(drawn), vec![Value::Text(String::new())]); + let grew = growth(|| { + rustgis_data::io::write_bytes_noted_within(&ds, "shp", Crs::LonLat, "t", &Limit::new(ROOM)).unwrap(); + }); + check(name, grew); + } + + // A shape is also refused early that would fit only if what the `.dbf` holds weren't counted: the peak grows // by little more than the table. let ds = large_shape_after_a_large_table(vertices()); let limit = Limit::new(SHARED_ROOM);