From d8b364e897da4afdcdf1c0195ffd7752e1d14340 Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 22 Nov 2026 16:05:17 +0800 Subject: [PATCH 1/3] fix(data): say when a .dbf's declared code page replaces bytes with U+FFFD (#2614) A .dbf in Shift_JIS, GBK, EUC-KR, Big5 or another code page encoding_rs decodes was read with U+FFFD in place of bytes that aren't valid in it, with no notice: #2325 counted only text read as UTF-8. Names and values are now counted with the declared decoder, on the whole read and on the read in place, and the notice names the code page the .cpg or the .dbf's language driver declares. --- crates/data/src/dbf.rs | 112 +++++++++++++----- crates/data/src/export.rs | 5 +- crates/data/src/export/tests.rs | 1 + crates/data/src/io.rs | 32 +++-- crates/data/src/source/mod.rs | 32 +++-- crates/data/src/source/shp.rs | 45 +++---- .../tests/integration/shapefile_encoding.rs | 72 ++++++++--- crates/engine/src/cmd/share.rs | 5 +- crates/engine/src/cmd/workflows.rs | 5 +- crates/map/src/source.rs | 2 +- docs/user-guide/data-formats.md | 5 +- docs/user-guide/shapefile-encoding.md | 8 +- 12 files changed, 225 insertions(+), 99 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 6266aea955..9388036730 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -27,13 +27,24 @@ impl DbfEncoding { } } - /// Whether text is read as UTF-8, whose decoder puts U+FFFD in place of bytes that aren't - /// UTF-8 without a word: the read counts them itself ([`not_utf8`]). - pub(crate) fn is_utf8(&self) -> bool { + /// Whether `text` holds bytes this encoding can't read. Its decoder puts U+FFFD in place of + /// them without a word, so the read counts them itself ([`not_utf8`]). It asks the decoder + /// `dbase` calls, so a count is of the values that were replaced. A DOS page gives every + /// byte a character, so nothing is. + pub(crate) fn malformed(&self, text: &[u8]) -> bool { match self { - Self::Standard(encoding) => *encoding == rs::UTF_8, + Self::Standard(encoding) if *encoding != rs::UTF_8 => !text.is_ascii() && encoding.decode(text).2, + Self::Standard(_) | Self::Utf8 => std::str::from_utf8(text).is_err(), Self::Oem(_) => false, - Self::Utf8 => true, + } + } + + /// The name of the encoding, for the notices of text it can't read. + pub(crate) fn name(&self) -> &'static str { + match self { + Self::Standard(encoding) => encoding.name(), + Self::Oem(_) => "a DOS code page", + Self::Utf8 => "UTF-8", } } @@ -175,31 +186,38 @@ fn page_name(page: u16) -> Option<&'static str> { /// code page RustGIS can't decode. pub(crate) const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS reads (a .cpg file containing 950 names Big5)"; -/// What opening a `.dbf` read as UTF-8 says of its field names that aren't UTF-8 ([`not_utf8`]), +/// The end of each note of text that isn't valid in `encoding`: for UTF-8, why the text was read as +/// it ([`NO_OTHER_ENCODING`]); for another, that the file declares it. +pub(crate) fn cause(encoding: &str) -> String { + if encoding == "UTF-8" { NO_OTHER_ENCODING.to_string() } else { format!("the .cpg or the .dbf's language driver declares {encoding}") } +} + +/// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`not_utf8`]), /// naming the first five by their column (from 1). `None` when there are none. -pub(crate) fn not_utf8_names_note(columns: &[usize]) -> Option { +pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option { let (what, label) = match columns.len() { 0 => return None, - 1 => ("1 field name isn't valid UTF-8 and was".to_string(), "field"), - n => (format!("{n} field names aren't valid UTF-8 and were"), "fields"), + 1 => (format!("1 field name isn't valid {encoding} and was"), "field"), + n => (format!("{n} field names aren't valid {encoding} and were"), "fields"), }; let named: Vec = columns.iter().take(5).map(usize::to_string).collect(); let more = if columns.len() > 5 { format!(" and {} more", columns.len() - 5) } else { String::new() }; Some(format!( - "Shapefile: {what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {NO_OTHER_ENCODING}", - named.join(", ") + "Shapefile: {what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}", + named.join(", "), + cause(encoding) )) } -/// What a `.dbf` read as UTF-8 holds that isn't UTF-8: which of its field names (by column, from 1), -/// and for each column by its position how many of its text values. `dbase` reads them with U+FFFD -/// in place of those bytes and doesn't say so. They are counted on the bytes, since U+FFFD in the -/// text read can also be what the file holds. The values are the ones `dbase` decodes as text: a +/// What a `.dbf` holds that isn't valid in its `encoding`: which of its field names (by column, from +/// 1), and for each column by its position how many of its text values. `dbase` reads them with +/// U+FFFD in place of those bytes and doesn't say so. They are counted on the bytes, since U+FFFD in +/// the text read can also be what the file holds. The values are the ones `dbase` decodes as text: a /// character (`C`) column's, up to a NUL, in the rows the header counts that aren't marked deleted /// (a row the read then leaves out as unreadable is counted too). It doesn't look at Cancel: it is /// one pass over a file that is read whole, so of at most [`crate::io::max_bytes`]. -pub(crate) fn not_utf8(dbf: &[u8]) -> (Vec, Vec) { - let lossy = |text: &[u8]| std::str::from_utf8(text.split(|b| *b == 0).next().unwrap_or(&[])).is_err(); +pub(crate) fn not_utf8(dbf: &[u8], encoding: &DbfEncoding) -> (Vec, Vec) { + let lossy = |text: &[u8]| encoding.malformed(text.split(|b| *b == 0).next().unwrap_or(&[])); let header_len = usize::from(u16::from_le_bytes([dbf.get(8).copied().unwrap_or(0), dbf.get(9).copied().unwrap_or(0)])); let rows = dbf.get(4..8).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, |b| u32::from_le_bytes(b) as usize); let mut names = Vec::new(); @@ -572,13 +590,36 @@ mod tests { assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); } - /// Text is read as UTF-8, so counted when it isn't, with no encoding named, with UTF-8 named - /// and with a code page that can't be decoded; a code page that is decoded isn't UTF-8. + /// Text is read as UTF-8 unless another encoding is named, with none named, with UTF-8 named + /// and with a code page that can't be decoded; a code page that is decoded is named by it. #[test] fn utf8_is_what_text_is_read_as_unless_another_encoding_is_named() { - let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, ldid, &mut Vec::new()).is_utf8(); - assert!(read(None, 0) && read(None, 0xF0) && read(Some(b"UTF-8"), 0x03) && read(Some(b"65001"), 0) && read(None, 0x6C)); - assert!(!read(Some(b"950"), 0) && !read(None, 0x4F) && !read(None, 0x01) && !read(Some(b"1252"), 0xF0)); + let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, ldid, &mut Vec::new()).name(); + for (cpg, ldid) in [(None, 0), (None, 0xF0), (Some(b"UTF-8".as_slice()), 0x03), (Some(b"65001".as_slice()), 0), (None, 0x6C)] { + assert_eq!(read(cpg, ldid), "UTF-8"); + } + assert_eq!(read(Some(b"950"), 0), "Big5"); + assert_eq!(read(None, 0x4F), "Big5"); + assert_eq!(read(None, 0x13), "Shift_JIS"); + assert_eq!(read(None, 0x4D), "GBK"); + assert_eq!(read(None, 0x4E), "EUC-KR"); + assert_eq!(read(Some(b"1252"), 0xF0), "windows-1252"); + assert_eq!(read(None, 0x01), "a DOS code page"); + } + + /// Bytes an encoding can't read are told by its own decoder: a lead byte with nothing after it, + /// or before a byte that can't follow it, in the multibyte pages; ASCII and whole characters + /// aren't. A DOS page gives every byte a character. + #[test] + fn bytes_that_cant_be_read_are_those_the_declared_decoder_replaces() { + let page = |cpg: &[u8]| encoding(Some(cpg), 0, &mut Vec::new()); + let (sjis, big5, utf8) = (page(b"932"), page(b"950"), page(b"UTF-8")); + assert!(sjis.malformed(b"X\x82") && sjis.malformed(b"\x82 ") && sjis.malformed(b"\xff")); + assert!(!sjis.malformed(b"\x93\x8c\x8b\x9e") && !sjis.malformed(b"plain") && !sjis.malformed(b"")); + assert!(big5.malformed(b"X\xa4") && !big5.malformed(b"\xa4\x40")); + // The same bytes are valid in one page and not in another. + assert!(utf8.malformed(b"\x93\x8c") && !sjis.malformed(b"\x93\x8c")); + assert!(!page(b"437").malformed(b"\xff") && !page(b"1252").malformed(b"\xff")); } /// A `.dbf` of these columns (name, type, width) and rows (the deletion flag, then the values). @@ -613,29 +654,36 @@ mod tests { b" a\0\xe9\xe9 \xc3\xa9 ", ]; let mut dbf = table(columns, rows); - assert_eq!(not_utf8(&dbf), (vec![1], vec![1, 0, 0, 1])); + assert_eq!(not_utf8(&dbf, &DbfEncoding::Utf8), (vec![1], vec![1, 0, 0, 1])); // A row past the header's count isn't read. dbf.extend_from_slice(b" \xe9t\xe9 20260305 1\xe9bc"); - assert_eq!(not_utf8(&dbf), (vec![1], vec![1, 0, 0, 1])); + assert_eq!(not_utf8(&dbf, &DbfEncoding::Utf8), (vec![1], vec![1, 0, 0, 1])); // A file cut short counts the rows that are whole, and one without a header nothing. let cut = dbf.len() - 2 * 18 - 1; - assert_eq!(not_utf8(&dbf[..cut]), (vec![1], vec![1, 0, 0, 1])); - assert_eq!(not_utf8(&dbf[..cut - 18]), (vec![1], vec![1, 0, 0, 0])); - assert_eq!(not_utf8(&dbf[..40]), (Vec::new(), Vec::new())); - assert_eq!(not_utf8(&[]), (Vec::new(), Vec::new())); + assert_eq!(not_utf8(&dbf[..cut], &DbfEncoding::Utf8), (vec![1], vec![1, 0, 0, 1])); + assert_eq!(not_utf8(&dbf[..cut - 18], &DbfEncoding::Utf8), (vec![1], vec![1, 0, 0, 0])); + assert_eq!(not_utf8(&dbf[..40], &DbfEncoding::Utf8), (Vec::new(), Vec::new())); + assert_eq!(not_utf8(&[], &DbfEncoding::Utf8), (Vec::new(), Vec::new())); } #[test] fn field_names_that_arent_utf8_are_said_with_their_columns() { - assert_eq!(not_utf8_names_note(&[]), None); - let one = not_utf8_names_note(&[3]).unwrap(); + assert_eq!(not_utf8_names_note(&[], "UTF-8"), None); + let one = not_utf8_names_note(&[3], "UTF-8").unwrap(); assert!(one.starts_with("Shapefile: 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]).unwrap(); + let two = not_utf8_names_note(&[3, 7], "UTF-8").unwrap(); assert!(two.starts_with("Shapefile: 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]).unwrap(); + let many = not_utf8_names_note(&[1, 2, 3, 4, 5, 6, 7], "UTF-8").unwrap(); assert!(many.contains("in fields 1, 2, 3, 4, 5 and 2 more;"), "{many}"); + // A declared code page is named, as what the file declares. + assert_eq!( + not_utf8_names_note(&[1], "Big5").as_deref(), + 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" + ) + ); } } diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 7798759f72..790b66886f 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -58,9 +58,11 @@ pub struct Exported { /// Per field of the layer, text values `` the source read as null /// ([`crate::source::Batch::null_text`], said by [`crate::source::null_text_note`]). pub null_text: Vec, - /// Per field of the layer, text values the source read as UTF-8 that aren't UTF-8 + /// Per field of the layer, text values that aren't valid in the encoding the source read them in /// ([`crate::source::Batch::not_utf8`], said by [`crate::source::not_utf8_note`]). pub not_utf8: Vec, + /// The encoding `not_utf8` is of ([`crate::source::FeatureSource::text_encoding`]). + pub not_utf8_in: &'static str, /// Per field of the layer, date-times a GeoPackage holds in UTC rather than at their own /// offset ([`crate::io::offset_dates`]; empty for the other formats). pub utc_dates: Vec, @@ -383,6 +385,7 @@ fn write_chunks_as( rounded_dates, null_text, not_utf8, + not_utf8_in: src.text_encoding(), utc_dates, fine_dates, written_values, diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 043a01b0b8..a25f1fdf6d 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -241,6 +241,7 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { rounded_dates: Vec::new(), null_text: Vec::new(), not_utf8: Vec::new(), + not_utf8_in: "UTF-8", utc_dates, fine_dates: if ext == "gpkg" { crate::io::fine_dates(whole.features.iter(), &whole.fields) } else { Vec::new() }, written_values: if ext == "fgb" { crate::io::written_values(whole.features.iter(), &whole.fields) } else { Vec::new() }, diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 9c140bc1fc..574f9abf47 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3520,12 +3520,14 @@ struct DbfRead { fields: Vec, decimals: Vec, report: ReadReport, - /// For each field, its text values that aren't UTF-8 in a table read as UTF-8 + /// For each field, its text values that aren't valid in the table's encoding /// ([`crate::dbf::not_utf8`]). not_utf8: Vec, /// The records marked deleted, by position, ascending: the reader gives them as any other /// ([`crate::dbf::take_deleted`]), and they are left out by position. deleted: Vec, + /// The name of that encoding ([`crate::dbf::DbfEncoding::name`]), for the notice. + encoding: &'static str, } /// Opens dBASE attributes with the Shapefile reader's code-page and date/number handling. @@ -3535,8 +3537,8 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result, cpg: Option<&[u8]>, name: &str) -> Result, cpg: Option<&[u8]>, name: &str) -> Result, cpg: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { - let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(bytes, cpg, name)?; + let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted, encoding } = dbf_reader(bytes, cpg, name)?; let mut ds = Dataset::new(name, GeometryType::None, fields); - let mut counts = DbfCounts::new(ds.fields.len(), not_utf8); + let mut counts = DbfCounts::new(ds.fields.len(), not_utf8, encoding); let allowance = *budget; let mut left = allowance; crate::progress::begin(reader.header().num_records as usize); @@ -3694,24 +3697,26 @@ fn dbf_attrs(record: &shapefile::dbase::Record, fields: &[Field], counts: &mut D /// Values a `.dbf` read changed, counted for each field by its position: dates that weren't /// ones, numbers that weren't finite, and text ``, all read as null; and text that wasn't -/// UTF-8 in a table read as UTF-8, counted before the read ([`crate::dbf::not_utf8`]). +/// valid in the table's encoding, counted before the read ([`crate::dbf::not_utf8`]). struct DbfCounts { unread_dates: Vec, nonfinite: Vec, null_text: Vec, not_utf8: Vec, + /// The name of the encoding `not_utf8` is of. + encoding: &'static str, } impl DbfCounts { - fn new(fields: usize, not_utf8: Vec) -> Self { - DbfCounts { unread_dates: vec![0; fields], nonfinite: vec![0; fields], null_text: Vec::new(), not_utf8 } + fn new(fields: usize, not_utf8: Vec, encoding: &'static str) -> Self { + DbfCounts { unread_dates: vec![0; fields], nonfinite: vec![0; fields], null_text: Vec::new(), not_utf8, encoding } } } /// Reports date, numeric and `` cells read as null, and text that isn't UTF-8, identically /// for tables and Shapefiles. fn dbf_notices(ds: &Dataset, report: &mut ReadReport, counts: &DbfCounts) { - let DbfCounts { unread_dates, nonfinite, null_text, not_utf8 } = counts; + let DbfCounts { unread_dates, nonfinite, null_text, not_utf8, encoding } = counts; let name = &ds.name; report.unread_dates = crate::source::unread_dates_note(&ds.fields, unread_dates); report.messages.extend(report.unread_dates.iter().map(|n| format!("{name}: {n}"))); @@ -3725,7 +3730,7 @@ fn dbf_notices(ds: &Dataset, report: &mut ReadReport, counts: &DbfCounts) { report.messages.push(format!("{name}: {what} read as empty, in {}", named_fields(&ds.fields, nonfinite))); } report.messages.extend(crate::source::null_text_note(&ds.fields, null_text).map(|n| format!("{name}: {n}"))); - report.messages.extend(crate::source::not_utf8_note(&ds.fields, not_utf8).map(|n| format!("{name}: {n}"))); + report.messages.extend(crate::source::not_utf8_note(&ds.fields, not_utf8, encoding).map(|n| format!("{name}: {n}"))); } /// The files of a Shapefile, read into memory. @@ -3743,7 +3748,8 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio use shapefile::Shape; use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); - let DbfRead { reader: mut dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; + let DbfRead { reader: mut dbf, fields, decimals, mut report, not_utf8, deleted, encoding } = + dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; let mut shapes = match parts.shx { Some(shx) => shapefile::ShapeReader::with_shx(Cursor::new(parts.shp), Cursor::new(shx)), None => shapefile::ShapeReader::new(Cursor::new(parts.shp)), @@ -3764,7 +3770,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // The box of the converted places in longitude/latitude, for the notice of a `.prj` that // doesn't match the coordinates. let mut lonlat_extent = rustgis_geom::Extent::EMPTY; - let mut counts = DbfCounts::new(ds.fields.len(), not_utf8); + let mut counts = DbfCounts::new(ds.fields.len(), not_utf8, encoding); let mut source_kind = GeometryType::None; let pt = |x: f64, y: f64| Coord::new(x, y); // Paired by position: a record marked deleted is read as any other, and left out with its shape. diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b4ce4f53d4..3a4bc5026e 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -258,8 +258,9 @@ pub struct Batch { /// What else the read lost or assumed, one note per kind with its count (values that don't fit /// their field, rings without area): said as they are. pub notes: Vec, - /// Text values of a Shapefile read as UTF-8 that aren't UTF-8, so hold U+FFFD in place of - /// those bytes, counted for each field by its position. Said by [`not_utf8_note`]. + /// Text values of a Shapefile that aren't valid in the encoding they were read in + /// ([`FeatureSource::text_encoding`]), so hold U+FFFD in place of those bytes, counted for each + /// field by its position. Said by [`not_utf8_note`]. pub not_utf8: Vec, } @@ -274,7 +275,7 @@ pub(crate) fn null_text_at(counts: &mut Vec, k: usize) { unread_dates_by(counts, k, 1); } -/// Counts one more text value that isn't UTF-8 in the field at `k` ([`Batch::not_utf8`]). +/// Counts one more text value that isn't valid in its encoding in the field at `k` ([`Batch::not_utf8`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn not_utf8_at(counts: &mut Vec, k: usize) { unread_dates_by(counts, k, 1); @@ -336,23 +337,23 @@ pub fn null_text_note(fields: &[crate::Field], counts: &[usize]) -> Option Option { +/// What a read says of a `.dbf`'s text values that aren't valid in the `encoding` they were read in +/// ([`Batch::not_utf8`], [`FeatureSource::text_encoding`]): how many, in which fields (the first five +/// named), and why they were read in it. `None` when there were none. +pub fn not_utf8_note(fields: &[crate::Field], counts: &[usize], encoding: &str) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; } let what = if total == 1 { - "1 text value isn't valid UTF-8 and was".to_string() + format!("1 text value isn't valid {encoding} and was") } else { - format!("{total} text values aren't valid UTF-8 and were") + format!("{total} text values aren't valid {encoding} and were") }; Some(format!( "{what} read with U+FFFD in place of the bytes that can't be read, in {}; {}", crate::io::named_fields(fields, counts), - crate::dbf::NO_OTHER_ENCODING + crate::dbf::cause(encoding) )) } @@ -409,6 +410,11 @@ pub trait FeatureSource: Send + Sync { fn coord_crs(&self) -> crate::raster::Crs { crate::raster::Crs::LonLat } + /// The encoding the source's text values are read in, for the notice of those that aren't + /// valid in it ([`not_utf8_note`]). + fn text_encoding(&self) -> &'static str { + "UTF-8" + } /// Whether features were left out of every read because the coordinate system the source /// declares can't place them, so that defining its projection again can't bring them back. fn lost_to_crs(&self) -> bool { @@ -670,6 +676,10 @@ impl FeatureSource for Fetching { self.0.lost_to_crs() } + fn text_encoding(&self) -> &'static str { + self.0.text_encoding() + } + fn skipped_at_open(&self) -> usize { self.0.skipped_at_open() } @@ -721,7 +731,7 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, losses: Vec::new(), }; let null_text = null_text_note(&info.fields, &null_text); - let not_utf8 = not_utf8_note(&info.fields, ¬_utf8); + let not_utf8 = not_utf8_note(&info.fields, ¬_utf8, src.text_encoding()); report.messages.extend( unread_dates.into_iter().chain(rounded).chain(null_text).chain(notes).chain(not_utf8).map(|n| format!("{}: {n}", info.name)), ); diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 0b1e8955a7..aff36cb0a6 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -184,8 +184,8 @@ impl ShpSource { if reproject.is_lonlat() && extent.beyond_lonlat() { notes.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); } - let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding.decoder(), encoding.is_utf8())?; - notes.extend(crate::dbf::not_utf8_names_note(¬_utf8)); + let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding)?; + notes.extend(crate::dbf::not_utf8_names_note(¬_utf8, encoding.name())); let fields = table.columns.iter().zip(names).map(|(c, n)| Field::new(n, c.out)).collect(); let mut info = SourceInfo { name: name.to_string(), @@ -219,6 +219,11 @@ impl FeatureSource for ShpSource { self.reproject.crs() } + /// The code page its text is read in. + fn text_encoding(&self) -> &'static str { + self.encoding.name() + } + /// Samples indexed records, falling back to geometry matches when the native view is refused. /// The fallback counts records and checks Cancel before reading each one. fn read(&self, req: &Request) -> Result { @@ -240,7 +245,6 @@ impl FeatureSource for ShpSource { let mut features = Vec::new(); let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut deleted = 0usize; - let utf8 = self.encoding.is_utf8(); // An extent the file's system couldn't bound (#1925) has no boxes for the index to sample // by: every record is visited, tested, and the matches sampled as they come. let late = req.extent.is_some() && bounds.is_none(); @@ -304,7 +308,7 @@ impl FeatureSource for ShpSource { if late && !sample.wants() { return Ok(()); } - self.table.values(&row, &encoding, &mut unread_dates, &mut null_text, utf8.then_some(&mut not_utf8)) + self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) } else { if late && !sample.wants() { return Ok(()); @@ -365,7 +369,6 @@ impl FeatureSource for ShpSource { let mut row = vec![0u8; self.table.row_len]; let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut deleted = 0usize; - let utf8 = self.encoding.is_utf8(); // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing // their directory or the complete feature collection in memory. @@ -422,7 +425,7 @@ impl FeatureSource for ShpSource { deleted += 1; return Ok(()); } - self.table.values(&row, &encoding, &mut unread_dates, &mut null_text, utf8.then_some(&mut not_utf8)) + self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) } else { vec![Value::Null; self.table.columns.len()] }; @@ -707,15 +710,16 @@ fn read_table(path: &Path) -> Result { impl Table { /// A row's values (after its deletion flag), counting in `unread_dates` the dates that /// aren't ones ([`Batch::unread_dates`]), in `null_text` the text `` read as null - /// ([`Batch::null_text`]) and in `not_utf8`, given when the table is read as UTF-8, the text - /// that isn't UTF-8 ([`Batch::not_utf8`]). + /// ([`Batch::null_text`]) and in `not_utf8` the text that isn't valid in `declared`, the + /// encoding `decoder` reads ([`Batch::not_utf8`]). fn values( &self, row: &[u8], - encoding: &dyn shapefile::dbase::Encoding, + decoder: &dyn shapefile::dbase::Encoding, + declared: &crate::dbf::DbfEncoding, unread_dates: &mut Vec, null_text: &mut Vec, - mut not_utf8: Option<&mut Vec>, + not_utf8: &mut Vec, ) -> Vec { let mut out = Vec::with_capacity(self.columns.len()); for (k, c) in self.columns.iter().enumerate() { @@ -732,17 +736,14 @@ impl Table { }) .map_or(Value::Null, Value::Date) } else { - let v = value(c, b, encoding); + let v = value(c, b, decoder); if c.ty == b'C' && matches!(&v, Value::Text(t) if Value::is_null_marker(t)) { super::null_text_at(null_text, k); Value::Null } else { // Counted on the bytes: U+FFFD in the text read can also be what the file holds. - if let Some(counts) = &mut not_utf8 - && matches!(v, Value::Text(_)) - && std::str::from_utf8(padded(b)).is_err() - { - super::not_utf8_at(counts, k); + if matches!(v, Value::Text(_)) && declared.malformed(padded(b)) { + super::not_utf8_at(not_utf8, k); } v } @@ -752,10 +753,10 @@ impl Table { } } -/// The `.dbf`'s column names, in order (read again: the layout above keeps only offsets), and, -/// when they are read as UTF-8 (`utf8`), the columns (from 1) whose names aren't UTF-8 -/// ([`crate::dbf::not_utf8_names_note`]). -fn read_names(path: &Path, n: usize, encoding: &dyn shapefile::dbase::Encoding, utf8: bool) -> Result<(Vec, Vec)> { +/// The `.dbf`'s column names, in order (read again: the layout above keeps only offsets), and the +/// columns (from 1) whose names aren't valid in its `encoding` ([`crate::dbf::not_utf8_names_note`]). +fn read_names(path: &Path, n: usize, encoding: &crate::dbf::DbfEncoding) -> Result<(Vec, Vec)> { + let decoder = encoding.decoder(); let mut f = BufReader::new(crate::provenance::open(path)?); f.seek(SeekFrom::Start(32))?; let mut out = Vec::with_capacity(n); @@ -766,10 +767,10 @@ fn read_names(path: &Path, n: usize, encoding: &dyn shapefile::dbase::Encoding, let name = d.get(..11).unwrap_or(&[]); let end = name.iter().position(|b| *b == 0).unwrap_or(name.len()); let name = name.get(..end).unwrap_or(&[]); - if utf8 && std::str::from_utf8(name).is_err() { + if encoding.malformed(name) { not_utf8.push(out.len() + 1); } - out.push(encoding.decode(name).unwrap_or_else(|_| String::from_utf8_lossy(name)).trim().to_string()); + out.push(shapefile::dbase::Encoding::decode(&decoder, name).unwrap_or_else(|_| String::from_utf8_lossy(name)).trim().to_string()); } Ok((out, not_utf8)) } diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 84dd20a804..e328a65277 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -68,22 +68,42 @@ fn named_parts(field: &[u8], text: &[u8], ldid: u8, cpg: Option<&[u8]>, rows: us /// Why text was read as UTF-8, as the notes of text that isn't UTF-8 end. const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS reads (a .cpg file containing 950 names Big5)"; -/// What a read of `places` says of `values` text values of its field `field` that aren't UTF-8. -fn not_utf8_note(values: usize, field: &str) -> String { +/// The end of a notice of text that isn't valid in `encoding`: UTF-8 is read when no `.cpg` names +/// another, so it says that; another encoding was declared, so it names it. +fn cause(encoding: &str) -> String { + match encoding { + "UTF-8" => NO_OTHER_ENCODING.to_string(), + other => format!("the .cpg or the .dbf's language driver declares {other}"), + } +} + +/// What a read of `places` says of `values` text values of its field `field` that aren't valid in `encoding`. +fn invalid_note(values: usize, field: &str, encoding: &str) -> String { let what = match values { - 1 => "1 text value isn't valid UTF-8 and was".to_string(), - n => format!("{n} text values aren't valid UTF-8 and were"), + 1 => format!("1 text value isn't valid {encoding} and was"), + n => format!("{n} text values aren't valid {encoding} and were"), }; - format!("places: {what} read with U+FFFD in place of the bytes that can't be read, in '{field}'; {NO_OTHER_ENCODING}") + format!("places: {what} read with U+FFFD in place of the bytes that can't be read, in '{field}'; {}", cause(encoding)) } -/// What opening a `.dbf` says of its one field name that isn't UTF-8, the first column. -fn name_not_utf8_note() -> String { +/// What opening a `.dbf` says of its one field name that isn't valid in `encoding`, the first column. +fn invalid_name_note(encoding: &str) -> String { format!( - "Shapefile: 1 field name isn't valid UTF-8 and was read with U+FFFD in place of the bytes that can't be read, in field 1; {NO_OTHER_ENCODING}" + "Shapefile: 1 field name isn't valid {encoding} and was read with U+FFFD in place of the bytes that can't be read, in field 1; {}", + cause(encoding) ) } +/// [`invalid_note`] for text read as UTF-8. +fn not_utf8_note(values: usize, field: &str) -> String { + invalid_note(values, field, "UTF-8") +} + +/// [`invalid_name_note`] for a name read as UTF-8. +fn name_not_utf8_note() -> String { + invalid_name_note("UTF-8") +} + /// Three points with two text fields: `name`, holding `first`, `second` and `Tainan` as these /// bytes, and `note`, plain ASCII. fn two_field_parts(first: &[u8], second: &[u8], ldid: u8, cpg: Option<&[u8]>) -> Vec<(String, Vec)> { @@ -707,14 +727,38 @@ fn esri_57_remains_windows_1252_rather_than_iso_8859_1() { check_ldid_readers(0x57, b"\x80\x96\x9f", "€–Ÿ", None, &[]); } -/// Malformed bytes in a declared multibyte code page are replaced with no notice yet (#2614). +/// Malformed bytes in a declared code page are replaced, and said: how many values, which fields, +/// and the code page the file declares (#2614). #[test] -fn malformed_multibyte_fields_replace_bytes_without_dropping_records() { - // Known gap (#2614): these four code pages' malformed bytes are replaced with no notice yet, so - // the empty notes below pin that behaviour rather than endorse it. - for (ldid, text) in [(0x13, b"X\x82".as_slice()), (0x4D, b"X\x81"), (0x4E, b"X\x81"), (0x4F, b"X\xa4")] { - check_ldid_readers(ldid, text, "X�", None, &[]); +fn malformed_multibyte_fields_replace_bytes_and_say_so() { + for (ldid, encoding, text) in + [(0x13, "Shift_JIS", b"X\x82".as_slice()), (0x4D, "GBK", b"X\x81"), (0x4E, "EUC-KR", b"X\x81"), (0x4F, "Big5", b"X\xa4")] + { + let said = [invalid_name_note(encoding), invalid_note(3, "X\u{FFFD}", encoding)]; + check_ldid_readers(ldid, text, "X\u{FFFD}", None, &[&said[0], &said[1]]); + } + // A `.cpg` names the page too, over a language driver that names another. + for (cpg, encoding, text) in [(b"932".as_slice(), "Shift_JIS", b"X\x82".as_slice()), (b"950", "Big5", b"X\xa4")] { + let said = [invalid_name_note(encoding), invalid_note(3, "X\u{FFFD}", encoding)]; + check_ldid_readers(0x03, text, "X\u{FFFD}", Some(cpg), &[&said[0], &said[1]]); } // Read as UTF-8, the name and the values with a byte replaced are counted. check_ldid_readers(0xF0, b"X\xff", "X�", None, &[&name_not_utf8_note(), ¬_utf8_note(3, "X�")]); } + +/// Valid text in the same pages, a value that fills its field and ends in a lead byte, and a value +/// with one bad byte among good characters: counted per value, only where it is malformed. +#[test] +fn malformed_values_are_counted_per_value_and_clean_text_says_nothing() { + // Shift_JIS: "東京" (valid) in one row, a lead byte alone in the others. + let files = two_field_parts(b"\x93\x8c\x8b\x9e", b"Y\x82", 0x13, None); + let (ds, report) = io::read_zip("places.zip", &rustgis_data::zip::write(&files).unwrap()).unwrap().remove(0); + assert_eq!(names(&ds), [Value::Text("東京".into()), Value::Text("Y\u{FFFD}".into()), Value::Text("Tainan".into())]); + assert_eq!(report.messages, [invalid_note(1, "name", "Shift_JIS")]); + // A value that fills its 32 bytes and ends in a lead byte is one malformed value. + let mut full = vec![b'A'; 31]; + full.push(0x82); + let files = parts(&full, 0x13, None); + let (_, report) = io::read_zip("places.zip", &rustgis_data::zip::write(&files).unwrap()).unwrap().remove(0); + assert_eq!(report.messages, [invalid_note(1, "name", "Shift_JIS")]); +} diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 59e4b4a23f..4458a57b99 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -733,7 +733,10 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk rustgis_data::source::null_text_note(&layer.fields, &e.null_text) .map(|n| format!("{path}: {}: {n} (empty in the export)", layer.name)), ); - dates.extend(rustgis_data::source::not_utf8_note(&layer.fields, &e.not_utf8).map(|n| format!("{path}: {}: {n}", layer.name))); + dates.extend( + rustgis_data::source::not_utf8_note(&layer.fields, &e.not_utf8, e.not_utf8_in) + .map(|n| format!("{path}: {}: {n}", layer.name)), + ); dates.extend(rustgis_data::io::utc_dates_note(&layer.fields, &e.utc_dates, path)); dates.extend(rustgis_data::io::fine_dates_note(&layer.fields, &e.fine_dates, path)); if ext == "fgb" { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b7eb5aefd7..fdf672a2a2 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2107,7 +2107,10 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Date: Sun, 22 Nov 2026 16:40:32 +0800 Subject: [PATCH 2/3] test(data): prove the declared code page reaches every notice (#2614) The streamed-shapefile engine test gains a Big5 case (language driver 0x4F) whose view read, export and conversion notices must name Big5, so Exported.not_utf8_in is tested, and a valid Big5 case that says nothing. A lead byte filling its field is also checked through a standalone .dbf and a read in place. The docs name the right test file. --- .../tests/integration/shapefile_encoding.rs | 12 +++++++ crates/engine/src/tests.rs | 34 +++++++++++++------ docs/user-guide/shapefile-encoding.md | 5 +-- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index e328a65277..60f5c3a345 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -761,4 +761,16 @@ fn malformed_values_are_counted_per_value_and_clean_text_says_nothing() { let files = parts(&full, 0x13, None); let (_, report) = io::read_zip("places.zip", &rustgis_data::zip::write(&files).unwrap()).unwrap().remove(0); assert_eq!(report.messages, [invalid_note(1, "name", "Shift_JIS")]); + // The same through a standalone `.dbf` and a read in place. + #[cfg(not(target_arch = "wasm32"))] + { + let dir = tempfile::tempdir().unwrap(); + for (name, bytes) in files { + std::fs::write(dir.path().join(name), bytes).unwrap(); + } + let (_, report) = io::read_path(&dir.path().join("places.dbf")).unwrap(); + assert_eq!(report.messages, [invalid_note(1, "name", "Shift_JIS")]); + let src = open_shp(&dir.path().join("places.shp"), "places").unwrap(); + assert_eq!(rustgis_data::source::materialize(&src).unwrap().1.messages, [invalid_note(1, "name", "Shift_JIS")]); + } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index afe38b7d5e..6c0010e253 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1744,20 +1744,33 @@ fn a_streamed_shapefile_says_text_that_isnt_utf8_once_and_in_its_exports() { let dir = Dir(std::env::temp_dir().join(format!("rustgis-streamed-not-utf8-{}-{nanos}", std::process::id()))); std::fs::create_dir_all(&dir.0).unwrap(); // What the notice must carry: the count, the field and the replacement, not its wording. - let says = |t: &str| ["1 text value", "'NAME'", "U+FFFD", ".cpg"].iter().all(|k| t.contains(k)); - // 臺北101 in Big5, and as many bytes of ASCII. - for (name, second, said) in [("big5", &b"\xbb\x4f\xa5\x5f101"[..], true), ("clean", &b"Tainan1"[..], false)] { + // `encoding` is what the text was read in, and the end of the note says why: no `.cpg` named + // another encoding for UTF-8, or that the file declares the code page. + let says = |t: &str, encoding: &str| { + let why = if encoding == "UTF-8" { "no .cpg file names another encoding".to_string() } else { format!("declares {encoding}") }; + ["1 text value", "'NAME'", "U+FFFD", ".cpg", &format!("isn't valid {encoding}"), &why].iter().all(|k| t.contains(k)) + }; + // 臺北101 in Big5, and as many bytes of ASCII. The last value is named Big5 by its language + // driver (0x4F) and ends in a lead byte; the one before it is valid Big5 and says nothing. + let cases: [(&str, &[u8], u8, Option<&str>); 4] = [ + ("big5", b"\xbb\x4f\xa5\x5f101", 0, Some("UTF-8")), + ("clean", b"Tainan1", 0, None), + ("declared", b"Taipei\xa4", 0x4F, Some("Big5")), + ("validbig5", b"\xbb\x4f\xa5\x5f101", 0x4F, None), + ]; + for (name, second, ldid, encoding) in cases { + let said = encoding.is_some(); let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("NAME", FieldType::Text)]); for (i, text) in ["Taipei", "AAAAAAA"].into_iter().enumerate() { ds.push(Some(Geometry::Point(rustgis_geom::Coord::new(i as f64, 1.0))), vec![V::Text(text.into())]); } let shp = dir.0.join(format!("{name}.shp")); rustgis_data::io::write_path(&ds, &shp).unwrap(); - // No encoding named: no `.cpg`, and no language driver in the `.dbf`. + // No `.cpg`; the language driver in the `.dbf` names the encoding, or none (0). std::fs::remove_file(shp.with_extension("cpg")).unwrap(); let dbf = shp.with_extension("dbf"); let mut table = std::fs::read(&dbf).unwrap(); - table[29] = 0; + table[29] = ldid; let at = table.windows(7).position(|w| w == b"AAAAAAA").unwrap(); table[at..at + 7].copy_from_slice(second); std::fs::write(&dbf, table).unwrap(); @@ -1766,7 +1779,7 @@ fn a_streamed_shapefile_says_text_that_isnt_utf8_once_and_in_its_exports() { let id = added["layer"].as_u64().unwrap() as u32; assert!(s.map().layer(id).unwrap().is_streamed(), "{name} is read in place"); let not_utf8 = |s: &Session, mark| -> Vec { - s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("valid UTF-8")).collect() + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("valid UTF-8") || t.contains("valid Big5")).collect() }; let mark = s.notice_mark(); let view = rustgis_geom::Extent::new(-180.0, -90.0, 180.0, 90.0); @@ -1781,8 +1794,9 @@ fn a_streamed_shapefile_says_text_that_isnt_utf8_once_and_in_its_exports() { assert!(!s.map().layer(id).unwrap().dataset.features.is_empty(), "{name}: the second read lands"); let notes = not_utf8(&s, mark); assert_eq!(notes.len(), usize::from(said), "{name}: view reads: {notes:?}"); - if said { - assert!(notes[0].starts_with("big5: ") && notes[0].contains("Load All Features") && says(¬es[0]), "{}", notes[0]); + if let Some(encoding) = encoding { + let note = ¬es[0]; + assert!(note.starts_with(&format!("{name}: ")) && note.contains("Load All Features") && says(note, encoding), "{note}"); } // An export a chunk at a time, and a Data Interop conversion of the source, say it. s.map_mut().layer_mut(id).unwrap().dataset.features.clear(); @@ -1794,8 +1808,8 @@ fn a_streamed_shapefile_says_text_that_isnt_utf8_once_and_in_its_exports() { s.run(command, ¶ms).unwrap(); let notes = not_utf8(&s, mark); assert_eq!(notes.len(), usize::from(said), "{name} {command}: {:?}", s.notices_since(mark)); - if said { - assert!(notes[0].contains("big5: ") && says(¬es[0]), "{}", notes[0]); + if let Some(encoding) = encoding { + assert!(notes[0].contains(&format!("{name}: ")) && says(¬es[0], encoding), "{command}: {}", notes[0]); } } } diff --git a/docs/user-guide/shapefile-encoding.md b/docs/user-guide/shapefile-encoding.md index 123fefdf35..03a761bd3d 100644 --- a/docs/user-guide/shapefile-encoding.md +++ b/docs/user-guide/shapefile-encoding.md @@ -66,7 +66,8 @@ fields, and another counts such field names. A file whose text is all valid UTF- Text read in a code page that is decoded here (932 Shift_JIS, 936 GBK, 949 EUC-KR, 950 Big5, the Windows pages and the rest) is counted the same way when its bytes aren't valid in that page: the notices say how many values and field names, in which fields, and that the `.cpg` or the `.dbf`'s -language driver declares it. The DOS pages (437, 850, 852, 861, 865) give every byte a character, so nothing in them is replaced. +language driver declares it. The DOS pages (437, 850, 852, 861, 865) give every byte a +character, so nothing in them is replaced. The existing transitive `yore` 1.4.0 package has CP737, CP857, CP860 and CP863 decoders, but RustGIS's current `dbase` adapter does not expose them. Making these available would @@ -88,7 +89,7 @@ tables or system programs are needed for the supported decoders above. - [`yore`'s `CodePage` implementations](https://docs.rs/yore/1.4.0/yore/trait.CodePage.html#implementors) list the available legacy decoders and lossy decoding API. -`crates/data/tests/shapefile_encoding.rs` specifies fixed bytes and Unicode expectations +`crates/data/tests/integration/shapefile_encoding.rs` specifies fixed bytes and Unicode expectations independently of RustGIS's mapping. Its matrix covers every marker above, names and values, ZIP and loose-file imports, a genuinely sampled streamed read, a complete read, and ordered chunk traversal. It also checks `.cpg` precedence, fallback diagnostics, the notices for text From a9050d789b04bca1710e9a19d306dc46b54d22c9 Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:36:38 +0000 Subject: [PATCH 3/3] fix(map): name the encoding pending not-UTF-8 counts were read in The note for text values that aren't valid UTF-8 took its encoding from the source handle at the time it was said, not from the handle the counts were kept from. If the source was opened again in between, a Big5 or Shift_JIS layer's counts could be reported as not valid UTF-8. Record the encoding with the counts when they are kept, use it when the note is taken, and clear it in reopen with the counts. Counts from a different encoding replace the pending ones rather than adding to them. Applied by the claude-autofix workflow. --- crates/map/src/source.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index d63353bed0..4ee1b74e17 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -158,6 +158,10 @@ pub struct SourceLayer { /// Text values a view read found weren't UTF-8 ([`Batch::not_utf8`]), likewise. #[serde(skip)] not_utf8: Option>, + /// The encoding `not_utf8` counts were read in, taken when they were kept: the source may be + /// opened again before they are said. + #[serde(skip)] + not_utf8_in: Option<&'static str>, #[serde(skip)] not_utf8_said: bool, /// What else view reads lost or assumed ([`Batch::notes`]), until said by @@ -833,6 +837,12 @@ impl SourceLayer { /// [`SourceLayer::take_not_utf8`] says it, as [`SourceLayer::saw_unread_dates`] does for dates. pub fn saw_not_utf8(&mut self, counts: &[usize]) { if !self.not_utf8_said && counts.iter().any(|n| *n > 0) { + let encoding = self.handle.as_ref().map_or("UTF-8", |h| h.text_encoding()); + // Counts of another encoding are of another opening's text: they aren't added to these. + if self.not_utf8_in != Some(encoding) { + self.not_utf8 = None; + } + self.not_utf8_in = Some(encoding); rustgis_data::source::add_unread_dates(self.not_utf8.get_or_insert_with(Vec::new), counts); } } @@ -845,7 +855,7 @@ impl SourceLayer { let fields = self.info().map(|i| i.fields.clone())?; let counts = self.not_utf8.take()?; self.not_utf8_said = true; - rustgis_data::source::not_utf8_note(&fields, &counts, self.handle.as_ref().map_or("UTF-8", |h| h.text_encoding())) + rustgis_data::source::not_utf8_note(&fields, &counts, self.not_utf8_in.take().unwrap_or("UTF-8")) } /// Keeps what view reads said they lost or assumed ([`Batch::notes`]) until @@ -1647,6 +1657,7 @@ impl SourceLayer { self.null_text = None; self.null_text_said = false; self.not_utf8 = None; + self.not_utf8_in = None; self.not_utf8_said = false; self.forget_read_notes(); self.reset(); @@ -1978,6 +1989,7 @@ impl SourceLayer { null_text: _, null_text_said: _, not_utf8: _, + not_utf8_in: _, not_utf8_said: _, read_notes: _, read_note_kinds: _,