diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 98435d5368..5186de460a 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,9 +39,37 @@ 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(())) + } + + /// 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 @@ -88,13 +125,19 @@ 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<'_> { /// 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 } @@ -117,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(()) @@ -179,6 +225,26 @@ 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() { + // 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(); + 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]).unwrap(); + assert_eq!(b.file.capacity(), 10); + let file = b.into_inner(); + assert_eq!((file.len(), file.capacity()), (6, 6)); + } + /// 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() { @@ -320,6 +386,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 f260faf359..7ddece5782 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}") } @@ -118,23 +140,23 @@ pub(crate) fn kml_typed_string(field: &crate::Field) -> bool { /// [`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<()> { + check_xml(&ds.name, "KML", || "layer name".to_string())?; out.write_all(b"\n{}", - xml(&ds.name, "KML", || "layer name".to_string())? + out.write_all( + b" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", )?; + write_xml(out, &ds.name, false)?; + out.write_all(b"\n")?; // Declare columns independently of populated values, so all-null columns survive a read. out.write_all(b"")?; for field in &ds.fields { crate::progress::check()?; - let name = xml(&field.name, "KML", || format!("{}, field name '{}'", ds.name, field.name.escape_debug()))? - .replace('\t', " ") - .replace('\n', " "); + check_xml(&field.name, "KML", || format!("{}, field name '{}'", ds.name, field.name.escape_debug()))?; // ExtendedData's Data/value entries are text. Keep their inferred-reader behavior; // a 64-bit integer must not be mislabeled as KML's 32-bit int type. - let ty = "string"; - write!(out, "")?; + out.write_all(b"")?; } out.write_all(b"\n")?; // KML's description is text. Other types and differently-cased columns stay in @@ -143,41 +165,49 @@ pub(crate) fn write_kml(ds: &Dataset, name_field: Option, out: &mut impl 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', " "); - // An opaque source id can look numeric, including ids accepted from malformed - // XML ID attributes. Explicit string typing keeps its exact spelling on read. - let ty = if kml_typed_string(fd) { " xsi:type=\"xs:string\"" } else { "" }; - 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"".as_slice() } else { b"\">".as_slice() })?; + 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")?; } @@ -194,6 +224,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 { @@ -208,7 +252,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. @@ -227,24 +270,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)?; } @@ -629,10 +672,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. @@ -644,27 +706,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")?; } @@ -731,6 +794,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 66e8e72122..ac7d972048 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1,7 +1,9 @@ //! Vector readers and writers: GeoJSON, CSV (with longitude/latitude columns) and Shapefile. +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}; @@ -1136,7 +1138,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)?; @@ -3591,11 +3593,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. @@ -3606,9 +3626,18 @@ 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() && { + // 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 + } + } + }) } /// Types a dataset's Text columns from their values (see [`text_type`]), for readers whose @@ -3657,10 +3686,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`. @@ -3688,12 +3715,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 @@ -3752,8 +3781,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 { @@ -3769,31 +3802,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 @@ -5281,7 +5350,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); @@ -5768,14 +5837,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 }; @@ -6314,7 +6386,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 } } } @@ -6441,8 +6513,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); @@ -6452,15 +6524,31 @@ 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; { 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 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 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) + { + 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) => { w.write_shape_and_record(&pt(c), &record(f)).map_err(fmt)?; @@ -6468,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 { @@ -6540,6 +6632,55 @@ 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 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 { + 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, then its content. + Some(8 + 4 + content) +} + fn is_outer

(r: &shapefile::PolygonRing

) -> bool { matches!(r, shapefile::PolygonRing::Outer(_)) } @@ -6599,6 +6740,109 @@ 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: 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 = |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 + }; + 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 [ + // 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(); + assert_eq!(parts, unlimited, "{max}"); + } + } + + /// 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..0d1e830122 --- /dev/null +++ b/crates/data/tests/large_value_memory.rs @@ -0,0 +1,163 @@ +//! 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, GeometryType, 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 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(); + 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) +} + +/// [`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)]); + 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); + // 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| { + 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()), + ("CSV number cell", "csv", None, "note", number()), + ] { + 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()), + ("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(); + }); + 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); + } + + // 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); + 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:#?}"); +}