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
37 changes: 29 additions & 8 deletions crates/data/src/dbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,21 +148,35 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No
if let Some(encoding) = DbfEncoding::from_name(label) {
return encoding;
}
notes.push("Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable");
}
// A `.cpg` that can't be used: the file's own language driver gives the encoding, and then
// nothing is assumed; without one it is UTF-8, assumed. One that names a code page RustGIS
// can't read is said below, as assumed, on its own.
let page = (ldid != 0).then(|| ldid_code_page(ldid)).flatten();
let resolved = page.and_then(DbfEncoding::from_number);
if cpg.is_some() {
let text = "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable";
notes.push(if ldid == 0 {
crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text)
} else {
crate::loss::Note::plain(text)
});
}
// No language driver: UTF-8, as it always was, without a note.
if ldid == 0 {
return DbfEncoding::Utf8;
}
let page = ldid_code_page(ldid);
if let Some(encoding) = page.and_then(DbfEncoding::from_number) {
if let Some(encoding) = resolved {
return encoding;
}
let named = page.map_or_else(String::new, |p| match page_name(p) {
Some(name) => format!(" (code page {p}, {name})"),
None => format!(" (code page {p})"),
});
notes.push(format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"));
notes.push(crate::loss::Note::loss(
crate::loss::LossCode::AssumedEncoding,
format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"),
));
DbfEncoding::Utf8
}

Expand Down Expand Up @@ -422,8 +436,10 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) -
match try_read_cpg(path) {
Ok(bytes) => bytes,
Err(e) => {
notes.push(format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable"));
None
// Why it can't be used; what the encoding falls back to, and whether that is assumed,
// is said with the `.dbf`'s code page in hand ([`encoding`]), as for one that can't be.
notes.push(crate::loss::Note::plain(format!("could not read the .cpg ({e})")));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A .cpg that can't be read now comes back as Some(Vec::new()), so encoding() also runs its ".cpg present" branch. Two things follow:

  1. The note there (dbf.rs:158, "unsupported or empty .cpg") says "empty" for a file that couldn't be read. With a .dbf language driver of 0 the user gets two notes for one fault: the plain "could not read the .cpg" and then the coded "unsupported or empty .cpg".
  2. No test covers this path. encoding_assumed in shapefile_encoding.rs only checks notes containing "; using ", so it skips the "could not read" note entirely. A .cpg path that is a directory should make the read fail on Linux, which gives a test without a fixture file.

Suggest a test for both cases (driver 0 gives assumed.encoding; a supported driver gives a plain note) and a separate wording for a read failure. The earlier thread was resolved by the fallback wording, so this is about the message and the missing test, not the code path.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right on both: an unreadable .cpg gives the plain read failure and then the "unsupported or empty" fallback, and no test reaches it. Wording each case apart and a test with a .cpg that is a directory are left for the release quality pass.

Some(Vec::new())
}
}
}
Expand Down Expand Up @@ -585,10 +601,15 @@ mod tests {
fn a_page_rustgis_cant_decode_is_named_in_the_note() {
let mut notes = crate::loss::Notes::new();
assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8));
assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]);
assert_eq!(
notes.texts().collect::<Vec<_>>(),
["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]
);
assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding));
let mut notes = crate::loss::Notes::new();
encoding(None, 0xFF, &mut notes);
assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]);
assert_eq!(notes.texts().collect::<Vec<_>>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]);
assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding));
}

/// Text is read as UTF-8 unless another encoding is named, with none named, with UTF-8 named
Expand Down
251 changes: 211 additions & 40 deletions crates/data/src/dxf.rs

Large diffs are not rendered by default.

85 changes: 76 additions & 9 deletions crates/data/src/esripbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ pub struct Losses {
pub with_zm: usize,
/// Places that convert to beyond longitude/latitude (the answer's system may not fit them).
pub beyond: usize,
/// The coordinate system code an answer with features with a geometry names and RustGIS
/// can't use, without a WKT (read as longitude/latitude).
pub unusable_code: Option<u32>,
/// Pages joined after the first that named another code RustGIS can't use.
pub other_unusable: usize,
}

