Skip to content
5 changes: 3 additions & 2 deletions crates/data/src/capped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,13 @@ impl Buffer<'_> {
Ok(())
}

/// The file made, its spare room given back, no longer counted against the limit.
/// The file made, no longer counted against the limit; a file held to a limit gives back its
/// spare room, one to be written keeps it until dropped (up to about twice its length).
pub fn into_inner(mut self) -> Vec<u8> {
let mut file = std::mem::take(&mut self.file);
// 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 {
if self.limit.bounded() {
file.shrink_to_fit();
}
self.release();
Expand Down
69 changes: 42 additions & 27 deletions crates/data/src/dbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No
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";
let text = "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 {
Expand All @@ -173,7 +173,7 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No
});
notes.push(crate::loss::Note::loss(
crate::loss::LossCode::AssumedEncoding,
format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"),
format!("unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"),
));
DbfEncoding::Utf8
}
Expand Down Expand Up @@ -215,7 +215,7 @@ pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option<c
let named: Vec<String> = columns.iter().take(5).map(usize::to_string).collect();
let more = if columns.len() > 5 { format!(" and {} more", columns.len() - 5) } else { String::new() };
let text = format!(
"Shapefile: {what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}",
"{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}",
named.join(", "),
cause(encoding)
);
Expand Down Expand Up @@ -433,7 +433,7 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result<Option<crate::date::Date
/// CST is a filename hint, never a decoder input or an observed source part.
pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() -> bool, notes: &mut crate::loss::Notes) {
if cpg_encoding(cpg).is_none() && ldid_code_page(ldid).and_then(DbfEncoding::from_number).is_none() && present() {
notes.push(crate::loss::Note::plain("Shapefile: an unused .cst sidecar exists; RustGIS does not read .cst encoding declarations. If its encoding label is trusted, write that label to a same-basename .cpg (replacing an unusable declaration if present) and reopen the data; otherwise confirm the encoding with the provider"));
notes.push(crate::loss::Note::plain("an unused .cst sidecar exists; RustGIS does not read .cst encoding declarations. If its encoding label is trusted, write that label to a same-basename .cpg (replacing an unusable declaration if present) and reopen the data; otherwise confirm the encoding with the provider"));
}
}

Expand All @@ -452,20 +452,25 @@ pub(crate) fn has_cst(path: &std::path::Path) -> bool {
/// Every ASCII case of the optional CST hint's extension.
const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"];

/// A code-page label should be a few bytes. Bound reads even for a hostile sidecar.
pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) -> crate::Result<Option<Vec<u8>>> {
cpg_result(try_read_cpg(path), notes)
/// A code-page label should be a few bytes. Bound reads even for a hostile sidecar. A `.cpg` that
/// can't be read is said once, with what is used instead: the `.dbf`'s code page (its language
/// driver `ldid`), or UTF-8, assumed, when it names none.
pub(crate) fn read_cpg(path: &std::path::Path, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result<Option<Vec<u8>>> {
cpg_result(try_read_cpg(path), ldid, notes)
}

/// An optional declaration can fall back after an I/O failure, but Cancel must end the read.
fn cpg_result(result: std::io::Result<Option<Vec<u8>>>, notes: &mut crate::loss::Notes) -> crate::Result<Option<Vec<u8>>> {
fn cpg_result(result: std::io::Result<Option<Vec<u8>>>, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result<Option<Vec<u8>>> {
match result.map_err(crate::DataError::from) {
Ok(bytes) => Ok(bytes),
Err(crate::DataError::Io(e)) => {
// 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})")));
Ok(Some(Vec::new()))
let text = format!("could not read the .cpg ({e}); using the .dbf code page if RustGIS reads it, otherwise UTF-8");
notes.push(if ldid == 0 {
crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text)
} else {
crate::loss::Note::plain(text)
});
Ok(None)
}
Err(e) => Err(e),
}
Expand Down Expand Up @@ -541,14 +546,17 @@ mod tests {
fn cpg_cancellation_is_not_an_encoding_fallback() {
let mut notes = crate::loss::Notes::new();
let cancelled = std::io::Error::other(crate::DataError::Cancelled);
assert!(matches!(cpg_result(Err(cancelled), &mut notes), Err(crate::DataError::Cancelled)));
assert!(matches!(cpg_result(Err(cancelled), 0, &mut notes), Err(crate::DataError::Cancelled)));
assert!(notes.is_empty());
let unreadable = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
assert_eq!(cpg_result(Err(unreadable), &mut notes).unwrap(), Some(Vec::new()));
assert_eq!(cpg_result(Err(unreadable), 0, &mut notes).unwrap(), None);
assert_eq!(notes.len(), 1);
assert_eq!(notes[0].text, "could not read the .cpg (permission denied)");
assert_eq!(
notes[0].text,
"could not read the .cpg (permission denied); using the .dbf code page if RustGIS reads it, otherwise UTF-8"
);
notes.clear();
assert_eq!(cpg_result(Ok(None), &mut notes).unwrap(), None);
assert_eq!(cpg_result(Ok(None), 0, &mut notes).unwrap(), None);
assert!(notes.is_empty());
}

Expand Down Expand Up @@ -584,28 +592,35 @@ mod tests {
let path = dir.path().join("places.dbf");
let cpg = path.with_extension("cpg");
assert!(Command::new("mkfifo").arg(&cpg).status().unwrap().success());
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new()));
// No label, and one note saying so.
let unusable = |path: &std::path::Path| {
let mut notes = crate::loss::Notes::new();
let read = read_cpg(path, 0, &mut notes).unwrap();
assert_eq!(notes.len(), 1, "{notes:?}");
read
};
assert_eq!(unusable(&path), None);
// A rejected spelling must not hide a later regular one.
// A case-insensitive filesystem gives this spelling to the FIFO itself.
if !path.with_extension("CpG").exists() {
std::fs::write(path.with_extension("CpG"), b"1252").unwrap();
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec()));
assert_eq!(read_cpg(&path, 0, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec()));
std::fs::remove_file(path.with_extension("CpG")).unwrap();
}
std::fs::remove_file(&cpg).unwrap();
let socket = std::os::unix::net::UnixListener::bind(&cpg).unwrap();
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new()));
assert_eq!(unusable(&path), None);
drop(socket);
std::fs::remove_file(&cpg).unwrap();
std::fs::create_dir(&cpg).unwrap();
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new()));
assert_eq!(unusable(&path), None);
std::fs::remove_dir(&cpg).unwrap();
std::os::unix::fs::symlink("/dev/zero", &cpg).unwrap();
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new()));
assert_eq!(unusable(&path), None);
std::fs::remove_file(&cpg).unwrap();
std::fs::write(dir.path().join("label"), b"1252").unwrap();
std::os::unix::fs::symlink("label", &cpg).unwrap();
assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec()));
assert_eq!(read_cpg(&path, 0, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec()));
return;
}
let mut child = Command::new(std::env::current_exe().unwrap())
Expand Down Expand Up @@ -762,12 +777,12 @@ mod tests {
assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8));
assert_eq!(
notes.texts().collect::<Vec<_>>(),
["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]
["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.texts().collect::<Vec<_>>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]);
assert_eq!(notes.texts().collect::<Vec<_>>(), ["unsupported .dbf code page 0xFF; using UTF-8"]);
assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding));
}

