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
4 changes: 2 additions & 2 deletions crates/data/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,8 @@ fn leap(y: i64) -> bool {
(y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}

/// The days in a month of the proleptic Gregorian calendar.
pub(crate) fn days_in_month(y: i64, m: i64) -> i64 {
/// The days in a month (1 to 12) of the proleptic Gregorian calendar; 31 for another month.
pub fn days_in_month(y: i64, m: i64) -> i64 {
match m {
2 if leap(y) => 29,
2 => 28,
Expand Down
24 changes: 23 additions & 1 deletion crates/data/src/dbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,28 @@ fn retype_columns(dbf: &mut [u8], from: u8, to: u8) -> Vec<usize> {
changed
}

/// The records of a `.dbf` marked deleted (`*`), by their position, with their marks cleared so
/// dBASE's reader gives every record the header counts, one for each shape: it passes over a
/// deleted record, which would pair every later shape with the next record. Only the records the
/// header counts that the file holds are looked at.
pub(crate) fn take_deleted(dbf: &mut [u8]) -> Vec<usize> {
let le16 = |at: usize| Some(usize::from(u16::from_le_bytes([*dbf.get(at)?, *dbf.get(at + 1)?])));
let (Some(header_len), Some(record_len)) = (le16(8), le16(10)) else { return Vec::new() };
let count = dbf.get(4..8).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, u32::from_le_bytes);
if record_len == 0 {
return Vec::new();
}
let Some(body) = dbf.get_mut(header_len..) else { return Vec::new() };
let mut deleted = Vec::new();
for (k, record) in body.chunks_exact_mut(record_len).take(usize::try_from(count).unwrap_or(usize::MAX)).enumerate() {
if let Some(flag) = record.first_mut().filter(|f| **f == b'*') {
*flag = b' ';
deleted.push(k);
}
}
deleted
}

/// A column of a `.dbf` as its header describes it: its name's bytes (up to the first NUL),
/// type letter, length in bytes and decimals.
#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -381,7 +403,7 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut Vec<String>) -> Optio
match try_read_cpg(path) {
Ok(bytes) => bytes,
Err(e) => {
notes.push(format!("Shapefile: could not read .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable"));
notes.push(format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable"));
Comment thread
giswqs marked this conversation as resolved.
Resolved
None
}
}
Expand Down
352 changes: 329 additions & 23 deletions crates/data/src/io.rs

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,9 @@ impl Features {
}
}

/// Appends a row with the id one past the largest. `max_id` stays right only because every
/// other change to `rows` goes through `DerefMut`, which clears it.
/// Appends a row with the id one past the largest. `max_id` stays right because every change
/// that removes or reorders rows clears it (`DerefMut`, `remove_row`, `retain_rows`,
/// `truncate_rows`), and the pushes keep it.
fn push_with_new_id(&mut self, geometry: Option<Geometry>, attrs: Vec<Value>) {
let max = self.max_id.unwrap_or_else(|| self.rows.iter().map(|f| f.id).max().unwrap_or(0));
let id = max.saturating_add(1);
Expand Down
10 changes: 6 additions & 4 deletions crates/data/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//!
//! On the desktop a memory limit plans for a share of the physical memory ([`SHARE`]): never below
//! the fixed value it had before (its floor, still the browser's limit), never above a ceiling. A
//! container's memory limit counts, when it is lower. The memory is read once, at the first limit
//! control-group limit (a container's, or a service's such as systemd's `MemoryMax`) counts, when
//! it is lower. The memory is read once, at the first limit
//! asked for; [`scaled`] takes it as an argument, so tests pass fixed amounts. Most limits plan for
//! what is left once the process holds more than half the memory ([`planned`], #2431 fix 3), so
//! they can be lower later in a session, never below their floors.
Expand All @@ -26,7 +27,8 @@ pub fn physical() -> Option<u64> {
}

/// Where [`physical`]'s figure came from: `"override"` ([`OVERRIDE`]), `"container"` (a
/// container's limit, lower than the computer's memory), `"computer"`, or `"unknown"` (the browser,
/// control-group limit, a container's or a service's such as systemd's `MemoryMax`, lower than
/// the computer's memory), `"computer"`, or `"unknown"` (the browser,
/// a fuzzing build, or memory that couldn't be read), so a leftover override doesn't change the
/// limits unnoticed.
pub fn source() -> &'static str {
Expand Down Expand Up @@ -59,8 +61,8 @@ fn overridden(value: Option<&str>) -> Option<u64> {
value?.trim().parse::<u64>().ok().filter(|m| *m > 0)
}

/// The memory to plan for: the override when it is set, else physical memory, or a container's
/// limit when that is lower.
/// The memory to plan for: the override when it is set, else physical memory, or a control-group
/// limit (a container's, or a service's such as systemd's `MemoryMax`) when that is lower.
#[cfg(all(not(fuzzing), not(target_arch = "wasm32")))]
fn read() -> (Option<u64>, &'static str) {
if let Some(m) = overridden(std::env::var(OVERRIDE).ok().as_deref()) {
Expand Down
7 changes: 5 additions & 2 deletions crates/data/src/ogc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,8 @@ pub const MAX_LISTED_LAYERS: usize = 2_000;
const MAX_READ_LAYERS: usize = if cfg!(test) { 3_000 } else { 100_000 };
/// Most bytes of a document's own request addresses (its GetMap's, GetFeature's…) copied into
/// its layers together: each layer's address repeats them, so long ones lower how many are read.
const MAX_COPIED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { 64 << 20 };
/// The same budget bounds the document addresses a listing repeats (`service.layers`).
pub const MAX_COPIED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { 64 << 20 };

/// How many layers are read from a document whose layers each copy `per_layer` bytes of its
/// request addresses: [`MAX_READ_LAYERS`], fewer for long addresses, at least one. (Fewer than
Expand Down Expand Up @@ -3879,7 +3880,9 @@ impl Pages {
&& !matches!(self.phase, Phase::Offsets { pbf: true, .. })
&& query_value(&self.url, "where").is_some_and(|w| !w.eq_ignore_ascii_case("1%3D1") && w != "1=1")
{
return Step::Failed(self.page_failure(&format!("the server rejected the query with its where clause: {error}")));
return Step::Failed(
self.page_failure(&format!("the server rejected the query (its where clause or area may be the cause): {error}")),
);
}
}
if matches!(self.phase, Phase::Offsets { pbf: true, .. }) {
Expand Down
26 changes: 21 additions & 5 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,10 @@ fn read_layout(r: Sparse) -> Result<Parse> {
let mut index = 0usize;
let mut allowance = MAX_TOTAL_TILES;
// Overviews left out for a sample count other than the full image's (its tag's, which a
// JPEG YCbCr image's decoded bands may differ from), and how many.
// JPEG YCbCr image's decoded bands may differ from), or another alpha role for the sample past
// the colour ones (an RGBA overview of an RGBI image would show its NIR as alpha), and how many.
let full_samples = dec.find_tag_unsigned::<u16>(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1);
let full_alpha = super::geotiff::extra_alpha(&mut dec);
let mut mismatched: Vec<String> = Vec::new();
let mut mismatched_count = 0usize;
// Images no smaller than the full image in both width and height (not overviews), and how many.
Expand Down Expand Up @@ -483,6 +485,7 @@ fn read_layout(r: Sparse) -> Result<Parse> {
// passed over too. All are said, and skipped before a tile size is checked or their
// tiles count against the budget.
let samples = dec.find_tag_unsigned::<u16>(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1);
let alpha = super::geotiff::extra_alpha(&mut dec);
let passed = match levels.first().map(|l| (l.width, l.height)) {
// The full image itself.
None => false,
Expand All @@ -493,10 +496,17 @@ fn read_layout(r: Sparse) -> Result<Parse> {
}
true
}
Some(_) if samples != full_samples => {
Some(_) if samples != full_samples || alpha != full_alpha => {
mismatched_count += 1;
if mismatched.len() < 5 {
mismatched.push(format!("image {index} ({samples})"));
let role = if alpha == full_alpha {
""
} else if alpha {
", with alpha"
} else {
", without alpha"
};
mismatched.push(format!("image {index} ({samples}{role})"));
}
true
}
Expand Down Expand Up @@ -556,7 +566,12 @@ fn read_layout(r: Sparse) -> Result<Parse> {
counts.truncate(n);
levels.push(Level { ifd: index, width: w, height: h, tile_width: tw, tile_height: th, offsets, counts });
}
if levels.len() >= MAX_LEVELS || !dec.more_images() {
if !dec.more_images() {
break;
}
// Sorted below, so a file storing its overviews smallest first loses its finest: said.
if levels.len() >= MAX_LEVELS {
lost.push(format!("the scan for overviews stopped at {MAX_LEVELS} levels: later images aren't read"));
break;
}
dec.next_image().map_err(err)?;
Expand All @@ -577,7 +592,8 @@ fn read_layout(r: Sparse) -> Result<Parse> {
if mismatched_count > 0 {
let more = if mismatched_count > mismatched.len() { ", …" } else { "" };
lost.push(format!(
"{mismatched_count} overview(s) with samples per pixel other than the full image's {full_samples} are left out: {}{more}",
"{mismatched_count} overview(s) with samples per pixel or an alpha sample other than the full image's ({full_samples}{}) are left out: {}{more}",
if full_alpha { ", with alpha" } else { "" },
mismatched.join(", ")
));
}
Expand Down
81 changes: 70 additions & 11 deletions crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,6 +1466,7 @@ pub(super) fn read_limited_with_nodata(
Err(e) => (None, Some(format!("its Copyright tag: it can't be read ({e}), so it is left out"))),
};
let spp = samples(&mut dec);
let full_alpha = extra_alpha(&mut dec);
let bytes = sample_bytes(&mut dec);
// The decoded image is held at its own pixel size before conversion to f32, so bound bytes
// as well as samples.
Expand Down Expand Up @@ -1495,9 +1496,14 @@ pub(super) fn read_limited_with_nodata(
}
let Ok((ow, oh)) = dec.dimensions() else { continue };
let (ospp, obytes) = (samples(&mut dec), sample_bytes(&mut dec));
// An overview with another sample count (three of an RGBI image's four) would read
// as another kind of image: the full image is read sparsely instead.
if ospp == spp && fits(ow, oh, ospp, obytes) && best.is_none_or(|(_, bw, bh)| ow as u64 * oh as u64 > bw as u64 * bh as u64) {
// An overview with another sample count (three of an RGBI image's four), or another
// alpha role for the sample past the colour ones (an RGBA overview of an RGBI image),
// would read as another kind of image: the full image is read sparsely instead.
if ospp == spp
&& extra_alpha(&mut dec) == full_alpha
&& fits(ow, oh, ospp, obytes)
&& best.is_none_or(|(_, bw, bh)| ow as u64 * oh as u64 > bw as u64 * bh as u64)
{
best = Some((index, ow, oh));
}
}
Expand Down Expand Up @@ -1928,8 +1934,10 @@ pub fn write(r: &Raster, band: usize) -> Result<Vec<u8>> {
}

/// Writes every band of a raster, for a layer whose pixels the project keeps: as [`write`] does
/// when that keeps them all, otherwise as 32-bit float samples (RGB first for a colour raster,
/// and alpha after them when it has one), which [`read`] reads back as the same bands.
/// when that keeps them all. Otherwise: 8-bit samples when the raster is `UInt8` and every valid
/// value is a whole number in 0–255 (an empty cell only where no-data can mark it), else 32-bit
Comment thread
giswqs marked this conversation as resolved.
Resolved
/// float samples (RGB first for a colour raster, and alpha after them when it has one). [`read`]
/// reads them back as the same bands.
pub fn write_all(r: &Raster) -> Result<Vec<u8>> {
encode(r, 0, true)
}
Expand Down Expand Up @@ -3614,6 +3622,58 @@ mod tests {
}
}

/// Sets the ExtraSamples value of each image with one, in turn, of a file
/// [`rgb_tiled_samples`] wrote.
fn set_extra_samples(bytes: &mut [u8], values: &[u16]) {
// The tag's entry: 338, type 3 (short), count 1, the value 0 as written.
let entry = [0x52, 0x01, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0];
let at: Vec<usize> = (0..bytes.len().saturating_sub(12)).filter(|i| bytes[*i..*i + 12] == entry).collect();
assert_eq!(at.len(), values.len());
for (at, value) in at.iter().zip(values) {
bytes[at + 8..at + 10].copy_from_slice(&value.to_le_bytes());
}
}

/// An overview with the full image's sample count but another alpha role (an RGBA overview of
/// an RGBI image, or the reverse) is left out and said, not decoded with the full image's
/// colour layout; one with the same role is a level, with nothing said.
#[test]
fn cog_overviews_require_a_matching_alpha_sample() {
use super::super::cog::{self, Parse, Sparse};
for (full, overview) in [(0, 0), (2, 2), (0, 2), (2, 0)] {
let mut bytes = rgb_tiled_samples(&[(40, 16, 4), (20, 16, 4)], 8, 1, |b, x, y| (b * 10 + x + y) as u16);
set_extra_samples(&mut bytes, &[full, overview]);
let whole = Sparse::default().with_len(bytes.len() as u64).with(0, bytes);
let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") };
let said: Vec<_> = layout.lost.iter().filter(|n| n.contains("overview(s)")).collect();
if full == overview {
assert_eq!(layout.levels.len(), 2);
assert!(said.is_empty(), "{:?}", layout.lost);
} else {
assert_eq!(layout.levels.len(), 1);
let role = if overview == 2 { "image 1 (4, with alpha)" } else { "image 1 (4, without alpha)" };
assert!(said.len() == 1 && said[0].contains("an alpha sample") && said[0].contains(role), "{:?}", layout.lost);
}
}
}

/// The scan stops at its most levels, and says so when the file holds more images; a file
/// with fewer says nothing of it.
#[test]
fn cog_says_when_it_stops_at_its_most_levels() {
use super::super::cog::{self, Parse, Sparse};
const STOPPED: &str = "the scan for overviews stopped at 32 levels";
for (images, cut) in [(32u32, false), (33, true)] {
// The full image 64 wide, its overviews 63, 62, … wide, smallest last.
let sizes: Vec<(u32, u32, u16)> = (0..images).map(|k| (64 - k, 16, 3)).collect();
let bytes = rgb_tiled_samples(&sizes, 8, 1, |b, x, y| (b + x + y) as u16);
let whole = Sparse::default().with_len(bytes.len() as u64).with(0, bytes);
let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") };
assert_eq!(layout.levels.len(), 32.min(images as usize));
assert_eq!(layout.lost.iter().any(|n| n.contains(STOPPED)), cut, "{:?}", layout.lost);
}
}

#[test]
fn cog_overviews_require_matching_sample_counts() {
use super::super::cog::{self, Parse, Sparse};
Expand All @@ -3631,11 +3691,9 @@ mod tests {
let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") };
assert_eq!((layout.levels.len(), layout.bands), (1, usize::from(full)));
assert!(
layout
.lost
.iter()
.any(|n| n.contains(&format!("1 overview(s) with samples per pixel other than the full image's {full}"))
&& n.contains(&format!("image 1 ({overview})"))),
layout.lost.iter().any(|n| n.contains(&format!(
"1 overview(s) with samples per pixel or an alpha sample other than the full image's ({full})"
)) && n.contains(&format!("image 1 ({overview})"))),
"{:?}",
layout.lost
);
Expand All @@ -3652,7 +3710,8 @@ mod tests {
layout
.lost
.iter()
.any(|n| n.contains("1 overview(s) with samples per pixel other than the full image's 4") && n.contains("image 2 (3)")),
.any(|n| n.contains("1 overview(s) with samples per pixel or an alpha sample other than the full image's (4)")
&& n.contains("image 2 (3)")),
"{:?}",
layout.lost
);
Expand Down
4 changes: 3 additions & 1 deletion crates/data/src/raster/wkt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2400,7 +2400,9 @@ const ELLIPSOIDS: &[(&str, &str, f64)] = &[
("sphere", "Sphere", 0.0),
];

/// The radius of the sphere with the area of the ellipsoid of axes `a` and `b` (PROJ's `+R_A`).
/// The radius of the sphere with the area of the ellipsoid of axes `a` and `b` (PROJ's `+R_A`):
/// `a √(q_p / 2)`, with `q_p` the authalic `q` at the pole, as in Snyder, *Map Projections: A
/// Working Manual*, USGS Professional Paper 1395 (1987), for the radius of the authalic sphere.
fn authalic_radius(a: f64, b: f64) -> f64 {
let e2 = 1.0 - (b / a).powi(2);
let e = e2.sqrt();
Expand Down
3 changes: 2 additions & 1 deletion crates/data/src/raster/zarr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2324,7 +2324,8 @@ fn grid_axes(store: &Store, a: &Array, chunks: &HashMap<String, Vec<u8>>) -> Res

/// The chunk keys of `variable`'s map coordinates, for [`window_of`]: each is read whole (its
/// first [`MAX_CHUNKS`] chunks, as any coordinate), so longer ones than [`MAX_COORDS`] can't place
/// a box (a window is given in cells instead). None for a grid its `spatial:transform` places.
/// a box (a window is given in cells instead). Empty for a grid its `spatial:transform` places
/// (a box is placed by arithmetic).
pub fn window_keys(store: &Store, variable: &str) -> Result<Vec<String>> {
let a = store.array(variable).ok_or_else(|| bad(format!("no variable named {variable}")))?;
// A grid placed by its spatial:transform places a box by arithmetic, however long its axes.
Expand Down
Loading
Loading