impl Losses {
Expand All @@ -152,6 +157,23 @@ impl Losses {
self.unprojected = self.unprojected.saturating_add(other.unprojected);
self.with_zm = self.with_zm.saturating_add(other.with_zm);
self.beyond = self.beyond.saturating_add(other.beyond);
match (self.unusable_code, other.unusable_code) {
(Some(a), Some(b)) if a != b => self.other_unusable += 1 + other.other_unusable,
(None, b) => {
self.unusable_code = b;
self.other_unusable += other.other_unusable;
}
_ => self.other_unusable += other.other_unusable,
}
}

/// The pages that named another code RustGIS can't use, as the notice for the first adds them.
pub fn others_said(&self) -> String {
match self.other_unusable {
0 => String::new(),
1 => " (and another page names a code it can't use either)".to_string(),
n => format!(" (and {n} other pages name codes it can't use either)"),
}
}

/// What they say, one message per kind (as [`read`] says them).
Expand All @@ -163,17 +185,33 @@ impl Losses {
"the answer names no coordinate system; coordinates are read as longitude/latitude",
));
}
// Said only when a geometry was read in it: assumed, then.
if let Some(code) = self.unusable_code {
out.push(crate::loss::Note::loss(
crate::loss::LossCode::AssumedCrs,
format!("coordinate system {code} can't be used{}; coordinates are read as longitude/latitude", self.others_said()),
));
}
if self.unreadable > 0 {
out.push(format!("{} values don't fit their field's type and are left empty", self.unreadable));
out.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{} values don't fit their field's type and are left empty", self.unreadable),
));
}
if self.not_utf8 > 0 {
out.push(format!(
"{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD",
self.not_utf8
out.push(crate::loss::Note::loss(
crate::loss::LossCode::ChangedEncoding,
format!(
"{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD",
self.not_utf8
),
));
}
if self.flat_rings > 0 {
out.push(format!("{} polygon rings have no area and are left out", self.flat_rings));
out.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedRing,
format!("{} polygon rings have no area and are left out", self.flat_rings),
));
}
if self.unprojected > 0 {
out.push(format!(
Expand Down Expand Up @@ -319,10 +357,16 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
fields.push(Field { name, ty: read_as.field_type(), alias });
}
if repeated > 0 {
report.messages.push(format!("{repeated} fields repeat an earlier field's name and are left out"));
report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{repeated} fields repeat an earlier field's name and are left out"),
));
}
if not_read > 0 {
report.messages.push(format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out"));
report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out"),
));
}
if unknown > 0 {
report.messages.push(format!("{unknown} fields have a type RustGIS doesn't know; their values are read as text"));
Expand All @@ -335,6 +379,9 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
// read in its place. If the replaced bytes break the WKT, it can't be told whether the WKT
// would have won, so that's said too. The WKT is looked at only when it isn't UTF-8, as this
// runs for every page.
// What reading the system says (its WKT's text, and what it assumes) holds only for a
// geometry read in it.
let said_before = report.messages.len();
if !wkt_utf8
&& (code.and_then(crs_of_code).is_none()
|| esri_wkt_over_code(code, wkt.as_deref()).is_some()
Expand All @@ -345,22 +392,25 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
"the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD",
));
}
let said_before = report.messages.len();
let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?;
// What reading the system said, which assumes a system only for a geometry read in it.
let crs_said = said_before..report.messages.len();
// A WKT that couldn't be read (or converted) is read as longitude/latitude, and said so;
// a geographic one gives no system and says nothing.
let mut unread_code = crs.is_none()
&& report
.messages
.get(said_before..)
.is_some_and(|m| m.iter().any(|m| m.ends_with("; coordinates are read as longitude/latitude")));
// Said with the page's losses, once it is known that a geometry was read in it.
let mut unusable_code = None;
if crs.is_none()
&& wkt.is_none()
&& let Some(code) = code
&& crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat)
{
unread_code = true;
report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude"));
unusable_code = Some(code);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes a page with no geometry silent about an unusable code. unusable_code is kept only for a page with geometry (.filter(|_| any_geometry) further down), so an answer that names an unusable code and has no features now says nothing. The base branch pushed a plain note there. Nothing is lost in that case, so this is a consistency point, not a data-loss bug.

The two no-geometry cases now behave differently. An unreadable WKT on a page with no geometry keeps its note as plain (an_unreadable_wkt_is_assumed_only_with_a_geometry asserts [None]), and the unusable code does not. The comment above the demotion block says "said, not as assumed", and the test at esripbf/tests.rs (an_unknown_coordinate_system_is_said, the no-geometry block) pins silence. Pick one: keep a plain note for the code path as the WKT path does, or say in the doc that a page without geometry places nothing and is silent by design, and make the comment match.

Confidence: medium on the intent, high that the comments and the two paths disagree.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made the comment match: a page without geometry places nothing in the code it names, so it says nothing of the code (the test pins that), while a WKT it can't read is still said plainly as what the answer holds. Silent is intended here: an answer of rows alone is read with no system at all.

}

