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
168 changes: 148 additions & 20 deletions crates/data/src/dbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,14 +368,7 @@ pub(crate) fn raw_table(dbf: &[u8]) -> Option<RawTable<'_>> {
let le16 = |at: usize| Some(usize::from(u16::from_le_bytes([*dbf.get(at)?, *dbf.get(at + 1)?])));
let count = usize::try_from(u32::from_le_bytes(dbf.get(4..8)?.try_into().ok()?)).ok()?;
let (header_len, record_len) = (le16(8)?, le16(10)?);
let mut columns = Vec::new();
for start in (32..header_len.min(dbf.len())).step_by(32) {
let d = dbf.get(start..start + 32).filter(|d| d.first() != Some(&0x0D));
let Some(d) = d else { break };
let name = d.get(..11)?;
let name = name.get(..name.iter().position(|b| *b == 0).unwrap_or(11))?.to_vec();
columns.push(Column { name, ty: *d.get(11)?, len: *d.get(16)?, decimals: *d.get(17)? });
}
let columns = column_descriptors(dbf, header_len)?;
let width: usize = 1 + columns.iter().map(|c| usize::from(c.len)).sum::<usize>();
if width != record_len || record_len == 0 {
return None;
Expand Down Expand Up @@ -405,6 +398,98 @@ pub(crate) fn raw_table(dbf: &[u8]) -> Option<RawTable<'_>> {
Some(RawTable { columns, records, deleted })
}

/// Reads the column descriptors for Publish without decoding field values.
#[cfg(not(target_arch = "wasm32"))]
fn column_descriptors(dbf: &[u8], header_len: usize) -> Option<Vec<Column>> {
let mut columns = Vec::new();
for start in (32..header_len.min(dbf.len())).step_by(32) {
let d = dbf.get(start..start + 32).filter(|d| d.first() != Some(&0x0D));
let Some(d) = d else { break };
columns.push(column_descriptor(d)?);
}
Some(columns)
}

fn column_descriptor(d: &[u8]) -> Option<Column> {
let name = d.get(..11)?.split(|b| *b == 0).next()?.to_vec();
Some(Column { name, ty: *d.get(11)?, len: *d.get(16)?, decimals: *d.get(17)? })
}

/// The generated descriptors precede the first record even if the writer's header length wrapped.
pub(crate) fn written_declarations(dbf: &[u8], count: usize) -> Option<Vec<Column>> {
let end = count.checked_mul(32)?.checked_add(32)?;
dbf.get(32..end)?.as_chunks::<32>().0.iter().map(|d| column_descriptor(d)).collect()
}

impl Column {
/// Compares on-disk types and widths. Legacy character widths use the decimals byte as
/// the high byte of their width.
pub(crate) fn same_declaration(&self, other: &Self) -> bool {
let width = |c: &Self| {
if c.ty.eq_ignore_ascii_case(&b'C') { (u16::from_le_bytes([c.len, c.decimals]), 0) } else { (u16::from(c.len), c.decimals) }
};
self.ty.eq_ignore_ascii_case(&other.ty) && width(self) == width(other)
}
}

/// Reads only the bounded header, stopping the descriptor scan at a terminator or the
/// declared end. Record width and padding after the descriptors do not affect comparison.
pub(crate) fn read_declarations(path: &std::path::Path) -> std::io::Result<(Vec<Column>, u8)> {
use std::io::{Error, ErrorKind, Read};
let invalid = || Error::new(ErrorKind::InvalidData, "incomplete DBF descriptors");
let (file, size) = open_declaration_file(path)?;
if size < 32 {
return Err(invalid());
}
let mut file = file.take(size);
let mut first = [0; 32];
file.read_exact(&mut first)?;
let header_len = u64::from(u16::from_le_bytes([first[8], first[9]])).checked_sub(32).ok_or_else(invalid)?;
let mut header = Vec::new();
file.take(header_len).read_to_end(&mut header)?;
let mut columns = Vec::new();
for start in (0..header_len as usize).step_by(32) {
if header.get(start) == Some(&0x0D) {
break;
}
if start + 32 > header_len as usize {
return Err(invalid());
}
let descriptor = header.get(start..start + 32).and_then(column_descriptor).ok_or_else(invalid)?;
columns.push(descriptor);
}
Ok((columns, first[29]))
}