Expand Down Expand Up @@ -853,11 +868,11 @@ mod tests {
let one = not_utf8_names_note(&[3], "UTF-8").unwrap();
assert_eq!(one.loss, Some(crate::loss::LossCode::ChangedEncoding));
let one = one.as_str();
assert!(one.starts_with("Shapefile: 1 field name isn't valid UTF-8 and was read with U+FFFD"), "{one}");
assert!(one.starts_with("1 field name isn't valid UTF-8 and was read with U+FFFD"), "{one}");
assert!(one.contains("in field 3;"), "{one}");
let two = not_utf8_names_note(&[3, 7], "UTF-8").unwrap();
let two = two.as_str();
assert!(two.starts_with("Shapefile: 2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}");
assert!(two.starts_with("2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}");
assert!(two.contains("in fields 3, 7;"), "{two}");
assert!(two.ends_with(NO_OTHER_ENCODING), "{two}");
let many = not_utf8_names_note(&[1, 2, 3, 4, 5, 6, 7], "UTF-8").unwrap();
Expand All @@ -867,7 +882,7 @@ mod tests {
assert_eq!(
not_utf8_names_note(&[1], "Big5").as_ref().map(crate::loss::Note::as_str),
Some(
"Shapefile: 1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5"
"1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5"
)
);
}
Expand Down
17 changes: 8 additions & 9 deletions crates/data/src/filegdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
ds.held_in = c;
}
let (mut curves, mut wall_hulls, mut unmerged, mut unprojected, mut beyond) = (0usize, 0usize, 0usize, 0usize, 0usize);
// Features with a place in longitude/latitude.
let mut placed = 0usize;
// Multipatches with points but no footprint: too few, all on one line, or not finite numbers.
let mut no_footprint = 0usize;
// Shapes decoded, a multipatch's too (its M values go even when it has no footprint).
Expand Down Expand Up @@ -448,7 +450,10 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
// longitude/latitude.
if let (Some(g), Some(t)) = (&geometry, &to_lonlat) {
match crate::io::places_lonlat_extent(g, t) {
Some(e) => beyond += usize::from(e.beyond_lonlat()),
Some(e) => {
placed += 1;
beyond += usize::from(e.beyond_lonlat());
}
None => unprojected += 1,
}
}
Expand All @@ -475,14 +480,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
report.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c));
}
if unprojected > 0 {
report
.messages
.push(if unprojected == 1 {
"one feature has a place that can't be given in longitude/latitude (coordinates outside its coordinate system): it is kept as the file holds it, but doesn't draw".to_string()
} else {
format!("{unprojected} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the file holds them, but don't draw")
});
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
report.messages.extend(crate::io::kept_unplaced_note("features", unprojected, placed == 0, c));
}
if zm {
// The table declares them for every shape.
Expand Down
18 changes: 17 additions & 1 deletion crates/data/src/filegdb/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,9 +571,25 @@ fn coordinates_that_cant_be_converted_are_said() {
assert!(rows[0].geometry.is_some() && rows[1].geometry.is_some(), "{:?}", rows[1].geometry);
assert!(!ds.crs_incomplete);
assert!(
report.messages.iter().any(|m| m.starts_with("one feature has a place that can't be given in longitude/latitude")),
report
.messages
.iter()
.any(|m| m.starts_with("one of the features has a place in EPSG:3035 that can't be given in longitude/latitude")),
"{report:?}"
);
// None of them placed: the system doesn't seem to be theirs, which Define Projection can set.
let all_out = vec![vec![V::Blob(polygon(&square(9e8, 9e8, 10.0))), V::Text(Some("out"))]];
let files = geodatabase(vec![("T", table(4, &fields, &all_out))]);
let layers = read_files(&files).unwrap();
assert!(
layers[0]
.1
.messages
.iter()
.any(|m| m.starts_with("none of the features has a place") && m.contains("Define Projection can set the right one")),
"{:?}",
layers[0].1
);
}

#[test]
Expand Down
27 changes: 17 additions & 10 deletions crates/data/src/gml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,7 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe
let unread_names = kind.unread_names.said();
let (mut outside, mut null_text) = (false, Vec::new());
// Features with a place the file's system can't give in longitude/latitude, kept missing.
let (mut unplaced, mut beyond) = (0usize, 0usize);
let (mut unplaced, mut beyond, mut placed) = (0usize, 0usize, 0usize);
// Held as the file holds its coordinates, in its own system (in the axis order RustGIS
// gives every system's), when RustGIS converts it.
if let Some((Some(_), _)) = &transform
Expand Down Expand Up @@ -814,6 +814,7 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe
}
});
unplaced += usize::from(missing.get());
placed += usize::from(!missing.get());
e = lonlat.get();
// Converted, but beyond longitude/latitude: it draws out of place.
beyond += usize::from(!missing.get() && e.beyond_lonlat());
Expand Down Expand Up @@ -847,7 +848,8 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe
ds.geometry_type = crate::io::dominant_type(&ds);
// The file's notices go with its first layer only.
let mut rep = if out.is_empty() { report.clone() } else { ReadReport::default() };
// Features whose shape couldn't be read are said with their own feature type.
// Features whose shape couldn't be read are said with their own feature type. These rows
// are kept, without their geometry: `skipped` counts them as the reading corpus compares.
rep.skipped = kind.skipped;
if kind.skipped > 0 {
let what = if kind.skipped == 1 { "feature" } else { "features" };
Expand All @@ -857,13 +859,8 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe
format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped),
));
}
if unplaced > 0 {
let what = if unplaced == 1 { "feature has" } else { "features have" };
let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label()));
rep.messages.push(format!(
"{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as the file holds them, but don't draw",
ds.name
));
if let Some((c, _)) = file_srs {
rep.messages.extend(crate::io::kept_unplaced_note("features", unplaced, placed == 0, c).map(|n| format!("{}: {n}", ds.name)));
}
if let Some((c, _)) = file_srs {
rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", ds.name)));
Expand Down Expand Up @@ -1216,9 +1213,19 @@ mod tests {
assert_eq!(parts[0][0], Coord::new(500000.0, 4649776.0), "the file's numbers");
assert_eq!(parts[0][1], Coord::new(1e15, 4649776.0), "the file's numbers");
assert!(serde_json::to_string(ds).is_ok(), "saves");
// None of its features has a place: the system doesn't seem to be theirs, which Define
// Projection can set.
let said = &layers[0].1.messages;
assert!(said.iter().any(|m| m.contains("1 feature has places") && m.contains("kept as the file holds them")), "{said:?}");
let all = ": none of the features has a place in longitude/latitude from";
assert!(said.iter().any(|m| m.contains(all) && m.contains("Define Projection can set the right one")), "{said:?}");
assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1);
// Beside one with a place, it is counted alone.
let two = gml.replace("</ogr:FeatureCollection>", r#"<gml:featureMember><ogr:roads fid="roads.1"><ogr:geometryProperty><gml:LineString srsName="EPSG:32633"><gml:coordinates>500000,4649776 500100,4649776</gml:coordinates></gml:LineString></ogr:geometryProperty></ogr:roads></gml:featureMember>
</ogr:FeatureCollection>"#);
let said = read("r.gml", two.as_bytes()).unwrap()[0].1.messages.clone();
let one = ": one of the features has a place in";
assert!(said.iter().any(|m| m.contains(one) && m.contains("it is kept as the file holds it, but doesn't draw")), "{said:?}");
assert!(said.iter().all(|m| !m.contains("Define Projection")), "{said:?}");
}

/// A place a file's system converts to beyond longitude/latitude (Web Mercator a billion
Expand Down
Loading
Loading