let layer_type = match shape_kind {
Expand Down Expand Up @@ -398,10 +448,27 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
ds.held_in = c;
}
// An answer without a geometry places nothing in the system it couldn't read: said, not as
// assumed.
if !any_geometry && !crs_said.is_empty() {
let said = std::mem::replace(&mut report.messages, crate::loss::Notes::new());
for (i, mut note) in said.into_iter().enumerate() {
if crs_said.contains(&i)
&& matches!(note.loss, Some(crate::loss::LossCode::AssumedCrs | crate::loss::LossCode::ChangedEncoding))
{
note.loss = None;
}
report.messages.push(note);
}
}
let losses = Losses {
// Assumed, so said: an answer that names no coordinate system.
no_crs: any_geometry && code.is_none() && wkt.is_none(),
unread_code: any_geometry && unread_code,
// A page without geometry places nothing in the code it names, so says nothing of it,
// unlike a WKT it can't read, which is said (plainly) as what the answer holds.
unusable_code: unusable_code.filter(|_| any_geometry),
other_unusable: 0,
unreadable: tally.unreadable,
not_utf8: tally.not_utf8,
flat_rings: tally.flat_rings,
Expand Down
62 changes: 56 additions & 6 deletions crates/data/src/esripbf/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ fn a_ring_without_area_is_left_out_and_said() {
let (ds, report) = read(&bytes, "t").unwrap();
let Some(Geometry::Polygon(polygons)) = &ds.features[0].geometry else { panic!("not a polygon") };
assert_eq!(polygons.len(), 1);
assert_eq!(report.messages, ["1 polygon rings have no area and are left out"]);
assert_eq!(report.messages.texts().collect::<Vec<_>>(), ["1 polygon rings have no area and are left out"]);
assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedRing));
}

#[test]
Expand Down Expand Up @@ -237,6 +238,11 @@ fn an_unknown_coordinate_system_is_said() {
report.messages.texts().collect::<Vec<_>>(),
["coordinate system 999999 can't be used; coordinates are read as longitude/latitude"]
);
assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::AssumedCrs));
// An answer with no geometry places nothing in it: nothing assumed, nothing said.
let rows = answer(&[message(8, &number(1, 999_999)), transform(false, 1.0, 0.0, 0.0), feature(&[])]);
let (_, report) = read(&rows, "t").unwrap();
assert!(!report.messages.iter().any(|m| m.contains("can't be used")), "{:?}", report.messages);
}

#[test]
Expand Down Expand Up @@ -286,8 +292,9 @@ fn text_that_isnt_utf8_is_read_with_replacements_and_said() {
assert_eq!(ds.fields[0].name, "N\u{FFFD}AME");
assert_eq!(ds.features[0].attrs, [Value::Text("a\u{FFFD}b".into())]);
assert_eq!(ds.features[1].attrs, [Value::Text("ok".into())]);
assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding));
assert_eq!(
report.messages,
report.messages.texts().collect::<Vec<_>>(),
["2 values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"]
);
}
Expand Down Expand Up @@ -317,13 +324,14 @@ fn repeated_names_and_unread_field_types_are_left_out_and_said() {
assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["NAME", "COUNT"]);
assert_eq!(ds.features[0].attrs, [Value::Text("a".into()), Value::Null]);
assert_eq!(
report.messages,
report.messages.texts().collect::<Vec<_>>(),
[
"1 fields repeat an earlier field's name and are left out",
"1 fields hold geometries, blobs or rasters, which aren't read, and are left out",
"1 values don't fit their field's type and are left empty",
]
);
assert!(report.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedValue)), "{:?}", report.messages);
// A table: no geometry type, no geometry.
assert_eq!(ds.geometry_type, GeometryType::None);
}
Expand Down Expand Up @@ -445,6 +453,20 @@ fn lengths_in_several_fields_keep_their_order() {
assert!(report.messages.is_empty(), "{:?}", report.messages);
}

