Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/data/src/capped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ impl Limit {
self.passed.load(Ordering::Relaxed)
}

/// The file `write` makes in a buffer held to this limit: refused as soon as it would pass
/// it, whatever `write` makes of the refused write.
pub fn file(&self, write: impl FnOnce(&mut dyn Write) -> Result<()>) -> Result<Vec<u8>> {
let mut out = self.buffer();
let made = write(&mut out);
self.whole(made.map(|()| out.into_inner()))
}

/// Whether there is a limit to pass: false for [`Limit::none`].
pub(crate) fn bounded(&self) -> bool {
self.max != usize::MAX
Expand Down
35 changes: 20 additions & 15 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1116,7 +1116,7 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R
"kmz" => {
crate::interop::write_kml(ds, name_field(ds), &mut out)?;
let kml = out.into_inner();
(zipped(&[("doc.kml".to_string(), kml)], limit)?, without_geometry(ds))
(crate::zip::write_within(&[("doc.kml".to_string(), kml)], limit)?, without_geometry(ds))
}
"gpx" => {
crate::interop::write_gpx(ds, name_field(ds), &mut out)?;
Expand All @@ -1128,25 +1128,14 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R
ds.name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '_' }).collect();
let base = if base.trim().is_empty() { "layer".to_string() } else { base };
let entries: Vec<(String, Vec<u8>)> = parts.into_iter().map(|(e, b)| (format!("{base}.{e}"), b)).collect();
(zipped(&entries, limit)?, left_out)
(crate::zip::write_within(&entries, limit)?, left_out)
}
other => return Err(DataError::Unsupported(other.to_string())),
})
})();
limit.whole(made)
}

/// 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.
fn zipped(entries: &[(String, Vec<u8>)], limit: &Limit) -> Result<Vec<u8>> {
let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum();
let _parts = limit.hold(parts)?;
let mut out = limit.buffer();
let made = crate::zip::write_to(entries, &mut out).map_err(DataError::Format);
limit.whole(made.map(|()| out.into_inner()))
}

/// The text `data.convert` makes of a dataset in longitude/latitude, in `format` (`geojson`,
/// `csv`, `kml`, `gpx`, else WKT in a CSV), within `limit`. KML and GPX name placemarks by the
/// field `name_field`.
Expand Down Expand Up @@ -2445,14 +2434,24 @@ pub fn to_geojson_text(ds: &Dataset) -> Result<String> {
}