/// Decodes only those names that need a code page. A metadata read error or an unknown
/// language driver leaves those names unresolved without affecting the ASCII descriptors.
pub(crate) fn declaration_names(path: &std::path::Path, columns: &[Column], ldid: u8) -> Vec<Option<String>> {
use shapefile::dbase::Encoding;
let mut encoding = None;
columns
.iter()
.map(|column| {
if column.name.is_ascii() {
return std::str::from_utf8(&column.name).ok().map(str::to_owned);
}
let (encoding, decoder) = encoding
.get_or_insert_with(|| {
let cpg = read_declaration_cpg(path).ok()?;
let encoding = cpg_encoding(cpg.as_deref()).or_else(|| {
if ldid == 0 { Some(DbfEncoding::Utf8) } else { ldid_code_page(ldid).and_then(DbfEncoding::from_number) }
})?;
let decoder = encoding.decoder();
Some((encoding, decoder))
})
.as_ref()?;
if encoding.malformed(&column.name) {
return None;
}
decoder.decode(&column.name).ok().map(|name| name.into_owned())
})
.collect()
}

/// A date (`D`) field's value, `YYYYMMDD`: `Ok(None)` when it's blank or zeros, as writers leave
/// a date empty, and `Err(())` when it isn't a date (`20260230`, `2026-3-5`). A year padded with
/// spaces (` 10101`, year 1, as GDAL writes it with `%4d`) is read as the zeros it stands for.
Expand Down Expand Up @@ -509,29 +594,72 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result<Option<Vec<u8>>> {
Ok(None)
}

/// Checks before and after opening. Unix nonblocking open covers a FIFO swapped in between;
/// regular-file leases retry with cancellation between attempts instead of blocking in the kernel.
pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
/// Reads the first present code-page spelling without recording a provenance input.
fn read_declaration_cpg(path: &std::path::Path) -> std::io::Result<Option<Vec<u8>>> {
use std::io::{Error, ErrorKind, Read};
for ext in CPG_SPELLINGS {
let sidecar = path.with_extension(ext);
match open_declaration_file(&sidecar) {
Ok((file, size)) => {
let mut bytes = Vec::new();
file.take(size.min(MAX_CPG_BYTES as u64 + 1)).read_to_end(&mut bytes)?;
return Ok(Some(bytes));
}
Err(e) if e.kind() == ErrorKind::NotFound => {
if std::fs::symlink_metadata(sidecar).is_ok() {
return Err(Error::other("the .cpg has no readable target"));
}
}
Err(e) => return Err(e),
}
}
Ok(None)
}

/// Checks the path and the opened handle. A FIFO swapped in after the first check, or a
/// write lease on Unix, cannot block the open. Reads are limited to the reported file size,
/// so size-zero pseudo-files such as `/proc/kmsg` and `trace_pipe` aren't read.
fn open_declaration_file(path: &std::path::Path) -> std::io::Result<(std::fs::File, u64)> {
let file = open_regular_file_now(path)?.ok_or_else(|| std::io::Error::other("not a regular file"))?;
let size = file.metadata()?.len();
Ok((file, size))
}

/// Checks the path and opened descriptor, making one nonblocking attempt without provenance.
/// Comparisons use this directly: waiting on a lease would change the export's write behavior.
fn open_regular_file_now(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
if !std::fs::metadata(path)?.is_file() {
return Ok(None);
}
#[cfg(unix)]
let file = loop {
let file = {
use rustix::fs::{Mode, OFlags, open};
match open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty()) {
Ok(fd) => break std::fs::File::from(fd),
Err(rustix::io::Errno::AGAIN) => {
crate::progress::check().map_err(std::io::Error::other)?;
std::thread::sleep(std::time::Duration::from_millis(20));
}
Err(e) => return Err(e.into()),
}
std::fs::File::from(open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty())?)
};
#[cfg(not(unix))]
let file = std::fs::File::open(path)?;
Ok(file.metadata()?.is_file().then_some(file))
}

/// Regular-file leases retain their cancellable wait for imports and Publish. Comparisons
/// use the one-attempt opener instead; neither opener records a destination as a source input.
pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
#[cfg(not(unix))]
{
open_regular_file_now(path)
}
#[cfg(unix)]
loop {
match open_regular_file_now(path) {
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
crate::progress::check().map_err(std::io::Error::other)?;
std::thread::sleep(std::time::Duration::from_millis(20));
}
result => return result,
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
5 changes: 4 additions & 1 deletion crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,10 @@ fn a_streamed_export_into_an_existing_geopackage_starts_again_inside_its_transac
let src = Runs::new(&both, 4);
let (e, table) = write_chunks_to(&src, &layer, &county, Crs::LonLat, &add, 1, None).unwrap();
assert_eq!(src.passes.load(std::sync::atomic::Ordering::Relaxed), 3, "written three times");
assert_eq!((e.written, table), (20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![] })));
assert_eq!(
(e.written, table),
(20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![], declaration_changes: Default::default() }))
);
let whole = d.join("whole.gpkg");
crate::io::write_path(&both, &whole).unwrap();
let read = |p: &Path, t: &str| {
Expand Down
Loading
Loading