/// A WKT RustGIS can't read is assumed to be longitude/latitude only for an answer with a
/// geometry read in it: one without places nothing there.
#[test]
fn an_unreadable_wkt_is_assumed_only_with_a_geometry() {
let wkt: &[u8] = b"PROJCS[\"nonsense\"]";
let assumed = |features: &[u8]| {
let bytes = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), features.to_vec()]);
let (_, report) = read(&bytes, "t").unwrap();
report.messages.iter().filter(|m| m.contains("read as longitude/latitude")).map(|m| m.loss).collect::<Vec<_>>()
};
assert_eq!(assumed(&feature(&[geometry(&[], &[1, 2])])), [Some(crate::loss::LossCode::AssumedCrs)]);
assert_eq!(assumed(&feature(&[])), [None]);
}

#[test]
fn a_wkt_that_isnt_utf8_is_said() {
let wkt = b"GEOGCS[\"GCS_WGS_1984\xff\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]";
Expand All @@ -454,6 +476,11 @@ fn a_wkt_that_isnt_utf8_is_said() {
report.messages.first().map(|m| m.as_str()),
Some("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD")
);
assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding));
// On a page with no geometry, nothing is placed in the system: said, without a code.
let rows = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), feature(&[])]);
let (_, report) = read(&rows, "t").unwrap();
assert_eq!(report.messages.first().map(|m| m.loss), Some(None), "{:?}", report.messages);
// Unused when a code RustGIS knows names the system: nothing to say.
let with_code = answer(&[
message(8, &[number(1, 4326), message(5, wkt)].concat()),
Expand Down Expand Up @@ -704,7 +731,7 @@ fn a_repeated_field_of_an_unknown_type_is_only_said_left_out() {
let bytes = answer(&[field("NAME", 4), field("name", 17), feature(&[text("a"), uint(5)])]);
let (ds, report) = read(&bytes, "t").unwrap();
assert_eq!(ds.fields.len(), 1);
assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]);
assert_eq!(report.messages.texts().collect::<Vec<_>>(), ["1 fields repeat an earlier field's name and are left out"]);
}

#[test]
Expand All @@ -713,10 +740,13 @@ fn a_left_out_field_whose_name_isnt_utf8_is_only_said_left_out() {
let repeat = message(13, &[message(1, b"N\xffame"), number(2, 4)].concat());
let bytes = answer(&[field("N\u{FFFD}AME", 4), repeat, feature(&[text("a"), text("b")])]);
let (_, report) = read(&bytes, "t").unwrap();
assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]);
assert_eq!(report.messages.texts().collect::<Vec<_>>(), ["1 fields repeat an earlier field's name and are left out"]);
let geometry = message(13, &[message(1, b"G\xff"), number(2, 7)].concat());
let (_, report) = read(&answer(&[field("NAME", 4), geometry, feature(&[text("a")])]), "t").unwrap();
assert_eq!(report.messages, ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"]);
assert_eq!(
report.messages.texts().collect::<Vec<_>>(),
["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"]
);
}

#[test]
Expand Down Expand Up @@ -769,3 +799,23 @@ fn a_wkt_is_taken_from_the_text_room_at_its_size_once_read() {
assert!(spatial_reference(&reference, &mut Tally { text_room: 13, ..Tally::default() }).is_err());
assert!(spatial_reference(&reference, &mut Tally { text_room: 14, ..Tally::default() }).is_ok());
}

/// Pages joined that name different codes RustGIS can't use say the first and how many others,
/// so every page's assumption is said; the same code again adds nothing.
#[test]
fn joined_pages_say_every_unusable_code() {
let page = |code| Losses { unusable_code: Some(code), ..Losses::default() };
let mut all = page(999_999);
all.add(&page(999_999));
all.add(&page(888_888));
all.add(&page(777_777));
let said: Vec<_> = all.messages().iter().map(|m| (m.as_str().to_string(), m.loss)).collect();
assert_eq!(
said,
[(
"coordinate system 999999 can't be used (and 2 other pages name codes it can't use either); coordinates are read as longitude/latitude"
.to_string(),
Some(crate::loss::LossCode::AssumedCrs)
)]
);
}
14 changes: 10 additions & 4 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2922,12 +2922,18 @@ pub(crate) fn read_rows(
// so its row has no geometry, said here.
if let Some(w) = wkt {
let column = headers.get(w).map_or("", |h| h.trim());
// The values read as empty, below the heading: each a value lost, and with it its row's
// geometry.
match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) {
0 => {}
1 => report.messages.push(format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry")),
n => report
.messages
.push(format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry")),
1 => report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry, or is left out if it held nothing else"),
)),
n => report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry, or are left out if they held nothing else"),
)),
}
}
let (mut bad_wkt, mut zm_rows, mut collection_rows) = (0usize, 0usize, 0usize);
Expand Down
Loading
Loading