/// [`to_geojson_text`]'s collection, written to `out`, buffered: its serializer writes a few
/// bytes at a time.
fn write_geojson(ds: &Dataset, out: &mut impl std::io::Write) -> Result<()> {
/// bytes at a time. The features are written as they are walked, so a sink that refuses a write
/// ([`crate::capped::Limit::file`]) stops it there.
pub fn write_geojson(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> {
let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?;
writer.write(&ds.features)?;
std::io::Write::flush(&mut writer.finish()?)?;
Ok(())
}

/// [`write_geojson`] for an OGC API Features `items` document, which also says how many features
/// it returns (`numberReturned`).
pub fn write_geojson_items(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> {
let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?;
writer.write(&ds.features)?;
std::io::Write::flush(&mut writer.finish_returning(ds.features.len())?)?;
Ok(())
}

/// A feature as a GeoJSON Feature, its attributes named by `fields`.
fn feature_to_geojson(fields: &[Field], feature: &crate::Feature) -> Json {
// Making a value can't fail: every key is text.
Expand Down Expand Up @@ -2538,6 +2537,12 @@ impl<W: std::io::Write> GeoJsonWriter<W> {
self.out.write_all(b"]}")?;
Ok(self.out)
}

/// [`GeoJsonWriter::finish`] with a `numberReturned` member of `returned`.
fn finish_returning(mut self, returned: usize) -> Result<W> {
write!(self.out, r#"],"numberReturned":{returned}}}"#)?;
Ok(self.out)
}
}

// ---------------------------------------------------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/row_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ impl Features {
self.rows.is_empty()
}

/// The memory the rows hold, their geometry, attribute text and spare capacity included.
pub fn held_bytes(&self) -> usize {
crate::source::chunk_memory::features_bytes(&self.rows)
}

/// Row `row`, if there is one.
pub fn row(&self, row: usize) -> Option<RowRef<'_>> {
self.rows.get(row).map(|row| RowRef { row })
Expand Down
148 changes: 112 additions & 36 deletions crates/data/src/zip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::io::{Seek, SeekFrom, Write};

use crate::capped::{PIECE, write_pieces};
use crate::capped::{Limit, 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;
Expand Down Expand Up @@ -45,51 +45,38 @@ pub fn write(entries: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> {
Ok(out.into_inner())
}

/// [`write`]'s archive of `entries` within `limit`: the entries, held already, 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.
pub fn write_within(entries: &[(String, Vec<u8>)], limit: &Limit) -> crate::Result<Vec<u8>> {
let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum();
let _parts = limit.hold(parts)?;
let mut out = limit.buffer();
let made = write_to(entries, &mut out).map_err(crate::DataError::Format);
limit.whole(made.map(|()| out.into_inner()))
}

/// [`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.
/// limit stops it there), the central directory too. Each entry is deflated into `out` a piece at
/// a time, so besides `out` it holds a few numbers for each entry, a piece and the compressor.
pub(crate) fn write_to(entries: &[(String, Vec<u8>)], 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())?;
// How much of the archive is written: where the next entry starts.
let mut written: usize = 0;
let mut central = Vec::new();
// What each entry's central record repeats of it.
let mut records = Vec::with_capacity(entries.len());
for (name, data) in entries {
let n = name.as_bytes();
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 offset = u32::try_from(written).map_err(|_| too_big())?;
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 {
h.extend_from_slice(&20u16.to_le_bytes()); // made by
}
h.extend_from_slice(&20u16.to_le_bytes()); // needed to extract
h.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 names
h.extend_from_slice(&method.to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // time
h.extend_from_slice(&0x21u16.to_le_bytes()); // date: 1980-01-01
h.extend_from_slice(&crc.to_le_bytes());
h.extend_from_slice(&body_len.to_le_bytes());
h.extend_from_slice(&data_len.to_le_bytes());
h.extend_from_slice(&name_len.to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // extra
if central {
h.extend_from_slice(&0u16.to_le_bytes()); // comment
h.extend_from_slice(&0u16.to_le_bytes()); // disk
h.extend_from_slice(&0u16.to_le_bytes()); // internal attributes
h.extend_from_slice(&0u32.to_le_bytes()); // external attributes
h.extend_from_slice(&offset.to_le_bytes());
}
h.extend_from_slice(n);
h
};
// 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);
let mut record = Record { method: 0, crc, body_len: 0, data_len, name_len, offset };
let local = record.header(n, false);
out.write_all(&local).map_err(failed)?;
let body_at = written.saturating_add(local.len()) as u64;
let (method, body_len) = match deflate_to(data, out).map_err(failed)? {
Expand All @@ -101,17 +88,25 @@ pub(crate) fn write_to(entries: &[(String, Vec<u8>)], out: &mut (impl Write + Se
(0, data.len())
}
};
let body_len_32 = u32::try_from(body_len).map_err(|_| too_big())?;
record.method = method;
record.body_len = 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.write_all(&record.header(n, false)).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));
records.push(record);
}
let cd_offset = u32::try_from(written).map_err(|_| too_big())?;
let cd_len = u32::try_from(central.len()).map_err(|_| too_big())?;
let mut end = central;
// A record at a time: a directory of many entries is never held apart from `out`.
let mut cd_size: usize = 0;
for ((name, _), record) in entries.iter().zip(&records) {
let central = record.header(name.as_bytes(), true);
out.write_all(&central).map_err(failed)?;
cd_size = cd_size.saturating_add(central.len());
}
let cd_len = u32::try_from(cd_size).map_err(|_| too_big())?;
let mut end = Vec::new();
end.extend_from_slice(&0x0605_4B50u32.to_le_bytes());
end.extend_from_slice(&[0, 0, 0, 0]);
end.extend_from_slice(&count.to_le_bytes());
Expand All @@ -122,6 +117,46 @@ pub(crate) fn write_to(entries: &[(String, Vec<u8>)], out: &mut (impl Write + Se
out.write_all(&end).map_err(failed)
}

/// An entry as its local header and its central record describe it.
struct Record {
method: u16,
crc: u32,
body_len: u32,
data_len: u32,
name_len: u16,
offset: u32,
}

impl Record {
/// The entry's central record, or its local header, followed by its name `n`.
fn header(&self, n: &[u8], central: bool) -> Vec<u8> {
let mut h = Vec::new();
h.extend_from_slice(&if central { 0x0201_4B50u32 } else { 0x0403_4B50 }.to_le_bytes());
if central {
h.extend_from_slice(&20u16.to_le_bytes()); // made by
}
h.extend_from_slice(&20u16.to_le_bytes()); // needed to extract
h.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 names
h.extend_from_slice(&self.method.to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // time
h.extend_from_slice(&0x21u16.to_le_bytes()); // date: 1980-01-01
h.extend_from_slice(&self.crc.to_le_bytes());
h.extend_from_slice(&self.body_len.to_le_bytes());
h.extend_from_slice(&self.data_len.to_le_bytes());
h.extend_from_slice(&self.name_len.to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // extra
if central {
h.extend_from_slice(&0u16.to_le_bytes()); // comment
h.extend_from_slice(&0u16.to_le_bytes()); // disk
h.extend_from_slice(&0u16.to_le_bytes()); // internal attributes
h.extend_from_slice(&0u32.to_le_bytes()); // external attributes
h.extend_from_slice(&self.offset.to_le_bytes());
}
h.extend_from_slice(n);
h
}
}

/// `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<Option<usize>> {
Expand Down Expand Up @@ -393,6 +428,47 @@ fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreads
mod tests {
use super::*;

/// An archive that notes the largest piece offered to it.
#[derive(Default)]
struct Pieces {
archive: std::io::Cursor<Vec<u8>>,
largest: usize,
}

impl Write for Pieces {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.largest = self.largest.max(bytes.len());
self.archive.write(bytes)
}

fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

impl Seek for Pieces {
fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
self.archive.seek(to)
}
}

/// Many small entries make a large central directory: it is handed to the output a record at
/// a time, so a limit on the output stops it there, and it is never held apart.
#[test]
fn the_central_directory_is_written_a_record_at_a_time() {
let entries: Vec<(String, Vec<u8>)> = (0..500).map(|i| (format!("entry-{i:04}"), vec![b'x'])).collect();
let mut out = Pieces::default();
write_to(&entries, &mut out).unwrap();
// A central record is 46 bytes and the 10 of its name; the directory is 28,000.
assert_eq!(out.largest, 46 + entries[0].0.len());
let archive = out.archive.into_inner();
assert_eq!(read(&archive).unwrap(), entries);
// Room for every entry and all but the last of the directory is refused.
let held: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum();
let limit = Limit::new(held + archive.len() - 1);
assert!(write_within(&entries, &limit).is_err() && limit.passed());
}

/// 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.
Expand Down
Loading
Loading