diff --git a/crates/data/src/date.rs b/crates/data/src/date.rs index 140e56cfc9..28e1398c2c 100644 --- a/crates/data/src/date.rs +++ b/crates/data/src/date.rs @@ -301,16 +301,172 @@ impl<'de> Deserialize<'de> for DateTime { /// A binary floating-point day count from an epoch, rounded to microseconds. Split whole /// days before scaling: scaling an absolute date as f64 loses low time bits in distant years. -/// The boolean says that fractional microseconds were rounded, for the reader's notice. +/// A serial a known program computes (days plus a fraction, Unix seconds or milliseconds over a +/// day's) reads as the time it stores, a whole second or millisecond; any other as the nearest +/// microsecond. The boolean says that the serial held more than its microsecond, for the +/// reader's notice: no way a program stores that microsecond gives this f64 +/// ([`stores_microsecond`]). A whole-minute serial such as 45000.1 (02:24:00) isn't exact in +/// binary, but it is the f64 nearest its minute, so nothing was lost. For a workbook's serial, +/// which a program may compute or write as text; [`binary_serial_datetime`] for one stored as a +/// binary double. pub(crate) fn serial_datetime(days: f64, epoch: i64) -> Option<(DateTime, bool)> { + serial_datetime_as(days, epoch, Serial::Workbook) +} + +/// As [`serial_datetime`], for a serial stored as a binary double (a File Geodatabase's): one a +/// known program computes (days plus a fraction, Unix milliseconds over a day's, Unix seconds over +/// 3600 over 24) reads as the time it stores, a whole second or millisecond, else as the nearest +/// microsecond; it held more than its microsecond unless it is the f64 nearest it or +/// one a program computes for it ([`stores_microsecond`]), never decimal text. +pub(crate) fn binary_serial_datetime(days: f64, epoch: i64) -> Option<(DateTime, bool)> { + serial_datetime_as(days, epoch, Serial::Binary) +} + +/// How a serial was stored, for what could have made it ([`stores_microsecond`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Serial { + /// A workbook's number: computed, or written as decimal text. + Workbook, + /// A binary double a program computed (a File Geodatabase's). + Binary, +} + +/// [`serial_datetime`], for a serial stored as `kind` says. +fn serial_datetime_as(days: f64, epoch: i64, kind: Serial) -> Option<(DateTime, bool)> { if !days.is_finite() || days.abs() > 4_000_000.0 { return None; } let whole = days.floor() as i64; let day = Date::from_days(whole.checked_add(epoch)?)?; - let fraction = (days - whole as f64) * DAY_US as f64; - let micros = day.sort_key().checked_add(fraction.round() as i64)?; - DateTime::local(micros).map(|t| (t, fraction.fract() != 0.0)) + // The fraction of the day and its microseconds are each rounded once; the errors of both are + // recovered (Knuth's two-sum for `days - whole`, which isn't exact between -0.5 and 0; + // Dekker's two-product for the scaling, which needs no fused multiply-add), so `off` is how + // far the serial is from the microsecond read, in microseconds, to within a rounding of its + // own. + let minus_whole = -(whole as f64); + let fraction = days + minus_whole; + let (back_minus, back_days) = (fraction - days, fraction - (fraction - days)); + let lost = (days - back_days) + (minus_whole - back_minus); + let scaled = fraction * DAY_US as f64; + let rounded = scaled.round(); + let off = (scaled - rounded) + product_error(fraction, DAY_US as f64, scaled) + lost * DAY_US as f64; + let part = rounded as i64; + // The microsecond a way of storing it gives, else the nearest one, and said to be rounded. A + // computed second or millisecond can be a microsecond from the nearest one, and several past + // day 65536 (2079), where an f64's step passes a microsecond. + let (part, held_more) = match stores_microsecond(days, whole, part, off, epoch, kind) { + Some(stored) => (stored, false), + None => (part, true), + }; + let micros = day.sort_key().checked_add(part)?; + DateTime::local(micros).map(|t| (t, held_more)) +} + +/// The microseconds into day `whole` that `days` stores, when it is the f64 some common way of +/// storing a time gives (`part` is the microsecond nearest it, and `off` how far `days` is from +/// that, in microseconds; `epoch` is the day 1970-01-01 is, counted from the serial's day 0, +/// negated); `None` when it is none of them, so it held more than a microsecond. First the ways a +/// program computes one from a whole second or millisecond, each tried at the one nearest `days` +/// and giving it exactly (from day 65536, 2079, an f64's step passes a microsecond, so the +/// nearest microsecond can be several from the second meant): +/// - the whole days plus the day's fraction, rounded on its own (`DATE() + TIME()`, +/// `45000 + s / 86400`); +/// - the milliseconds since 1970 over a day's, plus the epoch's days +/// (`unix_ms / 86400000 + 25569`), which rounds at the size of the days since 1970 first; +/// - the seconds since 1970 over an hour's, then a day's hours, plus the epoch's days +/// (`unix_s / 3600 / 24 + 25569`), which rounds twice on the way; +/// +/// then, at the microsecond nearest `days`: +/// - the f64 nearest the time (within half its unit in the last place). From day 65536 on every +/// serial is the nearest to its microsecond, and a loss finer than that can't be seen; +/// - the whole days plus the day's fraction, as above; +/// - the time's decimal text to 15 significant digits, as some programs write a number. +/// +/// The last applies only to a [`Serial::Workbook`]: decimal text is how a workbook writes a +/// number, not how a binary double is stored. The others are ways any program computes one. +fn stores_microsecond(days: f64, whole: i64, part: i64, off: f64, epoch: i64, kind: Serial) -> Option { + let days_plus = |p: i64| whole as f64 + p as f64 / DAY_US as f64 == days; + let since_1970 = whole.checked_add(epoch); + let unix_ms = |p: i64| { + p % 1000 == 0 + && since_1970 + .and_then(|d| d.checked_mul(86_400_000)) + .and_then(|ms| ms.checked_add(p / 1000)) + .is_some_and(|ms| ms as f64 / 86_400_000.0 - epoch as f64 == days) + }; + let unix_s = |p: i64| { + p % 1_000_000 == 0 + && since_1970 + .and_then(|d| d.checked_mul(86_400)) + .and_then(|s| s.checked_add(p / 1_000_000)) + .is_some_and(|s| s as f64 / 3600.0 / 24.0 - epoch as f64 == days) + }; + let second = (part + 500_000).div_euclid(1_000_000).checked_mul(1_000_000); + let milli = (part + 500).div_euclid(1000).checked_mul(1000); + if let Some(p) = [second, milli].into_iter().flatten().find(|&p| days_plus(p) || unix_ms(p) || unix_s(p)) { + return Some(p); + } + let size = days.abs(); + let unit = f64::from_bits(size.to_bits() + 1) - size; + if off.abs() <= unit / 2.0 * DAY_US as f64 || days_plus(part) { + return Some(part); + } + // Decimal text is how a workbook writes a number; a binary double isn't stored that way. + let text = i128::from(whole).checked_mul(i128::from(DAY_US)).and_then(|n| n.checked_add(i128::from(part))).and_then(fifteen_digits); + (kind == Serial::Workbook && text == Some(days)).then_some(part) +} + +/// The f64 of `n` microseconds' days written to 15 significant digits (halves away from zero) and +/// read back. +fn fifteen_digits(n: i128) -> Option { + let day = i128::from(DAY_US); + let a = n.checked_abs()?; + if a == 0 { + return Some(0.0); + } + // The power of ten of the leading digit: a / day >= 10^e. + let at_least = |e: i32| -> Option { + let ten = |k: i32| 10i128.checked_pow(k.unsigned_abs()); + Some(if e >= 0 { a >= day.checked_mul(ten(e)?)? } else { a.checked_mul(ten(e)?)? >= day }) + }; + let mut e = 8; + while e > -20 && !at_least(e)? { + e -= 1; + } + let scale = u32::try_from(14 - e).ok()?; + let scaled = a.checked_mul(10i128.checked_pow(scale)?)?; + let digits = scaled.checked_mul(2)?.checked_add(day)? / day.checked_mul(2)?; + let sign = if n < 0 { "-" } else { "" }; + format!("{sign}{digits}e-{scale}").parse().ok() +} + +/// The rounding error of `p = a * b`, exactly: `a * b - p` (Dekker's two-product, with Veltkamp's +/// split of each factor into halves of 26 bits whose products are exact). For finite factors whose +/// product neither overflows nor underflows. +fn product_error(a: f64, b: f64, p: f64) -> f64 { + let split = |x: f64| { + let c = 134_217_729.0 * x; // 2^27 + 1 + let hi = c - (c - x); + (hi, x - hi) + }; + let ((a_hi, a_lo), (b_hi, b_lo)) = (split(a), split(b)); + ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo +} + +/// The decimal text, to 30 places, of `whole + part / per_day` days: read as an f64, the serial +/// nearest that time (the parse rounds once), for tests of serial dates. +#[cfg(test)] +pub(crate) fn serial_text(whole: i64, part: i64, per_day: i64) -> String { + let total = whole * per_day + part; + let (sign, n) = if total < 0 { ("-", -total) } else { ("", total) }; + let mut text = format!("{sign}{}.", n / per_day); + let mut rest = n % per_day; + for _ in 0..30 { + rest *= 10; + text.push(char::from(b'0' + u8::try_from(rest / per_day).unwrap_or(0))); + rest %= per_day; + } + text } /// Whether microseconds since 1970 fall in years 1 to 9999. @@ -526,13 +682,144 @@ mod tests { let serial = 2_958_465.25 + 2f64.powi(-31); let (t, rounded) = serial_datetime(serial, -25_569).unwrap(); assert_eq!(t.to_string(), "9999-12-31T06:00:00.000040"); - assert!(rounded); + // That step is the f64's unit in the last place here: past day 65536 every f64 is the one + // nearest its microsecond (this one is 0.233 µs from 06:00:00.000040), so a loss finer + // than the microsecond can't be told from the serial, and nothing is said. + assert!(!rounded); assert_eq!(serial_datetime(25_569.5, -25_569).unwrap(), (dt("1970-01-01T12:00:00"), false)); for bad in [f64::NAN, f64::INFINITY, -1e100, 2_958_466.0] { assert!(serial_datetime(bad, -25_569).is_none()); } } + /// A binary double (a File Geodatabase's) isn't stored as decimal text, so 15 digits of text + /// aren't excused there; a time a program computes (days plus a fraction, Unix seconds over + /// an hour and a day's hours), which needn't be the f64 nearest its second, still is. + #[test] + fn a_binary_serial_is_rounded_unless_a_program_computes_it() { + for second in [0, 1, 59, 3_600, 86_399] { + assert!(!binary_serial_datetime(nearest_serial(45_000, second), -25_569).unwrap().1, "second {second}"); + } + let finer = 45_000.0 + 0.123_456_789 / 86_400.0; + assert!(binary_serial_datetime(finer, -25_569).unwrap().1); + // Every second of the day as days plus a fraction, and as Unix seconds over an hour and a + // day's hours, which aren't all the f64 nearest their second, is no rounding. + // Each reads as the second it was made from, to the microsecond. + let mut not_nearest = (0, 0); + for day in [1, 3, 45_000, 60_000, 65_536, 100_000, 2_958_465] { + let start = binary_serial_datetime(day as f64, -25_569).unwrap().0.micros(); + for second in 0..86_400 { + let computed = day as f64 + second as f64 / 86_400.0; + not_nearest.0 += usize::from(computed != nearest_serial(day, second)); + let (t, rounded) = binary_serial_datetime(computed, -25_569).unwrap(); + assert!(!rounded, "day {day}, second {second}"); + assert_eq!(t.micros() - start, second * 1_000_000, "day {day}, second {second}"); + let unix = ((day - 25_569) * 86_400 + second) as f64 / 3600.0 / 24.0 + 25_569.0; + not_nearest.1 += usize::from(unix != nearest_serial(day, second)); + let (t, rounded) = binary_serial_datetime(unix, -25_569).unwrap(); + assert!(!rounded, "day {day}, second {second}, Unix"); + assert_eq!(t.micros() - start, second * 1_000_000, "day {day}, second {second}, Unix"); + } + } + assert!(not_nearest.0 > 0 && not_nearest.1 > 0, "{not_nearest:?}"); + // 45000.123456789 is what 15 digits of text give for 02:57:46.666569: excused in a + // workbook, rounded in a binary double. + assert!(!serial_datetime(45_000.123_456_789, -25_569).unwrap().1); + assert!(binary_serial_datetime(45_000.123_456_789, -25_569).unwrap().1); + } + + /// The f64 nearest `day + seconds / 86400`, from its decimal text to 30 places (the parse + /// rounds once), so the test doesn't round twice as `day + seconds / 86400.0` can. + fn nearest_serial(day: i64, seconds: i64) -> f64 { + super::serial_text(day, seconds, 86_400).parse().unwrap() + } + + /// The serial of `day` and `seconds` written to 15 significant digits, as some programs write + /// a number, rounding the exact time's decimal text (no time of whole seconds is a tie). + fn fifteen_digit_serial(day: i64, seconds: i64) -> f64 { + let text = super::serial_text(day, seconds, 86_400); + let digits: String = text.chars().filter(char::is_ascii_digit).collect(); + let decimals = text.len() - text.find('.').unwrap() - 1; + let first: i128 = digits[..15].parse().unwrap(); + let up = digits.as_bytes()[15] >= b'5'; + format!("{}e-{}", first + i128::from(up), decimals - (digits.len() - 15)).parse().unwrap() + } + + /// A whole-second or whole-minute time's binary serial is rarely the time exactly, but it is + /// the f64 nearest it: that representation noise isn't rounding (#1894). A serial with digits + /// finer than the microsecond is. + #[test] + fn serial_noise_is_not_reported_as_rounding() { + // Days 1, 2 and 100, and -1 (1899-12-29, which FileGDB can hold), to the second. + for day in [1, 2, 100, -1] { + let start = serial_datetime(day as f64, -25_569).unwrap().0.micros(); + for second in 0..86_400 { + let (t, rounded) = serial_datetime(nearest_serial(day, second), -25_569).unwrap(); + assert_eq!(t.micros() - start, second * 1_000_000, "day {day}, second {second}"); + assert!(!rounded, "day {day}, second {second}"); + } + } + let day = serial_datetime(45_000.0, -25_569).unwrap().0.micros(); + for minute in 0..1440 { + let (t, rounded) = serial_datetime(nearest_serial(45_000, minute * 60), -25_569).unwrap(); + assert_eq!(t.micros() - day, minute * MINUTE_US, "minute {minute}"); + assert!(!rounded, "minute {minute}"); + // As a spreadsheet computes it, too. + assert!(!serial_datetime(45_000.0 + minute as f64 / 1440.0, -25_569).unwrap().1, "minute {minute}"); + } + // Every second of the day as a program adds it to the day (two roundings), and as 15 + // significant digits of text. + for second in 0..86_400 { + let (t, rounded) = serial_datetime(45_000.0 + second as f64 / 86_400.0, -25_569).unwrap(); + assert_eq!(t.micros() - day, second * 1_000_000, "second {second}"); + assert!(!rounded, "second {second}"); + // Fifteen digits hold a day's time here only to 8.64 µs: the serial is read as the + // microsecond nearest it, a few from the second, and that loss is the writer's. + let (t, rounded) = serial_datetime(fifteen_digit_serial(45_000, second), -25_569).unwrap(); + assert!((t.micros() - day - second * 1_000_000).abs() <= 5, "second {second}, 15 digits"); + assert!(!rounded, "second {second}, 15 digits"); + } + // Whole seconds and milliseconds from 1970 to 2100 as milliseconds since 1970 over a + // day's, plus 25569: that sum rounds at the size of the days since 1970 first. From day + // 65536 (2079) an f64's step is 1.26 µs, but the computation is tried at the millisecond + // nearest the serial, so each reads as its millisecond exactly. + for unix_day in (0..47_482i64).step_by(97) { + for ms in (0..86_400_000i64).step_by(86_400_000 / 211 + 7).chain([1_000, 59_999, 86_399_000]) { + let unix_ms = unix_day * 86_400_000 + ms; + let serial = unix_ms as f64 / 86_400_000.0 + 25_569.0; + let (t, rounded) = serial_datetime(serial, -25_569).unwrap(); + assert_eq!(t.micros(), unix_ms * 1000, "{unix_ms} ms: {t}"); + assert!(!rounded, "{unix_ms} ms"); + } + } + // 00:00:00.123456789 on the day after the epoch. + let (t, rounded) = serial_datetime(1.0 + 0.123_456_789 / 86_400.0, -25_569).unwrap(); + assert_eq!(t.to_string(), "1899-12-31T00:00:00.123457"); + assert!(rounded); + // A fraction of a day past the microsecond in a recent year: 10666666569.49 µs. + // 45000.123456789 is 15 significant digits, which hold a time here only to 8.64 µs: it is + // what a program writing 15 digits writes for 02:57:46.666569, so nothing is said. + let (t, rounded) = serial_datetime(45_000.123_456_789, -25_569).unwrap(); + assert_eq!(t.to_string(), "2023-03-15T02:57:46.666569"); + assert!(!rounded); + // 0.123456789 s past midnight on day 45000, as the f64 nearest it (17 digits): no way of + // storing 00:00:00.123457 gives that f64, so the rounding is said. + let (t, rounded) = serial_datetime(45_000.0 + 0.123_456_789 / 86_400.0, -25_569).unwrap(); + assert_eq!(t.to_string(), "2023-03-15T00:00:00.123457"); + assert!(rounded); + // 45000.0000000001 is 8.64 µs past midnight, but its f64 is 8.80 µs past it, 0.2 µs from + // 00:00:00.000009 and the f64 nearest it (steps are 0.63 µs here): the f64 can't tell + // them apart, so nothing is said. + let (t, rounded) = serial_datetime(45_000.000_000_000_1, -25_569).unwrap(); + assert_eq!(t.to_string(), "2023-03-15T00:00:00.000009"); + assert!(!rounded); + // On day 70000 (2091) an f64's step is 1.26 µs, so 0.123456789 s can't be held finer than + // the microsecond: the serial is the nearest f64 to 00:00:00.123457, and nothing is said. + let (t, rounded) = serial_datetime(70_000.0 + 0.123_456_789 / 86_400.0, -25_569).unwrap(); + assert_eq!(t.to_string(), "2091-08-25T00:00:00.123457"); + assert!(!rounded); + } + #[test] fn civil_days_round_trip() { for days in [MIN_DAYS, -1, 0, 59, 11_016, 20_517, MAX_DAYS] { diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 64208d69b9..969d2b5ab0 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -471,16 +471,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 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 { @@ -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, 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 { @@ -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) -> 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) -> (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`. diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 28448df7ed..11a6efc11f 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -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)); } } diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index 6c832b647b..8b0ad37ceb 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -176,20 +176,26 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> 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)); } @@ -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#""#) + }; + 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"").is_err()); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 68d8e50c76..8b5b24aace 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -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], + /// 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 @@ -3627,9 +3638,9 @@ pub(crate) fn read_rows( malformed: usize, name: &str, opts: &CsvOptions, - workbook: Option<(&[Option], &[usize])>, + workbook: Option>, ) -> 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, what: &str| -> Result> { match n.as_deref().map(str::trim).filter(|n| !n.is_empty()) { @@ -3703,9 +3714,15 @@ 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 = 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. @@ -3713,7 +3730,7 @@ pub(crate) fn read_rows( 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, @@ -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); } @@ -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 { @@ -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:?}"); + } + } + /// `` in a `.dbf` date column is counted once, as the marker, not also as a date that /// isn't one, whole and streamed. #[test] diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index e43e3c84cb..aa52486d1b 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -7,7 +7,7 @@ use std::io::Cursor; use calamine::{Data, ExcelDateTime, ExcelDateTimeType, Reader, Sheets, Xls, open_workbook_auto_from_rs, open_workbook_from_rs}; -use crate::io::{Columns, CsvOptions, columns_of, read_rows}; +use crate::io::{Columns, CsvOptions, Workbook, columns_of, read_rows}; use crate::{DataError, Dataset, Field, FieldType, ReadReport, Result}; mod biff; @@ -65,12 +65,13 @@ pub(crate) fn read_with_hint( ) -> Result<(Dataset, ReadReport)> { let g = grid(bytes, sheet)?; let title = if g.names.len() > 1 { format!("{name} {}", g.pick) } else { name.to_string() }; - let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some((&g.dates, &g.phantom_dates)))?; + // Serial date-times rounded to the microsecond are said with the date-time text rounded there. + let workbook = Workbook { types: &g.dates, phantom_dates: &g.phantom_dates, rounded_dates: &g.rounded_dates }; + let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some(workbook))?; let errors: usize = g.error_cells.iter().sum(); - let rounded: usize = g.rounded_dates.iter().sum(); let headings: usize = g.header_error_cells.iter().sum(); let fields: Vec = - if errors > 0 || rounded > 0 || headings > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; + if errors > 0 || headings > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; // A heading that is an error is named by its column letter: the column's name, not its data. if headings > 0 { let what = if headings == 1 { @@ -106,15 +107,6 @@ pub(crate) fn read_with_hint( }; report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); } - 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(&fields, &g.rounded_dates) - ), - )); - } let others: Vec<&str> = g.names.iter().filter(|n| **n != g.pick).map(String::as_str).take(20).collect(); if !others.is_empty() { report.messages.push(format!("{prefix}the workbook has more sheets ({}): {hint}", others.join(", "))); @@ -183,23 +175,13 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< if h.saturating_mul(w) > MAX_CELLS { return Err(DataError::Format(format!("sheet '{pick}' is too large ({h} × {w} cells)"))); } - let header_at = range.rows().position(|r| r.iter().any(|c| !cell(c).trim().is_empty())).unwrap_or(0); - let mut rounded_dates = vec![0usize; w]; - for row in range.rows().skip(header_at + 1) { + // The first row with anything in it, looking at Cancel on each row passed. + let mut header_at = 0; + for (i, r) in range.rows().enumerate() { crate::progress::check()?; - for (k, d) in row.iter().enumerate() { - if let Data::DateTime(dt) = d { - let serial = dt.as_f64() + if is_1904(dt) { DAYS_1900_TO_1904 } else { 0.0 }; - let adjusted = serial + if (1.0..60.0).contains(&serial) { 1.0 } else { 0.0 }; - if !dt.is_duration() - && serial >= 0.0 - && serial.floor() != 60.0 - && crate::date::serial_datetime(adjusted, -25_569).is_some_and(|(_, rounded)| rounded) - && let Some(n) = rounded_dates.get_mut(k) - { - *n += 1; - } - } + if r.iter().any(|c| !cell(c).trim().is_empty()) { + header_at = i; + break; } } let dates = (0..w) @@ -210,7 +192,9 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< crate::progress::check()?; let Some(d) = row.get(i) else { continue }; let text = cell(d); - if text.trim().is_empty() { + // `` is read as empty (and counted), so it types a column no more than an + // empty cell does. + if text.trim().is_empty() || crate::Value::is_null_marker(&text) { continue; } let temporal = matches!(d, Data::DateTime(t) if !t.is_duration()) || matches!(d, Data::DateTimeIso(_)); @@ -239,32 +223,58 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< // empty when it was all the row held. let mut phantom_dates = vec![0usize; w]; let mut error_cells = vec![0usize; w]; - // Error cells too are counted below the heading only: a title row's error is no cell of the - // table. - let mut rows = range.rows().enumerate().map(|(row, r)| { - let mut errors: Vec = Vec::new(); - let mut phantom: Vec = Vec::new(); - let cells = r - .iter() - .enumerate() - .map(|(k, d)| match (d, dates.get(k)) { - (Data::Error(_), _) => { - errors.push(k); - String::new() - } - (Data::DateTime(t), Some(None)) if is_phantom_day(t) => { - phantom.push(k); - String::new() - } - _ => cell(d), - }) - .collect::>(); - (row, cells, errors, phantom) - }); + // Serial date-times that held more than the microsecond, counted as their text is made. + let mut rounded_dates = vec![0usize; w]; + // Error cells and rounded serials too are counted below the heading only: a title row's error + // is no cell of the table. + // Cancel is looked at once a row: the rows stop, and the read ends with it below. + let stopped = std::cell::Cell::new(None); + let mut rows = range + .rows() + .take_while(|_| match crate::progress::check() { + Ok(()) => true, + Err(e) => { + stopped.set(Some(e)); + false + } + }) + .enumerate() + .map(|(row, r)| { + let mut errors: Vec = Vec::new(); + let mut phantom: Vec = Vec::new(); + let mut rounded: Vec = Vec::new(); + let cells = r + .iter() + .enumerate() + .map(|(k, d)| match (d, dates.get(k)) { + (Data::Error(_), _) => { + errors.push(k); + String::new() + } + (Data::DateTime(t), Some(None)) if is_phantom_day(t) => { + phantom.push(k); + String::new() + } + (Data::DateTime(t), _) if !t.is_duration() => { + let (text, held_more) = excel_date(t.as_f64(), is_1904(t), true); + if held_more { + rounded.push(k); + } + text + } + _ => cell(d), + }) + .collect::>(); + (row, cells, errors, phantom, rounded) + }); let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); - let keep = |(_, cells, _, _): &(usize, Vec, Vec, Vec)| cells.iter().any(|c| !c.trim().is_empty()); + let keep = |(_, cells, _, _, _): &(usize, Vec, Vec, Vec, Vec)| cells.iter().any(|c| !c.trim().is_empty()); // The first row with anything in it names the columns. - let (header_row, headers, _, _) = rows.by_ref().find(keep).unwrap_or_default(); + let (header_row, headers, _, _, _) = rows.by_ref().find(keep).unwrap_or_default(); + // Stopped before the header: not an empty sheet. + if let Some(e) = stopped.take() { + return Err(e); + } if headers.is_empty() { return Err(DataError::Format(format!("sheet '{pick}' is empty"))); } @@ -286,12 +296,17 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< }) .collect(); let rows = rows - .inspect(|(_, cells, errors, phantom)| { + .inspect(|(_, cells, errors, phantom, rounded)| { for k in errors { if let Some(n) = error_cells.get_mut(*k) { *n += 1; } } + for k in rounded { + if let Some(n) = rounded_dates.get_mut(*k) { + *n += 1; + } + } // A data row left out whole, below the heading: one whose only values were error // cells, or serial-60 dates, read as empty (one with both is said with the errors). if cells.iter().all(|c| c.trim().is_empty()) { @@ -308,8 +323,11 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< } }) .filter(keep) - .map(|(_, cells, _, _)| cells) + .map(|(_, cells, _, _, _)| cells) .collect(); + if let Some(e) = stopped.take() { + return Err(e); + } Ok(Grid { names, pick, @@ -610,14 +628,14 @@ fn cell(d: &Data) -> String { Data::Float(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", *f as i64), Data::Float(f) => f.to_string(), Data::DateTime(dt) if dt.is_duration() => duration(dt.as_f64()), - Data::DateTime(dt) => excel_date(dt.as_f64() + if is_1904(dt) { DAYS_1900_TO_1904 } else { 0.0 }, true), + Data::DateTime(dt) => excel_date(dt.as_f64(), is_1904(dt), true).0, Data::DateTimeIso(s) | Data::DurationIso(s) => s.clone(), } } /// Whether a date cell is serial 60, the 1900 system's 1900-02-29. fn is_phantom_day(dt: &ExcelDateTime) -> bool { - !dt.is_duration() && (dt.as_f64() + if is_1904(dt) { DAYS_1900_TO_1904 } else { 0.0 }).floor() == 60.0 + !dt.is_duration() && !is_1904(dt) && dt.as_f64().floor() == 60.0 } /// Days from the 1900 date system's day 0 to the 1904 one's (workbooks made on old Macs). @@ -642,25 +660,34 @@ fn duration(days: f64) -> String { format!("{sign}{}:{:02}:{:02}", secs / 3600, secs / 60 % 60, secs % 60) } -/// An Excel serial date (days since 1899-12-30) as `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM:SS` when it -/// has a time of day; a time alone (a serial below 1) keeps fractional seconds as ISO text. -fn excel_date(serial: f64, with_time: bool) -> String { +/// An Excel serial date as stored (days since 1899-12-30, or since 1904-01-01 in a workbook of the +/// 1904 system) as `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM:SS` when it has a time of day; a time alone (a +/// serial below 1) keeps fractional seconds as ISO text. The boolean says the serial held more than +/// the microsecond ([`crate::date::serial_datetime`]): the date system is applied in whole days, +/// so the serial is judged as stored. +fn excel_date(stored: f64, date1904: bool, with_time: bool) -> (String, bool) { + let serial = stored + if date1904 { DAYS_1900_TO_1904 } else { 0.0 }; if !serial.is_finite() || !(0.0..3_000_000.0).contains(&serial) { - return serial.to_string(); + return (stored.to_string(), false); } + // A time without a day is a serial below 1 in the 1900 system. In the 1904 system serial 0 is + // 1904-01-01, a real day (ECMA-376 Part 1, §18.17.4.1), and the cell's type here can't tell a + // time format from a date one, so it stays a date. if serial < 1.0 && with_time { - return crate::date::serial_datetime(serial, 0) - .and_then(|(t, _)| t.to_string().split_once('T').map(|(_, clock)| clock.to_string())) - .unwrap_or_else(|| serial.to_string()); + return crate::date::serial_datetime(stored, 0) + .and_then(|(t, rounded)| t.to_string().split_once('T').map(|(_, clock)| (clock.to_string(), rounded))) + .unwrap_or_else(|| (stored.to_string(), false)); } - // Serial 60 is the workbook's fictitious 1900-02-29. Keep that invalid spelling so + // Serial 60 is the 1900 system's fictitious 1900-02-29. Keep that invalid spelling so // a typed read reports it instead of silently changing it to a real day. - if serial.floor() == 60.0 { - return "1900-02-29".into(); - } - let adjusted = serial + if serial < 60.0 { 1.0 } else { 0.0 }; - let Some((t, _)) = crate::date::serial_datetime(adjusted, -25_569) else { return serial.to_string() }; - if !with_time || t.is_date() { t.date().to_string() } else { t.to_string() } + if !date1904 && serial.floor() == 60.0 { + return ("1900-02-29".into(), false); + } + // The 1904 system's day 0 is 1462 days after the 1900 one's; the 1900 system counts a day that + // never was, so its days before it are one day later than their count. + let epoch = -25_569 + if date1904 { DAYS_1900_TO_1904 as i64 } else { i64::from(serial < 60.0) }; + let Some((t, rounded)) = crate::date::serial_datetime(stored, epoch) else { return (stored.to_string(), false) }; + (if !with_time || t.is_date() { t.date().to_string() } else { t.to_string() }, rounded) } /// A column's letter name: A, B, …, Z, AA, AB… @@ -741,15 +768,20 @@ mod tests { #[test] fn dates_and_letters() { - assert_eq!(excel_date(45_000.0, false), "2023-03-15"); - assert_eq!(excel_date(25_569.5, true), "1970-01-01T12:00:00"); - assert_eq!(excel_date(1.0, false), "1900-01-01"); - assert_eq!(excel_date(59.0, false), "1900-02-28"); - assert_eq!(excel_date(61.0, false), "1900-03-01"); - assert_eq!(excel_date(45_000.999_999_9, true), "2023-03-15T23:59:59.991360", "fractional seconds are kept"); - assert_eq!(excel_date(0.5, true), "12:00:00", "a time of day alone"); - assert_eq!(excel_date(0.500_001, true), "12:00:00.086400", "clock fractions are kept"); - assert_eq!(excel_date(0.0, true), "00:00:00"); + assert_eq!(excel_date(45_000.0, false, false).0, "2023-03-15"); + assert_eq!(excel_date(25_569.5, false, true).0, "1970-01-01T12:00:00"); + assert_eq!(excel_date(1.0, false, false).0, "1900-01-01"); + assert_eq!(excel_date(59.0, false, false).0, "1900-02-28"); + assert_eq!(excel_date(61.0, false, false).0, "1900-03-01"); + assert_eq!(excel_date(45_000.999_999_9, false, true).0, "2023-03-15T23:59:59.991360", "fractional seconds are kept"); + assert_eq!(excel_date(0.5, false, true).0, "12:00:00", "a time of day alone"); + assert_eq!(excel_date(0.500_001, false, true).0, "12:00:00.086400", "clock fractions are kept"); + assert_eq!(excel_date(0.0, false, true).0, "00:00:00"); + // Day 0 of the 1904 system is a real day, 1904-01-01, not a time alone. + assert_eq!(excel_date(0.0, true, false).0, "1904-01-01"); + assert_eq!(excel_date(0.5, true, true).0, "1904-01-01T12:00:00"); + assert_eq!(excel_date(1.5, true, true).0, "1904-01-02T12:00:00"); + assert_eq!(excel_date(1.5, false, true).0, "1900-01-01T12:00:00"); assert_eq!(duration(1.5), "36:00:00"); assert_eq!(duration(-0.25), "-6:00:00"); // A 1904-system date is the same day as its 1900-system serial plus 1462. @@ -793,21 +825,234 @@ mod tests { assert_eq!(ds.value(0, 3), &Value::Text("2024-02-29".into())); } + /// A workbook's `book` with its cells styled by number format `fmt` (``), of the 1904 + /// date system when `date1904`. + fn styled_xlsx(book: &[u8], fmt: u32, date1904: bool) -> Vec { + let mut entries = crate::zip::read(book).unwrap(); + let styles = format!( + r#""# + ); + entries.push(("xl/styles.xml".into(), styles.into_bytes())); + if date1904 { + let at = entries.iter().position(|(n, _)| n == "xl/workbook.xml").unwrap(); + let xml = String::from_utf8(entries[at].1.clone()).unwrap().replace("", r#""#); + entries[at].1 = xml.into_bytes(); + } + crate::zip::write(&entries).unwrap() + } + + /// Making a sheet's cells text looks at Cancel once a row, as typing its columns does, and a + /// Cancel at any look ends the read with it, never with the rows read so far. + #[test] + fn a_sheet_looks_at_cancel_once_a_row_as_its_cells_become_text() { + use crate::progress::tests::Counted; + let cells: Vec = (0..20).map(|i| format!(r#"2023-03-{:02}"#, i + 1)).collect(); + let mut rows: Vec> = vec![vec!["day"]]; + rows.extend(cells.iter().map(|c| vec![c.as_str()])); + let rows: Vec<&[&str]> = rows.iter().map(Vec::as_slice).collect(); + let book = xlsx(&[("Dates", &rows)]); + let counted = std::sync::Arc::new(Counted::default()); + { + let _probe = crate::progress::install(Some(counted.clone())); + read(&book, "dates", None, &CsvOptions::default()).unwrap(); + } + let looks = counted.checks.load(std::sync::atomic::Ordering::Relaxed); + // 20 rows typed, then 21 made text: the header and each row. + assert!(looks >= 41, "{looks}"); + for n in 0..looks { + let _probe = crate::progress::install(Some(std::sync::Arc::new(Counted { after_checks: Some(n), ..Default::default() }))); + let got = read(&book, "dates", None, &CsvOptions::default()); + assert!(matches!(got, Err(DataError::Cancelled)), "look {n}: {:?}", got.map(|(d, r)| (d.features.len(), r))); + } + } + + /// A `` cell among date cells is read as empty and said, and doesn't make the column + /// text (#1894); a column of dates alone says nothing. + #[test] + fn a_null_cell_does_not_make_a_date_column_text() { + let date = |d: &str| format!(r#"{d}"#); + let (a, b) = (date("2023-03-15"), date("2023-03-16")); + let book = xlsx(&[("Dates", &[&["day"], &[&a], &["<Null>"], &[&b]])]); + let (ds, report) = read(&book, "dates", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.fields[0].ty, FieldType::Date); + assert_eq!(ds.value(0, 0).to_string(), "2023-03-15"); + assert!(ds.value(1, 0).is_null()); + assert_eq!(ds.value(2, 0).to_string(), "2023-03-16"); + assert_eq!(report.messages.texts().collect::>(), ["1 value written as Null was read as empty, in 'day'"]); + assert_eq!(report.unread_dates, None); + let book = xlsx(&[("Dates", &[&["day"], &[&a], &[&b]])]); + let (ds, report) = read(&book, "dates", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.fields[0].ty, FieldType::Date); + assert!(report.messages.is_empty(), "{report:?}"); + } + + /// An ISO date-time cell with seven fractional digits is rounded to the microsecond and said, + /// as a GPX time is; six are kept as they are. + #[test] + fn workbook_iso_times_past_the_microsecond_are_rounded_and_said() { + let cell = |t: &str| format!(r#"{t}"#); + let book = xlsx(&[("Times", &[&["moment"], &[&cell("2019-07-04T12:30:15.1234567Z")], &[&cell("2019-07-04T12:30:16Z")]])]); + let (ds, report) = read(&book, "times", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.fields[0].ty, FieldType::DateTime); + assert_eq!(ds.value(0, 0).to_string(), "2019-07-04T12:30:15.123457Z"); + assert_eq!( + report.messages.texts().collect::>(), + ["1 date-time was rounded to the microsecond, as more digits than that aren't kept, in 'moment'"] + ); + // A serial cell that held more than the microsecond, in the same column, is said in the + // same notice. + let book = + xlsx(&[("Times", &[&["moment"], &[&cell("2019-07-04T12:30:15.1234567Z")], &[r#"45000.000001428896"#]])]); + let book = styled_xlsx(&book, 22, false); + let (ds, report) = read(&book, "times", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.fields[0].ty, FieldType::DateTime); + assert_eq!( + report.messages.texts().collect::>(), + ["2 date-times were rounded to the microsecond, as more digits than that aren't kept, in 'moment'"] + ); + let book = xlsx(&[("Times", &[&["moment"], &[&cell("2019-07-04T12:30:15.123456Z")]])]); + let (ds, report) = read(&book, "times", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.value(0, 0).to_string(), "2019-07-04T12:30:15.123456Z"); + assert!(report.messages.is_empty() && report.rounded_dates.is_none(), "{report:?}"); + } + + /// Whole minutes are never said to be rounded, in either date system: the system and the 1900 + /// system's leap day are applied in whole days, not by adding to the serial, which would + /// round it again where the sum crosses a power of two (#1894). + #[test] + fn whole_minutes_are_not_rounded_in_either_date_system() { + // Stored days whose shifted sums cross a power of two: 1 and 3 in the 1900 system (one day + // is added before 1900-03-01), 16383 and 32767 in the 1904 system (1462 days are added). + for (day, date1904) in [(1i64, false), (3, false), (16_383, true), (32_767, true)] { + // The minute's serial as decimal text to 30 places, which the reader rounds once. + let serial = |minute: i64| format!(r#"{}"#, crate::date::serial_text(day, minute, 1440)); + let cells: Vec = (0..1440).map(serial).collect(); + let mut rows: Vec> = vec![vec!["moment"]]; + rows.extend(cells.iter().map(|c| vec![c.as_str()])); + let rows: Vec<&[&str]> = rows.iter().map(Vec::as_slice).collect(); + let book = xlsx(&[("Dates", &rows)]); + let book = styled_xlsx(&book, 22, date1904); + let (ds, report) = read(&book, "dates", None, &CsvOptions::default()).unwrap(); + assert_eq!(ds.fields[0].ty, FieldType::DateTime, "day {day}"); + assert!(report.messages.is_empty() && report.rounded_dates.is_none(), "day {day}: {report:?}"); + let micros = |row: usize| match ds.value(row, 0) { + Value::DateTime(t) => t.micros(), + v => panic!("day {day}, row {row}: {v:?}"), + }; + for minute in 0..1440 { + assert_eq!(micros(minute) - micros(0), minute as i64 * 60_000_000, "day {day}, minute {minute}"); + } + } + } + + /// In a 1904 workbook, cells on day 0 (1904-01-01) are dates like any other, so a date column + /// stays one; in a 1900 workbook a serial below 1 is a time alone and stays text. + #[test] + fn day_0_of_a_1904_workbook_is_a_date() { + let book = |serials: &[&str], fmt: u32, date1904: bool| { + let cells: Vec = serials.iter().map(|s| format!(r#"{s}"#)).collect(); + let mut rows: Vec> = vec![vec!["day"]]; + rows.extend(cells.iter().map(|c| vec![c.as_str()])); + let rows: Vec<&[&str]> = rows.iter().map(Vec::as_slice).collect(); + let book = styled_xlsx(&xlsx(&[("Dates", &rows)]), fmt, date1904); + read(&book, "dates", None, &CsvOptions::default()).unwrap() + }; + let (ds, report) = book(&["0", "1"], 14, true); + assert_eq!(ds.fields[0].ty, FieldType::Date, "{report:?}"); + assert_eq!(ds.value(0, 0).to_string(), "1904-01-01"); + let (ds, report) = book(&["0.5", "1.25"], 22, true); + assert_eq!(ds.fields[0].ty, FieldType::DateTime, "{report:?}"); + assert_eq!(ds.value(0, 0).to_string(), "1904-01-01T12:00:00"); + assert!(report.messages.is_empty(), "{report:?}"); + let (ds, _) = book(&["0.5"], 22, false); + assert_eq!(ds.fields[0].ty, FieldType::Text); + assert_eq!(ds.value(0, 0).to_string(), "12:00:00"); + } + + /// A workbook of the 1904 date system has no 1900-02-29: its serial 60 is a real day, and its + /// serials read as they did before serials were judged as stored. A negative serial isn't + /// taken for the 1904 system (`is_1904` looks at serials from 0), so it reads as the number it + /// is, then as no date, as it always has. + #[test] + fn a_1904_workbook_has_no_phantom_leap_day() { + let book = |serials: &[&str]| { + let cells: Vec = serials.iter().map(|s| format!(r#"{s}"#)).collect(); + let mut rows: Vec> = vec![vec!["day"]]; + rows.extend(cells.iter().map(|c| vec![c.as_str()])); + let rows: Vec<&[&str]> = rows.iter().map(Vec::as_slice).collect(); + let book = styled_xlsx(&xlsx(&[("Dates", &rows)]), 14, true); + read(&book, "dates", None, &CsvOptions::default()).unwrap() + }; + let (ds, report) = book(&["59", "60", "61"]); + assert_eq!(ds.fields[0].ty, FieldType::Date); + let days: Vec = (0..3).map(|r| ds.value(r, 0).to_string()).collect(); + assert_eq!(days, ["1904-02-29", "1904-03-01", "1904-03-02"]); + assert!(report.messages.is_empty(), "{report:?}"); + // A negative serial: no date, and counted, as before. + let (ds, report) = book(&["-1000", "61"]); + assert_eq!(ds.fields[0].ty, FieldType::Date); + assert!(ds.value(0, 0).is_null(), "{:?}", ds.value(0, 0)); + assert_eq!(ds.value(1, 0).to_string(), "1904-03-02"); + assert_eq!( + report.unread_dates.as_ref().map(crate::loss::Note::as_str), + Some("1 value isn't a date and was read as empty, in 'day'") + ); + assert_eq!(report.messages.texts().collect::>(), ["1 value isn't a date and was read as empty, in 'day'"]); + } + + /// A rounded serial in the WKT column isn't WKT, so its row has no geometry, and the bad-WKT + /// notice counts it. + #[test] + fn a_serial_in_the_wkt_column_is_counted_as_bad_wkt() { + let book = xlsx(&[("Dates", &[&["geom", "name"], &[r#"45000.000001428896"#, "a"]])]); + let book = styled_xlsx(&book, 22, false); + let opts = CsvOptions { wkt: Some("geom".into()), ..CsvOptions::default() }; + let (ds, report) = read(&book, "dates", None, &opts).unwrap(); + assert!(ds.features[0].geometry.is_none()); + assert!(report.messages.iter().any(|m| m.as_str() == "1 rows had geometry that isn't readable WKT"), "{report:?}"); + } + /// Native numeric date styles reach the public reader's rounding notice, including - /// time-only text. Exact half days stay silent; non-dyadic serials report the field/count. + /// time-only text. A serial is said to be rounded only when it holds more than the + /// microsecond: 45000.1 isn't 45000.1 in binary, but it is the f64 02:24:00 makes, so nothing + /// finer was lost (#1894). 45000.123456789 is 15 significant digits, which hold the time here + /// only to 8.64 µs, so it is what a program writing 15 digits writes for its microsecond. + /// 0.123456789 days is 02:57:46.6665696, and 45000.000001428896 is 0.12345663 s past + /// midnight, which were rounded. #[test] fn workbook_serial_dates_report_rounding_and_keep_clock_fractions() { - for (serial, rounded) in [("45000.5", false), ("45000.1", true), ("0.5", false), ("0.500001", false), ("0.123456789", true)] { + let cases = [ + ("45000.5", false), + ("45000.1", false), + ("0.5", false), + ("0.500001", false), + ("0.123456789", true), + ("45000.123456789", false), + ("45000.000001428896", true), + ]; + for (serial, rounded) in cases { let cell = format!(r#"{serial}"#); let book = xlsx(&[("Dates", &[&["moment"], &[&cell]])]); - let mut entries = crate::zip::read(&book).unwrap(); - entries.push(("xl/styles.xml".into(), br#""#.to_vec())); - let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "dates", None, &CsvOptions::default()).unwrap(); - let notices: Vec<_> = report.messages.iter().filter(|n| n.contains("rounded to the nearest microsecond")).collect(); + let book = styled_xlsx(&book, 22, false); + let (ds, report) = read(&book, "dates", None, &CsvOptions::default()).unwrap(); + 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")); + // A time without a day stays text, so it is said as a time. + let what = if ds.fields[0].ty == FieldType::DateTime { "1 date-time was" } else { "1 date or time value was" }; + assert_eq!( + notices[0].as_str(), + format!("{what} rounded to the microsecond, as more digits than that aren't kept, in 'moment'") + ); assert_eq!(notices[0].loss, Some(crate::loss::LossCode::ChangedRounded)); + assert_eq!(ds.fields[0].ty == FieldType::DateTime, serial != "0.123456789"); + } + if serial == "45000.123456789" { + assert_eq!(ds.value(0, 0).to_string(), "2023-03-15T02:57:46.666569"); + } + if serial == "45000.000001428896" { + assert_eq!(ds.value(0, 0).to_string(), "2023-03-15T00:00:00.123457"); } if serial == "0.500001" { assert_eq!(ds.fields[0].ty, FieldType::Text); @@ -816,6 +1061,9 @@ mod tests { if serial == "0.123456789" { assert_eq!(ds.value(0, 0).to_string(), "02:57:46.666570"); } + if serial == "45000.1" { + assert_eq!(ds.value(0, 0).to_string(), "2023-03-15T02:24:00"); + } } } @@ -828,9 +1076,8 @@ mod tests { let rows: Vec = cells.iter().map(|c| if *c == "x" { (*c).to_string() } else { format!(r#"{c}"#) }).collect(); let book = xlsx(&[("Dates", &[&["a"], &[&rows[0]], &[&rows[1]], &[&rows[2]]])]); - let mut entries = crate::zip::read(&book).unwrap(); - entries.push(("xl/styles.xml".into(), br#""#.to_vec())); - read(&crate::zip::write(&entries).unwrap(), "dates", None, &CsvOptions::default()).unwrap() + let book = styled_xlsx(&book, 14, false); + read(&book, "dates", None, &CsvOptions::default()).unwrap() }; // A column of dates: the cell is null and counted. let (ds, report) = book(["45000", "60", "45002"]); @@ -855,10 +1102,9 @@ mod tests { fn the_phantom_leap_day_in_a_wkt_column_is_said() { let book = |second: &str| { let book = xlsx(&[("Places", &[&["name", "wkt"], &["a", "POINT (1 2)"], &["b", second]])]); - let mut entries = crate::zip::read(&book).unwrap(); - entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let book = styled_xlsx(&book, 14, false); let opts = CsvOptions { wkt: Some("wkt".into()), ..CsvOptions::default() }; - read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap() + read(&book, "places", None, &opts).unwrap() }; let (ds, report) = book(r#"60"#); assert_eq!(ds.features.len(), 2); diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index ceaca371b4..9b67ff3bd6 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -492,6 +492,18 @@ pub fn not_utf8_note(fields: &[crate::Field], counts: &[usize], encoding: &str) /// whole numbers past 2^53 to the nearest decimal number a Double field holds. Names the first five /// fields. `None` when there were none. pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option { + rounded_note(fields, counts, ("date-time", "date-times")) +} + +/// [`rounded_dates_note`], for a reader whose serial dates may be kept as text (a time without a +/// day): said as date or time values when a counted field isn't a date-time field. +pub(crate) fn rounded_serials_note(fields: &[crate::Field], counts: &[usize]) -> Option { + let date_times = fields.iter().zip(counts).all(|(f, n)| *n == 0 || f.ty == crate::FieldType::DateTime); + rounded_note(fields, counts, if date_times { ("date-time", "date-times") } else { ("date or time value", "date or time values") }) +} + +/// [`rounded_dates_note`], its date-times called by `noun` (one, many). +fn rounded_note(fields: &[crate::Field], counts: &[usize], noun: (&str, &str)) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; @@ -512,7 +524,7 @@ pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option { - let what = if total == 1 { "1 date-time was".to_string() } else { format!("{total} date-times were") }; + let what = if total == 1 { format!("1 {} was", noun.0) } else { format!("{total} {} were", noun.1) }; format!( "{what} rounded to the microsecond, as more digits than that aren't kept, in {}", crate::io::named_fields(fields, counts) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d5e17b9e72..7567f9f36a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -65442,6 +65442,46 @@ fn a_city_models_volumes_come_in_extruded() { assert!(s.map().layers.iter().all(|l| l.extrusion.is_none()), "only a reader that knows the type extrudes"); } +/// A GPX time or a workbook date-time cell with digits past the microsecond is said to be +/// rounded once when the file is read, and an export of the layer doesn't say it again (#1894). +#[test] +fn a_rounded_time_is_said_once() { + use base64::Engine; + let gpx = r#""#; + let book = rustgis_data::sheets::xlsx(&[( + "Times", + &[&["moment", "longitude", "latitude"], &[r#"2019-07-04T12:30:15.1234567Z"#, "10", "20"]], + )]); + // Removed when the test ends, passing or not (the engine's tests have no tempfile). + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = Dir(std::env::temp_dir().join(format!("rustgis-rounded-{}-{nanos}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + for (what, command, params) in [ + ("gpx", "layer.addDataText", json!({"fileName": "trip.gpx", "text": gpx})), + ( + "xlsx", + "layer.addDataBytes", + json!({"fileName": "times.xlsx", "data": base64::engine::general_purpose::STANDARD.encode(&book), "x": "longitude", "y": "latitude"}), + ), + ] { + let mut s = Session::new(Project::default()); + let rounded = |s: &Session, mark| s.notices_since(mark).iter().filter(|n| n.text.contains("rounded to the microsecond")).count(); + let mark = s.notice_mark(); + s.run(command, ¶ms).unwrap(); + assert_eq!(rounded(&s, mark), 1, "{what}: {:?}", s.notices_since(mark)); + let id = s.map().layers.first().unwrap().id; + let mark = s.notice_mark(); + s.run("share.exportLayer", &json!({"layer": id, "path": dir.0.join(format!("{what}.csv"))})).unwrap(); + assert_eq!(rounded(&s, mark), 0, "{what}: {:?}", s.notices_since(mark)); + } +} + /// Files read as they are added, on the UI thread in the desktop app (a GeoJSON document that /// isn't a FeatureCollection, a KML), stay within 256 MiB whatever the memory (#2408), saying so. /// The KML is a sparse file. The GeoJSON is padded with 256 MiB of spaces, which it may end in: a diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b9043e15fa..e0ddfaceb9 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -167,16 +167,24 @@ and **Data › Layer Templates** adds empty layers with ready-made schemas to dr Dates and date-times remain typed when reading Shapefile, GeoPackage, GeoParquet, local FlatGeobuf, FileGDB, workbook date cells and GPX timestamps. Ordinary spreadsheet text that looks like a date stays text. A workbook column mixing date cells with ordinary text is read -entirely as text; clean that column in the workbook before using date operations. +entirely as text; clean that column in the workbook before using date operations. Empty cells and +`` cells don't count as text there: they are read as empty values. Invalid dates become empty values with a notice naming the fields and counting the values; dates cover years 1–9999. Fractional seconds are kept to microseconds: -digits past the sixth (nanosecond timestamps in Parquet, text read from a GeoPackage or FlatGeobuf, or -converted by Convert Field) are rounded to the nearest microsecond, and a read says how many values it -rounded and in which fields. Text typed in, kept in a project, read from GPX or compared in a -where clause isn't rounded: with more digits than that it isn't a date. Floating-point serial dates in workbooks and FileGDB are rounded -the same way, with a notice when rounding is needed. A workbook's 1900-02-29 (serial 60, a day +digits past the sixth (nanosecond timestamps in Parquet, text read from a GeoPackage, FlatGeobuf, +GPX timestamps or workbook date cells, or converted by Convert Field) are rounded to the nearest +microsecond, and a read says how many values it rounded and in which fields. Text typed in, kept in a +project or compared in a where clause isn't rounded: with more digits than that it isn't a date. +Floating-point serial dates in workbooks and FileGDB are rounded the same way, with a notice only +when the serial holds more than a microsecond can say (a whole minute or second isn't reported). +A FileGDB serial is a binary number: it counts as holding no more than its microsecond when it is +the nearest such number to it, or what a program computes for it (days plus the day's fraction, +or seconds or milliseconds since 1970 turned into days). A workbook's serial may also be the +number's 15-digit text. A workbook's 1900-02-29 (serial 60, a day that never existed) is read as empty and counted, in a column of dates or any other. -Times without a day stay text; Parquet clocks retain `Z` when declared UTC. +Times without a day stay text. In a workbook of the 1904 date system, though, a time-only cell +reads as a date-time on 1904-01-01: the reader can't tell a time format from a date format there. +Parquet clocks retain `Z` when declared UTC. GeoParquet exports use native dates and microsecond timestamps. Zoned date-times are written as UTC instants, with a notice when their displayed offsets change; unzoned times stay unzoned.