Skip to content
Open
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
297 changes: 292 additions & 5 deletions crates/data/src/date.rs

Large diffs are not rendered by default.

32 changes: 11 additions & 21 deletions crates/data/src/filegdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,16 +471,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
}
ds.push_next(geometry, attrs);
}
let rounded: usize = rounded_dates.iter().sum();
if rounded > 0 {
report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::ChangedRounded,
format!(
"{rounded} serial date values were rounded to the nearest microsecond, in {}",
crate::io::named_fields(&ds.fields, &rounded_dates)
),
));
}
report.rounded_dates = crate::source::rounded_serials_note(&ds.fields, &rounded_dates);
report.messages.extend(report.rounded_dates.clone());
report.unread_dates = crate::source::unread_dates_note(&ds.fields, &unread_dates);
report.messages.extend(report.unread_dates.clone());
if curves > 0 {
Expand Down Expand Up @@ -866,12 +858,14 @@ impl Table {
let text = |b: &[u8]| if self.utf8 { String::from_utf8_lossy(b).into_owned() } else { utf16(b) };
let cell = |value: Value| Cell { value, blob: None, invalid_date: false, rounded_date: false };
let date_cell = |days: f64, offset: Option<i16>, only: bool| {
let value = match gdb_datetime(days, offset) {
let (value, rounded) = gdb_datetime(days, offset);
let value = match value {
Value::DateTime(t) if only && t.is_date() => Value::Date(t.date()),
Value::DateTime(_) if only => Value::Null,
v => v,
};
let rounded_date = !value.is_null() && serial_rounds(days);
// A date-only field keeps only the day, so nothing of the microsecond is lost.
let rounded_date = rounded && !only && !value.is_null();
Cell { invalid_date: value.is_null(), rounded_date, value, blob: None }
};
out.push(match f.kind {
Expand Down Expand Up @@ -913,20 +907,16 @@ fn float(v: f64) -> Value {
if v.is_finite() { Value::Float(v) } else { Value::Null }
}

/// Whether the floating-point serial has precision below the microsecond RustGIS stores.
fn serial_rounds(days: f64) -> bool {
crate::date::serial_datetime(days, -25_569).is_some_and(|(_, rounded)| rounded)
}

/// FileGDB days count from 1899-12-30. Offset fields store local clock days and minutes east
/// of UTC. Round the binary floating-point serial to microseconds, retaining its precision.
fn gdb_datetime(days: f64, offset: Option<i16>) -> Value {
let Some((wall, _)) = crate::date::serial_datetime(days, -25_569) else { return Value::Null };
/// of UTC. Round the binary floating-point serial to microseconds, retaining its precision; the
/// boolean says the serial held more than the microsecond.
fn gdb_datetime(days: f64, offset: Option<i16>) -> (Value, bool) {
let Some((wall, rounded)) = crate::date::binary_serial_datetime(days, -25_569) else { return (Value::Null, false) };
let t = match offset {
None => Some(wall),
Some(off) => wall.micros().checked_sub(i64::from(off) * 60_000_000).and_then(|v| crate::DateTime::with_offset(v, off)),
};
t.map(Value::DateTime).unwrap_or_default()
(t.map(Value::DateTime).unwrap_or_default(), rounded)
}

/// Days since 1899-12-30 as text in `fmt`.
Expand Down
33 changes: 26 additions & 7 deletions crates/data/src/filegdb/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -970,17 +970,36 @@ fn filegdb_temporal_fields_keep_days_offsets_and_null_notices() {
);
assert!(report.unread_dates.unwrap().starts_with("1 value"));
assert!(ds.features[1].attrs.iter().all(Value::is_null));
assert_eq!(gdb_datetime(25_569.5, None).to_string(), "1970-01-01T12:00:00");
assert!(gdb_datetime(25_569.0, Some(i16::MIN)).is_null());
assert!(gdb_datetime(1e100, None).is_null());
// Exercise the reader/report boundary as well as the shared serial helper.
for (serial, rounded) in [(45_000.5, false), (45_000.1, true)] {
assert_eq!(gdb_datetime(25_569.5, None).0.to_string(), "1970-01-01T12:00:00");
assert!(gdb_datetime(25_569.0, Some(i16::MIN)).0.is_null());
assert!(gdb_datetime(1e100, None).0.is_null());
// A date-only field keeps the day: a time finer than the microsecond in it isn't counted.
let (t, x) = table(0, &[F::Date("day", 14)], &[vec![V::Date(Some((45_000.0 + 0.123_456_789 / 86_400.0, None)))]]);
let (ds, report) = read_table("dates", &t, &x, None).unwrap().unwrap();
assert!(report.rounded_dates.is_none(), "{report:?}");
assert!(ds.value(0, 0).is_null(), "a time of day isn't a date: {:?}", ds.value(0, 0));
// Exercise the reader/report boundary as well as the shared serial helper. 45000.1 isn't
// 45000.1 in binary, but it is the f64 02:24:00 makes, so nothing finer was lost (#1894);
// a File Geodatabase stores a binary double, so 45000.123456789, which isn't the f64 nearest
// any microsecond, held more than one (a workbook's 15 digits of text would be excused);
// serials holding more than the microsecond are rounded and said.
for (serial, rounded) in [
(45_000.5, false),
(45_000.1, false),
(1.0 + 0.123_456_789 / 86_400.0, true),
(45_000.123_456_789, true),
(45_000.0 + 0.123_456_789 / 86_400.0, true),
] {
let (t, x) = table(0, &[F::Date("moment", 5)], &[vec![V::Date(Some((serial, None)))]]);
let (_, report) = read_table("dates", &t, &x, None).unwrap().unwrap();
let notices: Vec<_> = report.messages.iter().filter(|n| n.contains("rounded to the nearest microsecond")).collect();
let notices: Vec<_> = report.messages.iter().filter(|n| n.contains("rounded to the microsecond")).collect();
assert_eq!(notices.len(), usize::from(rounded), "{serial}: {report:?}");
assert_eq!(report.rounded_dates.is_some(), rounded, "{serial}");
if rounded {
assert!(notices[0].contains("1 serial date") && notices[0].contains("moment"));
assert_eq!(
notices[0].as_str(),
"1 date-time was rounded to the microsecond, as more digits than that aren't kept, in 'moment'"
);
assert_eq!(notices[0].loss, Some(crate::loss::LossCode::ChangedRounded));
}
}
Expand Down
36 changes: 32 additions & 4 deletions crates/data/src/gpx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,20 +176,26 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
if let Some(field) = ds.fields.get_mut(k) {
field.ty = FieldType::DateTime;
}
let mut counts = Vec::new();
let (mut counts, mut rounded) = (Vec::new(), Vec::new());
for feature in &mut ds.features {
crate::progress::step(1)?;
if let Some(value @ Value::Text(_)) = feature.attrs.get_mut(k) {
let Value::Text(s) = &*value else { continue };
let parsed = crate::DateTime::parse(s).filter(|_| s.contains(['T', 't']));
if parsed.is_none() {
// Digits past the microsecond (.NET writes seven) are rounded to it and counted.
let (parsed, was_rounded) =
if s.contains(['T', 't']) { Value::parse_stored_counted(s, FieldType::DateTime) } else { (Value::Null, false) };
if parsed.is_null() {
crate::source::unread_date(&mut counts, k);
} else if was_rounded {
crate::source::unread_date(&mut rounded, k);
}
*value = parsed.map(Value::DateTime).unwrap_or_default();
*value = parsed;
}
}
report.unread_dates = crate::source::unread_dates_note(&ds.fields, &counts);
report.messages.extend(report.unread_dates.clone());
report.rounded_dates = crate::source::rounded_dates_note(&ds.fields, &rounded);
report.messages.extend(report.rounded_dates.clone());
}
out.push((ds, report));
}
Expand Down Expand Up @@ -321,6 +327,28 @@ mod tests {
assert!(read("clean.gpx", GPX.as_bytes()).unwrap().iter().all(|(_, r)| r.unread_dates.is_none()));
}

/// A time with seven fractional digits, as .NET's round-trip format writes it, is rounded to
/// the microsecond and said, not read as empty (#1894); six digits are kept as they are.
#[test]
fn gpx_times_past_the_microsecond_are_rounded_and_said() {
let gpx = |time: &str| {
format!(r#"<gpx><wpt lat="1" lon="1"><time>{time}</time></wpt><wpt lat="2" lon="2"><time>{time}</time></wpt></gpx>"#)
};
let layers = read("net.gpx", gpx("2019-07-04T12:30:15.1234567Z").as_bytes()).unwrap();
let (ds, report) = &layers[0];
let k = ds.field_index("time").unwrap();
assert_eq!(ds.value(0, k).to_string(), "2019-07-04T12:30:15.123457Z");
assert_eq!(report.unread_dates, None);
let note = report.rounded_dates.as_ref().map(crate::loss::Note::as_str).unwrap();
assert_eq!(note, "2 date-times were rounded to the microsecond, as more digits than that aren't kept, in 'time'");
assert_eq!(report.messages.iter().filter(|m| m.contains("rounded to the microsecond")).count(), 1, "{report:?}");
let layers = read("six.gpx", gpx("2019-07-04T12:30:15.123456Z").as_bytes()).unwrap();
let (ds, report) = &layers[0];
assert_eq!(ds.value(0, k).to_string(), "2019-07-04T12:30:15.123456Z");
assert_eq!((report.rounded_dates.as_ref(), report.unread_dates.as_ref()), (None, None));
assert!(report.messages.is_empty(), "{report:?}");
}

#[test]
fn hostile_input() {
assert!(read("x.gpx", b"<kml/>").is_err());
Expand Down
53 changes: 46 additions & 7 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3617,6 +3617,17 @@ fn read_csv_with_budget(text: &str, name: &str, opts: &CsvOptions, budget: &mut
read_csv_records(&mut rdr, name, opts, budget, None)
}

/// What a workbook knows of a sheet's columns beyond their text, by column ([`read_rows`]).
#[derive(Clone, Copy)]
pub(crate) struct Workbook<'a> {
/// The type its cells give a column, which overrides text inference.
pub types: &'a [Option<FieldType>],
/// Date cells of a day that never was (serial 60), read as empty.
pub phantom_dates: &'a [usize],
/// Serial date-times that held more than the microsecond, rounded to it.
pub rounded_dates: &'a [usize],
}

/// Rows of text cells under a header row (delimited text, a spreadsheet's sheet) as a dataset, as
/// [`read_csv_with`] describes; `malformed` rows were already passed over. A workbook gives its
/// cell types, which may override text inference by source column, and the dates it already read
Expand All @@ -3627,9 +3638,9 @@ pub(crate) fn read_rows(
malformed: usize,
name: &str,
opts: &CsvOptions,
workbook: Option<(&[Option<FieldType>], &[usize])>,
workbook: Option<Workbook<'_>>,
) -> Result<(Dataset, ReadReport)> {
let types = workbook.map(|(types, _)| types);
let types = workbook.map(|wb| wb.types);
let position = |n: &str| headers.iter().position(|h| h.trim().eq_ignore_ascii_case(n));
let named = |n: &Option<String>, what: &str| -> Result<Option<usize>> {
match n.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
Expand Down Expand Up @@ -3703,17 +3714,23 @@ pub(crate) fn read_rows(
let gt = if xy.is_some() { GeometryType::Point } else { GeometryType::None };
let mut ds = Dataset::new(name, gt, fields);
let mut srid: Option<u32> = None;
let (mut unread_dates, mut null_text, mut whitespace) = (Vec::new(), Vec::new(), Vec::new());
for (k, &i) in columns.iter().enumerate() {
crate::source::unread_dates_by(&mut unread_dates, k, workbook.and_then(|(_, empty)| empty.get(i)).copied().unwrap_or(0));
let (mut unread_dates, mut null_text, mut whitespace, mut rounded_dates) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
for (k, (&i, field)) in columns.iter().zip(&ds.fields).enumerate() {
crate::source::unread_dates_by(&mut unread_dates, k, workbook.and_then(|wb| wb.phantom_dates.get(i)).copied().unwrap_or(0));
// A workbook's serial date-times that held more than the microsecond, counted with the
// date-time text rounded below: one notice says both. A date field keeps only the day,
// so nothing of the microsecond is lost there.
if field.ty != FieldType::Date {
crate::source::unread_dates_by(&mut rounded_dates, k, workbook.and_then(|wb| wb.rounded_dates.get(i)).copied().unwrap_or(0));
}
}
// The WKT column is the geometry, not a field: a workbook date there that never was is empty,
// 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) {
match workbook.and_then(|wb| wb.phantom_dates.get(w)).copied().unwrap_or(0) {
0 => {}
1 => report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
Expand Down Expand Up @@ -3771,7 +3788,15 @@ pub(crate) fn read_rows(
if marker {
crate::source::null_text_at(&mut null_text, k);
}
let value = Value::parse_file(&text, f.ty);
// A date-time with digits past the microsecond (a workbook's ISO cell, as .NET
// writes them) is rounded to it and counted, not dropped.
let (value, rounded) = match f.ty {
FieldType::DateTime => Value::parse_stored_counted(&text, f.ty),
_ => (Value::parse_file(&text, f.ty), false),
};
if rounded {
crate::source::unread_date(&mut rounded_dates, k);
}
if value.is_null() && f.ty != FieldType::Text && !text.is_empty() && text.trim().is_empty() {
crate::source::null_text_at(&mut whitespace, k);
}
Expand Down Expand Up @@ -3880,6 +3905,8 @@ pub(crate) fn read_rows(
}
report.unread_dates = crate::source::unread_dates_note(&ds.fields, &unread_dates);
report.messages.extend(report.unread_dates.clone());
report.rounded_dates = crate::source::rounded_serials_note(&ds.fields, &rounded_dates);
report.messages.extend(report.rounded_dates.clone());
report.messages.extend(crate::source::null_text_note(&ds.fields, &null_text));
let total: usize = whitespace.iter().sum();
if total > 0 {
Expand Down Expand Up @@ -9965,6 +9992,18 @@ mod tests {
assert_eq!(to_csv(&back).unwrap(), once, "export/import is stable");
}

/// Delimited text never types a column as dates, so date-time text with digits past the
/// microsecond is kept as it is written, and nothing is said; six digits likewise.
#[test]
fn csv_date_time_text_is_kept_as_written() {
for time in ["2019-07-04T12:30:15.1234567Z", "2019-07-04T12:30:15.123456Z"] {
let (ds, report) = read_csv(&format!("when\n{time}\n"), "t").unwrap();
assert_eq!(ds.fields[0].ty, FieldType::Text);
assert_eq!(ds.value(0, 0), &Value::Text(time.into()));
assert!(report.messages.is_empty() && report.rounded_dates.is_none(), "{report:?}");
}
}

/// `<Null>` in a `.dbf` date column is counted once, as the marker, not also as a date that
/// isn't one, whole and streamed.
#[test]
Expand Down
Loading
Loading