diff --git a/Cargo.lock b/Cargo.lock index c4822e5..5bfc45f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -22,9 +22,9 @@ dependencies = [ [[package]] name = "android_system_properties" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" dependencies = [ "libc", ] @@ -49,15 +49,15 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bitflags" -version = "2.13.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "bstr" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", "regex-automata", @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "cast" @@ -78,9 +78,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.2.67" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "shlex", @@ -88,9 +88,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "chrono" @@ -144,18 +144,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.2" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd059f9da4f5c36b3787f65d38ccaab1cc315f07b01f89abc8359ee6a8205011" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.6.2" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstyle", "clap_lex", @@ -163,9 +163,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "console_error_panic_hook" @@ -220,9 +220,9 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -230,18 +230,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.20" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.22" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crunchy" @@ -265,33 +265,33 @@ dependencies = [ [[package]] name = "either" -version = "1.16.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-task", @@ -365,15 +365,15 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "js-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -382,13 +382,13 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libhaystack" -version = "4.1.1" +version = "4.2.0" dependencies = [ "chrono", "chrono-tz", @@ -415,9 +415,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "memchr" @@ -541,18 +541,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.46" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -635,9 +635,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.16" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -673,9 +673,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -683,29 +683,29 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "serde_json" -version = "1.0.150" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -722,9 +722,9 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" @@ -734,9 +734,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.2" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "syn" @@ -749,6 +749,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -771,9 +782,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unit-gen" @@ -804,12 +815,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -817,9 +827,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -827,31 +837,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -919,7 +929,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -930,7 +940,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -974,22 +984,22 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "zerocopy" -version = "0.8.54" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.54" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 6e00c2e..6056314 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libhaystack" -version = "4.1.1" +version = "4.2.0" description = "Rust implementation of the Haystack 4 data types, defs, filter, units, and encodings" authors = ["J2 Innovations", "Radu Racariu "] edition = "2024" diff --git a/README.md b/README.md index 8c7d692..0fdb434 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,34 @@ let value: Value = dict.into(); assert!(value.is_dict()); ``` +### Spans + +Time ranges modelled after Haxall's `Span` (timezone-aware, inclusive start, exclusive end) and `DateSpan` (date-only, inclusive) are available in the [span](https://docs.rs/libhaystack/latest/libhaystack/haystack/span/index.html) module. + +```rust +use chrono_tz::Tz; +use libhaystack::span::*; + +// Parse an absolute date range in a timezone (the end date is exclusive) +let span = Span::from_str("2026-04-01,2026-05-01", Tz::Europe__London).expect("Span"); +assert_eq!(span.num_days(), 30); +assert!(span.aligns_to_month()); + +// Relative spans resolve against the current date +let this_week = Span::make_rel(SpanMode::ThisWeek, Tz::UTC); +assert!(this_week.mode().is_rel()); +``` + +For an application-owned clock, use `Span::make_rel_on(mode, today, tz)`, +`Span::from_str_on(text, today, tz)`, and `span.fresh_on(today)`. Pass a Haystack `Date` +representing the local date in the target timezone; these APIs do not read the system clock. + +`span.is_empty()` tests whether the bounds are equal. `span.each_day(...)` visits no dates +for an empty span. Use `span.try_to_date_span()` when converting to an inclusive `DateSpan`: +it returns `None` for empty spans. The existing `to_date_span()` retains its compatibility +behavior, including converting an empty midnight-aligned span to a single day. `span.dis()` +renders an empty span as a datetime range (e.g. `01-Apr-2026 00:00..01-Apr-2026 00:00`). + ### Filter A Haystack 4 compliant [filter](https://docs.rs/libhaystack/latest/libhaystack/haystack/filter/index.html) parser and evaluator is provided that uses the [ontology](https://project-haystack.org/doc/docHaystack/Ontology) definitions from Project Haystack. diff --git a/src/haystack.rs b/src/haystack.rs index 6bff270..cc9129d 100644 --- a/src/haystack.rs +++ b/src/haystack.rs @@ -15,6 +15,8 @@ pub mod defs; pub mod encoding; #[cfg(feature = "filter")] pub mod filter; +#[cfg(all(feature = "value", feature = "timezone-db"))] +pub mod span; #[cfg(feature = "timezone")] pub mod timezone; #[cfg(feature = "units")] diff --git a/src/haystack/span.rs b/src/haystack/span.rs new file mode 100644 index 0000000..d044f3d --- /dev/null +++ b/src/haystack/span.rs @@ -0,0 +1,31 @@ +// Copyright (c) 2026, J2 Innovations. All Rights Reserved + +//! Haystack time span types, ported from Haxall's `Span` and `DateSpan`. +//! +//! - [`Span`]: a timezone-aware DateTime range (inclusive start, exclusive end), either absolute +//! or relative (`today`, `thisWeek`, `pastMonth`, ...). +//! - [`DateSpan`]: a date-only range (inclusive start and end) with a period classification. +//! +//! Note the differing end semantics: a `Span` range excludes its end, so +//! `"2026-04-01,2026-05-01"` is the whole of April, while a `DateSpan` range includes its end, +//! so the same month is `"2026-04-01,2026-04-30"`. +//! +//! ``` +//! use chrono_tz::Tz; +//! use libhaystack::span::*; +//! +//! // Parse an absolute date range in a timezone (the end date is exclusive) +//! let span = Span::from_str("2026-04-01,2026-05-01", Tz::Europe__London).expect("Span"); +//! assert_eq!(span.num_days(), 30); +//! assert!(span.aligns_to_month()); +//! +//! // Relative spans resolve against the current date +//! let this_week = Span::make_rel(SpanMode::ThisWeek, Tz::UTC); +//! assert!(this_week.mode().is_rel()); +//! ``` + +pub mod date_span; +pub mod date_time_span; + +pub use date_span::{DateSpan, DateSpanPeriod}; +pub use date_time_span::{Span, SpanMode, SpanModePeriod}; diff --git a/src/haystack/span/date_span.rs b/src/haystack/span/date_span.rs new file mode 100644 index 0000000..73d6a31 --- /dev/null +++ b/src/haystack/span/date_span.rs @@ -0,0 +1,892 @@ +// Copyright (c) 2026, J2 Innovations. All Rights Reserved + +//! Date-only span type (inclusive start and end). +//! +//! A `DateSpan` represents an inclusive date +//! range with an optional period classification (`day`, `week`, `month`, `quarter`, `year`, +//! or `range`). Unlike `Span` (see [`Span`](super::Span)), `DateSpan` is date-only — no time or +//! timezone component. + +use crate::val::Date; +use chrono::{Datelike, Duration, Months, NaiveDate}; + +/// Construct a `NaiveDate` from year/month/day that are **known to be valid** by construction. +/// +/// Panics only in `#[cfg(debug_assertions)]` builds if the inputs are invalid. +fn make_date(year: i32, month: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(year, month, day).unwrap_or(NaiveDate::MIN) +} + +/// English 3-letter month abbreviation (`chrono`'s own `%b` formatting is locale-independent +/// English by default, but this avoids depending on that behavior not changing). +pub(crate) fn month_abbr(month: u32) -> &'static str { + match month { + 1 => "Jan", + 2 => "Feb", + 3 => "Mar", + 4 => "Apr", + 5 => "May", + 6 => "Jun", + 7 => "Jul", + 8 => "Aug", + 9 => "Sep", + 10 => "Oct", + 11 => "Nov", + 12 => "Dec", + _ => "", + } +} + +/// Formats a `Date` as `"DD-MMM-YYYY"` (zero-padded day, 4-digit year), e.g. `"01-Jul-2010"` — +/// matches the format used by the Funcs.xeto docs' `toDateSpan()`/`toSpan()` example output +/// (e.g. `toDateSpan(2010) >> 01-Jan-2010..31-Dec-2010`). +pub(crate) fn fmt_date_dd_mmm_yyyy(d: &Date) -> String { + format!("{:02}-{}-{}", d.day(), month_abbr(d.month()), d.year()) +} + +/// The period classification of a [`DateSpan`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DateSpanPeriod { + /// A single day. + Day, + /// A calendar week (Sunday–Saturday, matching upstream locale convention). + Week, + /// A calendar month. + Month, + /// A calendar quarter. + Quarter, + /// A calendar year. + Year, + /// An explicit date range (no period alignment). + Range, +} + +impl DateSpanPeriod { + /// The string representation used by Axon for serialization and parsing. + pub fn as_str(&self) -> &'static str { + match self { + DateSpanPeriod::Day => "day", + DateSpanPeriod::Week => "week", + DateSpanPeriod::Month => "month", + DateSpanPeriod::Quarter => "quarter", + DateSpanPeriod::Year => "year", + DateSpanPeriod::Range => "range", + } + } + + /// Parse a period string into a `DateSpanPeriod`. + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Option { + match s { + "day" => Some(DateSpanPeriod::Day), + "week" => Some(DateSpanPeriod::Week), + "month" => Some(DateSpanPeriod::Month), + "quarter" => Some(DateSpanPeriod::Quarter), + "year" => Some(DateSpanPeriod::Year), + "range" => Some(DateSpanPeriod::Range), + _ => None, + } + } +} + +/// A date-based span with inclusive start and end dates, and an optional period classification. +/// +/// This mirrors the upstream `DateSpan` class from Haxall. The `start` and `end` are both +/// inclusive. The `period` field indicates the semantic meaning of the span (e.g., "this week", +/// "last month") or `"range"` for an arbitrary date-to-date span. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DateSpan { + /// Inclusive start date. + pub start: Date, + /// Inclusive end date. + pub end: Date, + /// Period classification (e.g., `day`, `week`, `month`, `quarter`, `year`, `range`). + pub period: DateSpanPeriod, +} + +impl DateSpan { + /// Create a new `DateSpan` with an explicit start, end, and period. + pub fn new(start: Date, end: Date, period: DateSpanPeriod) -> Self { + DateSpan { start, end, period } + } + + /// Create a `DateSpan` from a start date and a period string. + /// + /// The start date will be adjusted to align to the period boundary: + /// - `day`: start = start, end = start + /// - `week`: start = Sunday of the week containing start, end = Saturday + /// - `month`: start = 1st of the month, end = last day of the month + /// - `quarter`: start = 1st of the quarter, end = last day of the quarter + /// - `year`: start = Jan 1, end = Dec 31 + pub fn from_period(start: Date, period: DateSpanPeriod) -> Self { + // Date derefs to NaiveDate, so we can use Datelike methods directly + let (s, e) = match period { + DateSpanPeriod::Day => (*start, *start), + DateSpanPeriod::Week => { + // Align to Sunday–Saturday (upstream uses locale start of week, which is Sunday) + let days_from_sun = start.weekday().num_days_from_sunday() as i64; + let sunday = *start - Duration::days(days_from_sun); + let saturday = sunday + Duration::days(6); + (sunday, saturday) + } + DateSpanPeriod::Month => { + let first = make_date(start.year(), start.month(), 1); + // Last day of month = first day of next month minus 1 day + let (next_year, next_month) = if start.month() == 12 { + (start.year() + 1, 1) + } else { + (start.year(), start.month() + 1) + }; + let first_next = make_date(next_year, next_month, 1) - Duration::days(1); + (first, first_next) + } + DateSpanPeriod::Quarter => { + let quarter_month = (start.month() - 1) / 3 * 3 + 1; + let first = make_date(start.year(), quarter_month, 1); + // Last day of quarter = first day of next quarter minus 1 day + let next_q_month = quarter_month + 3; + let (next_year, nm) = if next_q_month > 12 { + (start.year() + 1, 1) + } else { + (start.year(), next_q_month) + }; + let first_next = make_date(next_year, nm, 1) - Duration::days(1); + (first, first_next) + } + DateSpanPeriod::Year => { + let first = make_date(start.year(), 1, 1); + let last = make_date(start.year(), 12, 31); + (first, last) + } + DateSpanPeriod::Range => (*start, *start), + }; + DateSpan { + start: Date::from(s), + end: Date::from(e), + period, + } + } + + /// Create an explicit range span (no period alignment). + pub fn range(start: Date, end: Date) -> Self { + DateSpan { + start, + end, + period: DateSpanPeriod::Range, + } + } + + /// Number of days in this span (inclusive on both ends). + pub fn num_days(&self) -> i64 { + (*self.end - *self.start).num_days() + 1 + } + + /// Check if a date is contained within this span (inclusive on both ends). + pub fn contains(&self, date: &Date) -> bool { + *date >= self.start && *date <= self.end + } + + /// Shift the span forward by a duration. The result is always a `Range`. + pub fn plus(&self, duration: Duration) -> Self { + DateSpan::range( + Date::from(*self.start + duration), + Date::from(*self.end + duration), + ) + } + + /// Shift the span backward by a duration. The result is always a `Range`. + pub fn minus(&self, duration: Duration) -> Self { + DateSpan::range( + Date::from(*self.start - duration), + Date::from(*self.end - duration), + ) + } + + /// Get the previous period (e.g., previous month, previous week). + /// For `Range` period, roll start and end back one day. + pub fn prev(&self) -> Self { + match self.period { + DateSpanPeriod::Day => { + let new_start = *self.start - Duration::days(1); + DateSpan::new( + Date::from(new_start), + Date::from(new_start), + DateSpanPeriod::Day, + ) + } + DateSpanPeriod::Week => { + let new_start = *self.start - Duration::days(7); + let new_end = *self.end - Duration::days(7); + DateSpan::new( + Date::from(new_start), + Date::from(new_end), + DateSpanPeriod::Week, + ) + } + DateSpanPeriod::Month => { + let prev_first = *self.start - Duration::days(1); + DateSpan::from_period(Date::from(prev_first), DateSpanPeriod::Month) + } + DateSpanPeriod::Quarter => { + let prev_first = *self.start - Duration::days(1); + DateSpan::from_period(Date::from(prev_first), DateSpanPeriod::Quarter) + } + DateSpanPeriod::Year => { + let prev_first = *self.start - Duration::days(1); + DateSpan::from_period(Date::from(prev_first), DateSpanPeriod::Year) + } + DateSpanPeriod::Range => self.minus(Duration::days(1)), + } + } + + /// Get the next period (e.g., next month, next week). + /// For `Range` period, roll start and end forward one day. + pub fn next(&self) -> Self { + match self.period { + DateSpanPeriod::Day => { + let new_start = *self.start + Duration::days(1); + DateSpan::new( + Date::from(new_start), + Date::from(new_start), + DateSpanPeriod::Day, + ) + } + DateSpanPeriod::Week => { + let new_start = *self.start + Duration::days(7); + let new_end = *self.end + Duration::days(7); + DateSpan::new( + Date::from(new_start), + Date::from(new_end), + DateSpanPeriod::Week, + ) + } + DateSpanPeriod::Month => { + let next_first = *self.end + Duration::days(1); + DateSpan::from_period(Date::from(next_first), DateSpanPeriod::Month) + } + DateSpanPeriod::Quarter => { + let next_first = *self.end + Duration::days(1); + DateSpan::from_period(Date::from(next_first), DateSpanPeriod::Quarter) + } + DateSpanPeriod::Year => { + let next_first = *self.end + Duration::days(1); + DateSpan::from_period(Date::from(next_first), DateSpanPeriod::Year) + } + DateSpanPeriod::Range => self.plus(Duration::days(1)), + } + } + + /// Iterate over each day in the span, calling `func` with the date and a 0-based index. + pub fn each_day(&self, mut func: F) + where + F: FnMut(Date, i32), + { + let mut current = self.start; + let mut idx: i32 = 0; + while current <= self.end { + func(current, idx); + current = Date::from(*current + Duration::days(1)); + idx += 1; + } + } + + /// Iterate over each month in the span, calling `func` with a `DateSpan` for that month. + pub fn each_month(&self, mut func: F) + where + F: FnMut(DateSpan), + { + let mut current = DateSpan::from_period(self.start, DateSpanPeriod::Month); + loop { + if current.end >= self.start && current.start <= self.end { + func(current.clone()); + } + if current.end >= self.end { + break; + } + let next_start = *current.end + Duration::days(1); + current = DateSpan::from_period(Date::from(next_start), DateSpanPeriod::Month); + } + } + + /// Convert to a list of dates (one per day in the span). + pub fn to_date_list(&self) -> Vec { + let mut dates = Vec::new(); + self.each_day(|d, _| dates.push(d)); + dates + } + + /// Machine-parseable string representation (mirrors Fantom's `DateSpan.toStr()`): + /// `","` for a `Range` period, `","` otherwise. Round-trips + /// through [`DateSpan::from_str`]; this is what the `toStr()` Axon stdlib function returns. + pub fn to_str(&self) -> String { + match self.period { + DateSpanPeriod::Range => { + format!("{},{}", self.start, self.end) + } + _ => { + format!("{},{}", self.start, self.period.as_str()) + } + } + } + + /// Human-friendly display string for the console/REPL, e.g. `"01-Jul-2010..03-Jul-2010"`. + /// Always renders the explicit inclusive `start..end` date range with a zero-padded day and + /// 4-digit year, matching the format used by the Funcs.xeto docs' own examples (e.g. + /// `toDateSpan(2010) >> 01-Jan-2010..31-Dec-2010`), regardless of period. + pub fn dis(&self) -> String { + format!( + "{}..{}", + fmt_date_dd_mmm_yyyy(&self.start), + fmt_date_dd_mmm_yyyy(&self.end) + ) + } + + /// Check period predicates. + pub fn is_day(&self) -> bool { + self.period == DateSpanPeriod::Day + } + pub fn is_week(&self) -> bool { + self.period == DateSpanPeriod::Week + } + pub fn is_month(&self) -> bool { + self.period == DateSpanPeriod::Month + } + pub fn is_quarter(&self) -> bool { + self.period == DateSpanPeriod::Quarter + } + pub fn is_year(&self) -> bool { + self.period == DateSpanPeriod::Year + } + pub fn is_range(&self) -> bool { + self.period == DateSpanPeriod::Range + } + + /// Parse a `DateSpan` from a string. + /// + /// Supported formats: + /// - `"YYYY-MM-DD,period"` — e.g., `"2026-04-01,month"` + /// - `"YYYY-MM-DD,YYYY-MM-DD"` — explicit range + /// - `"today"`, `"yesterday"` — a single day span + /// - `"thisWeek"`, `"thisMonth"`, `"thisQuarter"`, `"thisYear"` — current period + /// - `"lastWeek"`, `"lastMonth"`, `"lastQuarter"`, `"lastYear"` — previous period + /// - `"pastWeek"`, `"pastMonth"` — rolling 7/30-day span ending today + /// - `"pastYear"` — from the same date last year (clamped to month end) to today + pub fn from_str(s: &str, today: Date) -> Option { + let s = s.trim(); + // Check for keyword shortcuts + match s { + "today" => { + return Some(DateSpan::new(today, today, DateSpanPeriod::Day)); + } + "yesterday" => { + let day = Date::from(*today - Duration::days(1)); + return Some(DateSpan::new(day, day, DateSpanPeriod::Day)); + } + "thisWeek" => { + return Some(DateSpan::from_period(today, DateSpanPeriod::Week)); + } + "thisMonth" => { + return Some(DateSpan::from_period(today, DateSpanPeriod::Month)); + } + "thisQuarter" => { + return Some(DateSpan::from_period(today, DateSpanPeriod::Quarter)); + } + "thisYear" => { + return Some(DateSpan::from_period(today, DateSpanPeriod::Year)); + } + "lastWeek" => { + let ws = DateSpan::from_period(today, DateSpanPeriod::Week); + return Some(ws.prev()); + } + "lastMonth" => { + let ms = DateSpan::from_period(today, DateSpanPeriod::Month); + return Some(ms.prev()); + } + "lastQuarter" => { + let qs = DateSpan::from_period(today, DateSpanPeriod::Quarter); + return Some(qs.prev()); + } + "lastYear" => { + let ys = DateSpan::from_period(today, DateSpanPeriod::Year); + return Some(ys.prev()); + } + "pastWeek" => { + let end = today; + let start_naive = *today - Duration::days(7); + return Some(DateSpan::range(Date::from(start_naive), end)); + } + "pastMonth" => { + let end = today; + let start_naive = *today - Duration::days(30); + return Some(DateSpan::range(Date::from(start_naive), end)); + } + "pastYear" => { + let start = today + .checked_sub_months(Months::new(12)) + .unwrap_or(NaiveDate::MIN); + return Some(DateSpan::range(Date::from(start), today)); + } + _ => {} + } + + // Try parsing "date,period" or "date,date" + if let Some(comma) = s.find(',') { + let date_part = &s[..comma]; + let second_part = &s[comma + 1..]; + let start_date = NaiveDate::parse_from_str(date_part, "%Y-%m-%d").ok()?; + let start_date = Date::from(start_date); + + // Try as period string first + if let Some(period) = DateSpanPeriod::from_str(second_part) { + return Some(DateSpan::from_period(start_date, period)); + } + + // Try as second date (explicit range) + if let Ok(end_date) = NaiveDate::parse_from_str(second_part, "%Y-%m-%d") { + return Some(DateSpan::range(start_date, Date::from(end_date))); + } + } + + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::NaiveDate; + + fn d(y: i32, m: u32, day: u32) -> Date { + Date::from(NaiveDate::from_ymd_opt(y, m, day).unwrap()) + } + + #[test] + fn day_period_is_single_day() { + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Day); + assert_eq!(span.start, d(2026, 4, 15)); + assert_eq!(span.end, d(2026, 4, 15)); + assert_eq!(span.num_days(), 1); + } + + #[test] + fn week_period_aligns_to_sunday_saturday() { + // 2026-04-15 is a Wednesday + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Week); + // Sunday 2026-04-12 to Saturday 2026-04-18 + assert_eq!(span.start, d(2026, 4, 12)); + assert_eq!(span.end, d(2026, 4, 18)); + assert_eq!(span.num_days(), 7); + } + + #[test] + fn month_period_aligns_to_first_last() { + let span = DateSpan::from_period(d(2026, 2, 15), DateSpanPeriod::Month); + assert_eq!(span.start, d(2026, 2, 1)); + assert_eq!(span.end, d(2026, 2, 28)); + assert_eq!(span.num_days(), 28); + } + + #[test] + fn quarter_period_q1() { + let span = DateSpan::from_period(d(2026, 2, 15), DateSpanPeriod::Quarter); + assert_eq!(span.start, d(2026, 1, 1)); + assert_eq!(span.end, d(2026, 3, 31)); + } + + #[test] + fn year_period() { + let span = DateSpan::from_period(d(2026, 7, 3), DateSpanPeriod::Year); + assert_eq!(span.start, d(2026, 1, 1)); + assert_eq!(span.end, d(2026, 12, 31)); + } + + #[test] + fn contains_inclusive() { + let span = DateSpan::range(d(2026, 4, 1), d(2026, 4, 30)); + assert!(span.contains(&d(2026, 4, 1))); + assert!(span.contains(&d(2026, 4, 15))); + assert!(span.contains(&d(2026, 4, 30))); + assert!(!span.contains(&d(2026, 3, 31))); + assert!(!span.contains(&d(2026, 5, 1))); + } + + #[test] + fn plus_minus_shifts_dates() { + let span = DateSpan::range(d(2026, 4, 1), d(2026, 4, 10)); + let shifted = span.plus(Duration::days(5)); + assert_eq!(shifted.start, d(2026, 4, 6)); + assert_eq!(shifted.end, d(2026, 4, 15)); + + let shifted_back = span.minus(Duration::days(3)); + assert_eq!(shifted_back.start, d(2026, 3, 29)); + assert_eq!(shifted_back.end, d(2026, 4, 7)); + } + + #[test] + fn each_day_iterates_correctly() { + let span = DateSpan::range(d(2026, 4, 1), d(2026, 4, 3)); + let mut dates = Vec::new(); + let mut indices = Vec::new(); + span.each_day(|d, i| { + dates.push(d); + indices.push(i); + }); + assert_eq!(dates, vec![d(2026, 4, 1), d(2026, 4, 2), d(2026, 4, 3)]); + assert_eq!(indices, vec![0, 1, 2]); + } + + #[test] + fn from_str_parses_date_period() { + let today = d(2026, 4, 15); + let span = DateSpan::from_str("2026-04-01,month", today).unwrap(); + assert_eq!(span.start, d(2026, 4, 1)); + assert_eq!(span.end, d(2026, 4, 30)); + assert!(span.is_month()); + } + + #[test] + fn from_str_parses_date_range() { + let today = d(2026, 4, 15); + let span = DateSpan::from_str("2026-04-01,2026-04-30", today).unwrap(); + assert_eq!(span.start, d(2026, 4, 1)); + assert_eq!(span.end, d(2026, 4, 30)); + assert!(span.is_range()); + } + + #[test] + fn from_str_keyword_today() { + let today = d(2026, 4, 15); + let span = DateSpan::from_str("today", today).unwrap(); + assert_eq!(span.start, today); + assert_eq!(span.end, today); + assert!(span.is_day()); + } + + #[test] + fn from_str_invalid_returns_none() { + let today = d(2026, 4, 15); + assert!(DateSpan::from_str("not-a-date", today).is_none()); + assert!(DateSpan::from_str("2026-04-01,invalid", today).is_none()); + } + + #[test] + fn prev_month_from_april_is_march() { + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Month); + let prev = span.prev(); + assert_eq!(prev.start, d(2026, 3, 1)); + assert_eq!(prev.end, d(2026, 3, 31)); + } + + #[test] + fn next_month_from_april_is_may() { + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Month); + let next = span.next(); + assert_eq!(next.start, d(2026, 5, 1)); + assert_eq!(next.end, d(2026, 5, 31)); + } + + #[test] + fn to_str_format_for_period() { + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Month); + assert_eq!(span.to_str(), "2026-04-01,month"); + } + + #[test] + fn to_str_format_for_range() { + let span = DateSpan::range(d(2026, 4, 1), d(2026, 4, 30)); + assert_eq!(span.to_str(), "2026-04-01,2026-04-30"); + } + + #[test] + fn dis_format_matches_funcs_docs_examples() { + // toDateSpan(2010-07-01..2010-07-03) >> 01-Jul-2010..03-Jul-2010 + let range = DateSpan::range(d(2010, 7, 1), d(2010, 7, 3)); + assert_eq!(range.dis(), "01-Jul-2010..03-Jul-2010"); + + // toDateSpan(2010-07) >> 01-Jul-2010..31-Jul-2010 + let month = DateSpan::from_period(d(2010, 7, 15), DateSpanPeriod::Month); + assert_eq!(month.dis(), "01-Jul-2010..31-Jul-2010"); + + // toDateSpan(2010) >> 01-Jan-2010..31-Dec-2010 + let year = DateSpan::from_period(d(2010, 6, 1), DateSpanPeriod::Year); + assert_eq!(year.dis(), "01-Jan-2010..31-Dec-2010"); + } + + fn ends(span: &DateSpan) -> (Date, Date) { + (span.start, span.end) + } + + #[test] + fn make_date_falls_back_to_min_for_invalid_input() { + assert_eq!(make_date(2026, 13, 1), NaiveDate::MIN); + assert_eq!( + make_date(2026, 4, 15), + NaiveDate::from_ymd_opt(2026, 4, 15).unwrap() + ); + } + + #[test] + fn month_abbr_covers_all_months() { + let names: Vec<&str> = (1..=12).map(month_abbr).collect(); + assert_eq!( + names, + [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + ] + ); + assert_eq!(month_abbr(0), ""); + assert_eq!(month_abbr(13), ""); + } + + #[test] + fn period_string_round_trip() { + let periods = [ + DateSpanPeriod::Day, + DateSpanPeriod::Week, + DateSpanPeriod::Month, + DateSpanPeriod::Quarter, + DateSpanPeriod::Year, + DateSpanPeriod::Range, + ]; + for period in periods { + assert_eq!(DateSpanPeriod::from_str(period.as_str()), Some(period)); + } + assert_eq!(DateSpanPeriod::from_str("bogus"), None); + } + + #[test] + fn period_predicates() { + let day = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Day); + let week = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Week); + let month = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Month); + let quarter = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Quarter); + let year = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Year); + let range = DateSpan::range(d(2026, 4, 1), d(2026, 4, 2)); + + assert!(day.is_day() && !day.is_week()); + assert!(week.is_week() && !week.is_month()); + assert!(month.is_month() && !month.is_quarter()); + assert!(quarter.is_quarter() && !quarter.is_year()); + assert!(year.is_year() && !year.is_range()); + assert!(range.is_range() && !range.is_day()); + } + + #[test] + fn from_period_range_is_single_day() { + let span = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Range); + assert_eq!(ends(&span), (d(2026, 4, 15), d(2026, 4, 15))); + assert!(span.is_range()); + } + + #[test] + fn from_period_year_end_rollovers() { + let december = DateSpan::from_period(d(2026, 12, 10), DateSpanPeriod::Month); + assert_eq!(ends(&december), (d(2026, 12, 1), d(2026, 12, 31))); + + let q3 = DateSpan::from_period(d(2026, 8, 10), DateSpanPeriod::Quarter); + assert_eq!(ends(&q3), (d(2026, 7, 1), d(2026, 9, 30))); + + let q4 = DateSpan::from_period(d(2026, 11, 10), DateSpanPeriod::Quarter); + assert_eq!(ends(&q4), (d(2026, 10, 1), d(2026, 12, 31))); + } + + #[test] + fn prev_and_next_for_every_period() { + let day = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Day); + assert_eq!(ends(&day.prev()), (d(2026, 4, 14), d(2026, 4, 14))); + assert_eq!(ends(&day.next()), (d(2026, 4, 16), d(2026, 4, 16))); + + let week = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Week); + assert_eq!(ends(&week.prev()), (d(2026, 4, 5), d(2026, 4, 11))); + assert_eq!(ends(&week.next()), (d(2026, 4, 19), d(2026, 4, 25))); + + let january = DateSpan::from_period(d(2026, 1, 10), DateSpanPeriod::Month); + assert_eq!(ends(&january.prev()), (d(2025, 12, 1), d(2025, 12, 31))); + assert_eq!(ends(&january.prev().next()), ends(&january)); + + let quarter = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Quarter); + assert_eq!(ends(&quarter.prev()), (d(2026, 1, 1), d(2026, 3, 31))); + assert_eq!(ends(&quarter.next()), (d(2026, 7, 1), d(2026, 9, 30))); + assert!(quarter.prev().is_quarter() && quarter.next().is_quarter()); + + let year = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Year); + assert_eq!(ends(&year.prev()), (d(2025, 1, 1), d(2025, 12, 31))); + assert_eq!(ends(&year.next()), (d(2027, 1, 1), d(2027, 12, 31))); + + // A range rolls by one day, regardless of its length. + let range = DateSpan::range(d(2026, 4, 1), d(2026, 4, 10)); + assert_eq!(ends(&range.prev()), (d(2026, 3, 31), d(2026, 4, 9))); + assert_eq!(ends(&range.next()), (d(2026, 4, 2), d(2026, 4, 11))); + assert!(range.prev().is_range() && range.next().is_range()); + } + + #[test] + fn plus_minus_produce_range() { + let month = DateSpan::from_period(d(2026, 4, 15), DateSpanPeriod::Month); + let plus = month.plus(Duration::days(1)); + assert_eq!(ends(&plus), (d(2026, 4, 2), d(2026, 5, 1))); + assert!(plus.is_range()); + let minus = month.minus(Duration::days(1)); + assert_eq!(ends(&minus), (d(2026, 3, 31), d(2026, 4, 29))); + assert!(minus.is_range()); + } + + #[test] + fn each_month_visits_every_overlapping_month() { + let span = DateSpan::range(d(2026, 1, 15), d(2026, 3, 10)); + let mut months = Vec::new(); + span.each_month(|m| months.push(ends(&m))); + assert_eq!( + months, + vec![ + (d(2026, 1, 1), d(2026, 1, 31)), + (d(2026, 2, 1), d(2026, 2, 28)), + (d(2026, 3, 1), d(2026, 3, 31)), + ] + ); + + let mut count = 0; + DateSpan::range(d(2026, 4, 3), d(2026, 4, 20)).each_month(|_| count += 1); + assert_eq!(count, 1); + } + + #[test] + fn to_date_list_has_one_date_per_day() { + let span = DateSpan::range(d(2026, 2, 27), d(2026, 3, 2)); + assert_eq!( + span.to_date_list(), + vec![d(2026, 2, 27), d(2026, 2, 28), d(2026, 3, 1), d(2026, 3, 2)] + ); + } + + #[test] + fn from_str_keywords() { + let today = d(2026, 4, 15); // a Wednesday + let cases = [ + ( + "yesterday", + d(2026, 4, 14), + d(2026, 4, 14), + DateSpanPeriod::Day, + ), + ( + "thisWeek", + d(2026, 4, 12), + d(2026, 4, 18), + DateSpanPeriod::Week, + ), + ( + "thisMonth", + d(2026, 4, 1), + d(2026, 4, 30), + DateSpanPeriod::Month, + ), + ( + "thisQuarter", + d(2026, 4, 1), + d(2026, 6, 30), + DateSpanPeriod::Quarter, + ), + ( + "thisYear", + d(2026, 1, 1), + d(2026, 12, 31), + DateSpanPeriod::Year, + ), + ( + "lastWeek", + d(2026, 4, 5), + d(2026, 4, 11), + DateSpanPeriod::Week, + ), + ( + "lastMonth", + d(2026, 3, 1), + d(2026, 3, 31), + DateSpanPeriod::Month, + ), + ( + "lastQuarter", + d(2026, 1, 1), + d(2026, 3, 31), + DateSpanPeriod::Quarter, + ), + ( + "lastYear", + d(2025, 1, 1), + d(2025, 12, 31), + DateSpanPeriod::Year, + ), + ( + "pastWeek", + d(2026, 4, 8), + d(2026, 4, 15), + DateSpanPeriod::Range, + ), + ( + "pastMonth", + d(2026, 3, 16), + d(2026, 4, 15), + DateSpanPeriod::Range, + ), + ( + "pastYear", + d(2025, 4, 15), + d(2026, 4, 15), + DateSpanPeriod::Range, + ), + ]; + for (text, start, end, period) in cases { + let span = DateSpan::from_str(text, today).unwrap_or_else(|| panic!("{text}")); + assert_eq!(ends(&span), (start, end), "{text}"); + assert_eq!(span.period, period, "{text}"); + } + } + + #[test] + fn past_year_clamps_leap_day() { + let span = DateSpan::from_str("pastYear", d(2028, 2, 29)).unwrap(); + assert_eq!(ends(&span), (d(2027, 2, 28), d(2028, 2, 29))); + } + + #[test] + fn from_str_trims_whitespace_and_parses_week_period() { + let today = d(2026, 4, 15); + assert!(DateSpan::from_str(" today ", today).unwrap().is_day()); + + // 2026-04-01 is a Wednesday + let week = DateSpan::from_str("2026-04-01,week", today).unwrap(); + assert_eq!(ends(&week), (d(2026, 3, 29), d(2026, 4, 4))); + } + + #[test] + fn from_str_rejects_bad_dates() { + let today = d(2026, 4, 15); + assert!(DateSpan::from_str("2026-13-01,month", today).is_none()); + assert!(DateSpan::from_str("2026-04-01,2026-99-99", today).is_none()); + assert!(DateSpan::from_str("", today).is_none()); + } + + #[test] + fn to_str_round_trips_for_every_period() { + let today = d(2026, 4, 15); + let spans = [ + DateSpan::from_period(today, DateSpanPeriod::Day), + DateSpan::from_period(today, DateSpanPeriod::Week), + DateSpan::from_period(today, DateSpanPeriod::Month), + DateSpan::from_period(today, DateSpanPeriod::Quarter), + DateSpan::from_period(today, DateSpanPeriod::Year), + DateSpan::range(d(2026, 4, 3), d(2026, 4, 9)), + ]; + for span in spans { + let encoded = span.to_str(); + assert_eq!(DateSpan::from_str(&encoded, today), Some(span), "{encoded}"); + } + } + + #[test] + fn dis_for_single_day() { + let day = DateSpan::from_period(d(2026, 4, 5), DateSpanPeriod::Day); + assert_eq!(day.dis(), "05-Apr-2026..05-Apr-2026"); + } +} diff --git a/src/haystack/span/date_time_span.rs b/src/haystack/span/date_time_span.rs new file mode 100644 index 0000000..e101f63 --- /dev/null +++ b/src/haystack/span/date_time_span.rs @@ -0,0 +1,1498 @@ +// Copyright (c) 2026, J2 Innovations. All Rights Reserved + +//! Timezone-aware DateTime span type (inclusive start, exclusive end). +//! +//! A `Span` represents a DateTime range with +//! timezone awareness. Unlike `DateSpan` (see [`DateSpan`](super::DateSpan)), `Span` operates at +//! DateTime granularity with an **exclusive end** (start is inclusive, end is exclusive). +//! +//! `Span` can be either absolute (fixed start/end DateTime values) or relative (a mode like +//! `today`, `thisWeek`, `pastMonth` that resolves to absolute dates when `fresh()` is called). +//! +//! # Timezones +//! +//! A `Span` does not store a timezone of its own: it is carried by `start` and `end`, which are +//! required to share the same IANA timezone (enforced by [`Span::make_abs`]). All date-level +//! operations — [`Span::to_date_span`], [`Span::num_days`], [`Span::dis`], [`Span::prev`], +//! [`Span::next`] and the alignment predicates — are evaluated against the *local* calendar dates +//! in that timezone, so they stay correct across DST transitions (a 23- or 25-hour day still +//! counts as one day). + +use crate::val::{Date, DateTime}; +use chrono::{ + Datelike, Days, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeDelta, + TimeZone, Timelike, Weekday, +}; +use chrono_tz::Tz; + +use super::date_span::{DateSpan, DateSpanPeriod, fmt_date_dd_mmm_yyyy}; + +/// The weekday a week-aligned span starts on. Fantom uses the current locale's start of week; +/// this port fixes it to Sunday, matching [`DateSpan`]'s own week alignment. +const START_OF_WEEK: Weekday = Weekday::Sun; + +/// Formats a `DateTime` as `"DD-MMM-YYYY HH:MM"`, e.g. `"15-Jul-2026 14:30"` — used by +/// `Span::dis()` for a span that isn't aligned to midnight date boundaries. +fn fmt_datetime_dd_mmm_yyyy_hm(dt: &DateTime) -> String { + format!( + "{} {:02}:{:02}", + fmt_date_dd_mmm_yyyy(&Date::from(dt.date_naive())), + dt.hour(), + dt.minute() + ) +} + +/// Adds `days` calendar days to a date, saturating at the representable range. +/// +/// Calendar arithmetic, unlike adding `24h` to a DateTime, is unaffected by DST transitions. +fn add_days(date: NaiveDate, days: u64) -> NaiveDate { + date.checked_add_days(Days::new(days)) + .unwrap_or(NaiveDate::MAX) +} + +/// Subtracts `days` calendar days from a date, saturating at the representable range. +fn sub_days(date: NaiveDate, days: u64) -> NaiveDate { + date.checked_sub_days(Days::new(days)) + .unwrap_or(NaiveDate::MIN) +} + +/// The first day of `date`'s month. +fn first_of_month(date: NaiveDate) -> NaiveDate { + date.with_day(1).unwrap_or(date) +} + +/// The first day of the month following `date`'s month. +fn first_of_next_month(date: NaiveDate) -> NaiveDate { + let (year, month) = if date.month() == 12 { + (date.year() + 1, 1) + } else { + (date.year(), date.month() + 1) + }; + NaiveDate::from_ymd_opt(year, month, 1).unwrap_or(date) +} + +/// The first day of the quarter containing `date`. +fn first_of_quarter(date: NaiveDate) -> NaiveDate { + let month = (date.month() - 1) / 3 * 3 + 1; + NaiveDate::from_ymd_opt(date.year(), month, 1).unwrap_or(date) +} + +/// The first day of the quarter following the one containing `date`. +fn first_of_next_quarter(date: NaiveDate) -> NaiveDate { + let start = first_of_quarter(date); + let month = start.month() + 3; + if month > 12 { + NaiveDate::from_ymd_opt(start.year() + 1, 1, 1).unwrap_or(date) + } else { + NaiveDate::from_ymd_opt(start.year(), month, 1).unwrap_or(date) + } +} + +/// January 1st of the given year. +fn first_of_year(year: i32) -> NaiveDate { + NaiveDate::from_ymd_opt(year, 1, 1).unwrap_or(NaiveDate::MIN) +} + +/// The mode of a [`Span`] — either absolute or one of the relative period shortcuts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SpanMode { + /// Absolute span with fixed start/end. + Abs, + /// Today (midnight to midnight). + Today, + /// Yesterday. + Yesterday, + /// This week (start of week to the same weekday next week). + ThisWeek, + /// Last week (previous week, same alignment as `ThisWeek`). + LastWeek, + /// Past 7 days, ending at today's midnight (exclusive, so today is not included). + PastWeek, + /// This month (1st to 1st of next month). + ThisMonth, + /// Last month. + LastMonth, + /// Past 28 days, ending at today's midnight (exclusive). + PastMonth, + /// This quarter. + ThisQuarter, + /// Last quarter. + LastQuarter, + /// Past 90 days, ending at today's midnight (exclusive). + PastQuarter, + /// This year (Jan 1 to next Jan 1). + ThisYear, + /// Last year. + LastYear, + /// Past 365 days, ending at today's midnight (exclusive). + PastYear, +} + +impl SpanMode { + /// Whether this mode is relative (needs `fresh()` to resolve to absolute dates). + pub fn is_rel(&self) -> bool { + !matches!(self, SpanMode::Abs) + } + + /// Whether this mode is absolute. + pub fn is_abs(&self) -> bool { + matches!(self, SpanMode::Abs) + } + + /// The period this mode represents. + pub fn period(&self) -> SpanModePeriod { + match self { + SpanMode::Abs => SpanModePeriod::Abs, + SpanMode::Today | SpanMode::Yesterday => SpanModePeriod::Day, + SpanMode::ThisWeek | SpanMode::LastWeek | SpanMode::PastWeek => SpanModePeriod::Week, + SpanMode::ThisMonth | SpanMode::LastMonth | SpanMode::PastMonth => { + SpanModePeriod::Month + } + SpanMode::ThisQuarter | SpanMode::LastQuarter | SpanMode::PastQuarter => { + SpanModePeriod::Quarter + } + SpanMode::ThisYear | SpanMode::LastYear | SpanMode::PastYear => SpanModePeriod::Year, + } + } + + /// Display name for the mode. + pub fn dis(&self) -> &'static str { + match self { + SpanMode::Abs => "abs", + SpanMode::Today => "today", + SpanMode::Yesterday => "yesterday", + SpanMode::ThisWeek => "thisWeek", + SpanMode::LastWeek => "lastWeek", + SpanMode::PastWeek => "pastWeek", + SpanMode::ThisMonth => "thisMonth", + SpanMode::LastMonth => "lastMonth", + SpanMode::PastMonth => "pastMonth", + SpanMode::ThisQuarter => "thisQuarter", + SpanMode::LastQuarter => "lastQuarter", + SpanMode::PastQuarter => "pastQuarter", + SpanMode::ThisYear => "thisYear", + SpanMode::LastYear => "lastYear", + SpanMode::PastYear => "pastYear", + } + } + + /// Parse a mode from its display name. + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Option { + match s { + "abs" => Some(SpanMode::Abs), + "today" => Some(SpanMode::Today), + "yesterday" => Some(SpanMode::Yesterday), + "thisWeek" => Some(SpanMode::ThisWeek), + "lastWeek" => Some(SpanMode::LastWeek), + "pastWeek" => Some(SpanMode::PastWeek), + "thisMonth" => Some(SpanMode::ThisMonth), + "lastMonth" => Some(SpanMode::LastMonth), + "pastMonth" => Some(SpanMode::PastMonth), + "thisQuarter" => Some(SpanMode::ThisQuarter), + "lastQuarter" => Some(SpanMode::LastQuarter), + "pastQuarter" => Some(SpanMode::PastQuarter), + "thisYear" => Some(SpanMode::ThisYear), + "lastYear" => Some(SpanMode::LastYear), + "pastYear" => Some(SpanMode::PastYear), + _ => None, + } + } +} + +/// The period granularity of a [`SpanMode`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SpanModePeriod { + Abs, + Day, + Week, + Month, + Quarter, + Year, +} + +/// A timezone-aware DateTime span. +/// +/// Key invariants, enforced by the constructors: +/// - `start` is **inclusive** +/// - `end` is **exclusive** (this is the main difference from `DateSpan`, which is inclusive on +/// both ends) +/// - `start <= end` +/// - Both `start` and `end` are in the same timezone +/// +/// A `Span` can be absolute (fixed dates) or relative (a `SpanMode` that resolves lazily). +/// Call `fresh()` to resolve a relative span to absolute dates. +/// +/// Equality follows Haxall: relative spans are equal when their modes match (whatever dates +/// or timezone they resolved to), absolute spans when their start and end match. +#[derive(Debug, Clone)] +pub struct Span { + start: DateTime, + end: DateTime, + mode: SpanMode, + aligns_to_dates: bool, +} + +impl Span { + /// Create an absolute span from two DateTime values. + /// + /// Returns an error if `start` and `end` are in different timezones, or if `start > end`. + pub fn make_abs(start: DateTime, end: DateTime) -> Result { + if start.timezone() != end.timezone() { + return Err(format!( + "Mismatched tz: {} != {}", + start.timezone(), + end.timezone() + )); + } + if start > end { + return Err("start > end".into()); + } + Ok(Span::make_date_times(SpanMode::Abs, start, end)) + } + + /// Internal constructor from two DateTime values known to satisfy the invariants. + fn make_date_times(mode: SpanMode, start: DateTime, end: DateTime) -> Self { + let aligns_to_dates = is_midnight(&start) && is_midnight(&end); + Span { + start, + end, + mode, + aligns_to_dates, + } + } + + /// Internal constructor from an inclusive start date and an **exclusive** end date, both + /// resolved to midnight in `tz`. + fn make_dates(mode: SpanMode, start: NaiveDate, end: NaiveDate, tz: Tz) -> Self { + Span { + start: date_at_midnight(start, tz), + end: date_at_midnight(end, tz), + mode, + aligns_to_dates: true, + } + } + + /// Create a span for a single date in the given timezone (midnight to midnight). + pub fn make_date(date: Date, tz: Tz) -> Self { + Span::make_dates(SpanMode::Abs, *date, add_days(*date, 1), tz) + } + + /// Create a relative span for the given mode and timezone, resolved against the current + /// date in that timezone. + pub fn make_rel(mode: SpanMode, tz: Tz) -> Self { + Span::do_make_rel(mode, local_today(tz), tz) + } + + /// Resolve a relative mode using a caller-supplied local date in `tz`, without reading + /// the system clock. The resulting span retains its relative mode. + /// + /// `SpanMode::Abs` has no period to resolve and yields an absolute single-day span. + /// + /// ``` + /// use chrono::NaiveDate; + /// use chrono_tz::Tz; + /// use libhaystack::{span::{Span, SpanMode}, val::Date}; + /// + /// let today = Date::from(NaiveDate::from_ymd_opt(2026, 3, 29).unwrap()); + /// let span = Span::make_rel_on(SpanMode::Today, today, Tz::Europe__London); + /// assert_eq!(span.start_date(), today); + /// assert_eq!(span.num_days(), 1); + /// assert_eq!(span.mode(), SpanMode::Today); + /// ``` + pub fn make_rel_on(mode: SpanMode, today: Date, tz: Tz) -> Self { + Span::do_make_rel(mode, *today, tz) + } + + /// Resolve a relative mode against a given "today" date in `tz`. + fn do_make_rel(mode: SpanMode, today: NaiveDate, tz: Tz) -> Self { + let (start, end) = match mode { + // An absolute mode has no period to resolve; treat it as a single day. + SpanMode::Abs => (today, add_days(today, 1)), + SpanMode::Today => (today, add_days(today, 1)), + SpanMode::Yesterday => (sub_days(today, 1), today), + SpanMode::ThisWeek => { + let start = start_of_week(today); + (start, add_days(start, 7)) + } + SpanMode::LastWeek => { + let start = sub_days(start_of_week(today), 7); + (start, add_days(start, 7)) + } + SpanMode::PastWeek => (sub_days(today, 7), today), + SpanMode::ThisMonth => (first_of_month(today), first_of_next_month(today)), + SpanMode::LastMonth => { + let last = sub_days(first_of_month(today), 1); + (first_of_month(last), first_of_next_month(last)) + } + SpanMode::PastMonth => (sub_days(today, 28), today), + SpanMode::ThisQuarter => (first_of_quarter(today), first_of_next_quarter(today)), + SpanMode::LastQuarter => { + let last = sub_days(first_of_quarter(today), 1); + (first_of_quarter(last), first_of_next_quarter(last)) + } + SpanMode::PastQuarter => (sub_days(today, 90), today), + SpanMode::ThisYear => (first_of_year(today.year()), first_of_year(today.year() + 1)), + SpanMode::LastYear => (first_of_year(today.year() - 1), first_of_year(today.year())), + SpanMode::PastYear => (sub_days(today, 365), today), + }; + Span::make_dates(mode, start, end, tz) + } + + /// Create a "today" span for the given timezone. + pub fn today(tz: Tz) -> Self { + Span::make_rel(SpanMode::Today, tz) + } + + /// Resolve a relative span to its current absolute dates. + /// For absolute spans, this is a no-op (returns a clone). + pub fn fresh(&self) -> Self { + if self.mode.is_abs() { + return self.clone(); + } + Span::make_rel(self.mode, self.tz()) + } + + /// Refresh using a caller-supplied local date in this span's timezone. + /// Absolute spans are returned unchanged. + pub fn fresh_on(&self, today: Date) -> Self { + if self.mode.is_abs() { + return self.clone(); + } + Span::make_rel_on(self.mode, today, self.tz()) + } + + /// Inclusive start DateTime. + pub fn start(&self) -> &DateTime { + &self.start + } + + /// Exclusive end DateTime. + pub fn end(&self) -> &DateTime { + &self.end + } + + /// Whether this span is absolute or relative. + pub fn mode(&self) -> SpanMode { + self.mode + } + + /// Get the timezone of this span. Both `start` and `end` are in this timezone. + pub fn tz(&self) -> Tz { + self.start.timezone() + } + + /// The local start date in this span's timezone. + pub fn start_date(&self) -> Date { + Date::from(self.start.date_naive()) + } + + /// The local **exclusive** end date in this span's timezone. + pub fn end_date(&self) -> Date { + Date::from(self.end.date_naive()) + } + + /// Convert to a different timezone, keeping the same instants. + /// + /// The result is always absolute, and its alignment is recomputed — a span aligned to + /// midnight in one timezone is generally not aligned to midnight in another. + pub fn to_time_zone(&self, tz: Tz) -> Self { + if self.tz() == tz { + return self.clone(); + } + Span::make_date_times( + SpanMode::Abs, + DateTime::from(self.start.with_iana_timezone(tz)), + DateTime::from(self.end.with_iana_timezone(tz)), + ) + } + + /// Convert to a `DateSpan` using the aligned local dates. + /// + /// For compatibility, an empty midnight-aligned span converts to a single day. + /// Use [`try_to_date_span`](Self::try_to_date_span) to reject empty spans instead. + pub fn to_date_span(&self) -> DateSpan { + let start = self.start.date_naive(); + if !self.aligns_to_dates { + // Not midnight-aligned: both local dates are taken as-is (inclusive). + return DateSpan::range(Date::from(start), self.end_date()); + } + if self.aligns_to_day() { + return DateSpan::from_period(Date::from(start), DateSpanPeriod::Day); + } + if self.aligns_to_week() { + return DateSpan::from_period(Date::from(start), DateSpanPeriod::Week); + } + if self.aligns_to_month() { + return DateSpan::from_period(Date::from(start), DateSpanPeriod::Month); + } + if self.aligns_to_quarter() { + return DateSpan::from_period(Date::from(start), DateSpanPeriod::Quarter); + } + if self.aligns_to_year() { + return DateSpan::from_period(Date::from(start), DateSpanPeriod::Year); + } + // The exclusive end date becomes an inclusive one, using calendar arithmetic. + DateSpan::range( + Date::from(start), + Date::from(sub_days(self.end.date_naive(), 1)), + ) + } + + /// Convert to an inclusive `DateSpan`, returning `None` for an empty span. + /// Non-empty spans use the same local-date semantics as [`to_date_span`](Self::to_date_span). + pub fn try_to_date_span(&self) -> Option { + if self.is_empty() { + None + } else { + Some(self.to_date_span()) + } + } + + /// Whether this span contains no instants. + pub fn is_empty(&self) -> bool { + self.start == self.end + } + + /// Check if a DateTime is contained within this span (inclusive start, exclusive end). + pub fn contains(&self, ts: &DateTime) -> bool { + *ts >= self.start && *ts < self.end + } + + /// Number of whole days this span includes, counted as *calendar* days in this span's + /// timezone (so a DST transition does not add or drop a day). + pub fn num_days(&self) -> i64 { + (self.end.date_naive() - self.start.date_naive()).num_days() + } + + /// Which quarter (1-4) this span falls in (based on the local start date). + pub fn quarter(&self) -> i32 { + ((self.start.date_naive().month() - 1) / 3 + 1) as i32 + } + + /// Whether this span aligns to midnight date boundaries in its timezone. + pub fn aligns_to_dates(&self) -> bool { + self.aligns_to_dates + } + + /// Does this span align to a single day? + pub fn aligns_to_day(&self) -> bool { + self.aligns_to_dates && self.num_days() <= 1 + } + + /// Does this span align to a single week starting on [`START_OF_WEEK`]? + pub fn aligns_to_week(&self) -> bool { + self.aligns_to_dates + && self.start.date_naive().weekday() == START_OF_WEEK + && self.num_days() == 7 + } + + /// Does this span align to a single month (1st to the 1st of the next month)? + pub fn aligns_to_month(&self) -> bool { + if !self.aligns_to_dates { + return false; + } + let (start, end) = (self.start.date_naive(), self.end.date_naive()); + if start.day() != 1 || end.day() != 1 { + return false; + } + first_of_next_month(start) == end + } + + /// Does this span align to a single quarter (1st of the quarter to the 1st of the next)? + pub fn aligns_to_quarter(&self) -> bool { + if !self.aligns_to_dates { + return false; + } + let (start, end) = (self.start.date_naive(), self.end.date_naive()); + if start.day() != 1 || end.day() != 1 { + return false; + } + if (start.month() - 1) % 3 != 0 { + return false; + } + first_of_next_quarter(start) == end + } + + /// Does this span align to a single year (Jan 1 to the next Jan 1)? + pub fn aligns_to_year(&self) -> bool { + if !self.aligns_to_dates { + return false; + } + let (start, end) = (self.start.date_naive(), self.end.date_naive()); + start.day() == 1 + && end.day() == 1 + && start.month() == 1 + && end.month() == 1 + && start.year() + 1 == end.year() + } + + /// Get the previous period, relative to this span's current alignment. + /// + /// For the `this*` relative modes this returns the matching `last*` relative span. + pub fn prev(&self) -> Self { + let tz = self.tz(); + match self.mode { + SpanMode::Today => return Span::make_rel(SpanMode::Yesterday, tz), + SpanMode::ThisWeek => return Span::make_rel(SpanMode::LastWeek, tz), + SpanMode::ThisMonth => return Span::make_rel(SpanMode::LastMonth, tz), + SpanMode::ThisQuarter => return Span::make_rel(SpanMode::LastQuarter, tz), + SpanMode::ThisYear => return Span::make_rel(SpanMode::LastYear, tz), + _ => {} + } + + let (start, end) = (self.start.date_naive(), self.end.date_naive()); + if self.aligns_to_day() { + return Span::make_dates(SpanMode::Abs, sub_days(start, 1), sub_days(end, 1), tz); + } + if self.aligns_to_week() { + return Span::make_dates(SpanMode::Abs, sub_days(start, 7), sub_days(end, 7), tz); + } + if self.aligns_to_month() { + let prev_start = first_of_month(sub_days(start, 1)); + return Span::make_dates(SpanMode::Abs, prev_start, start, tz); + } + if self.aligns_to_quarter() { + let prev_start = first_of_quarter(sub_days(start, 1)); + return Span::make_dates(SpanMode::Abs, prev_start, start, tz); + } + if self.aligns_to_year() { + return Span::make_dates( + SpanMode::Abs, + first_of_year(start.year() - 1), + first_of_year(start.year()), + tz, + ); + } + if self.aligns_to_dates { + let days = self.num_days().unsigned_abs(); + return Span::make_dates( + SpanMode::Abs, + sub_days(start, days), + sub_days(end, days), + tz, + ); + } + let diff = *self.end - *self.start; + Span::make_date_times( + SpanMode::Abs, + DateTime::from(*self.start - diff), + DateTime::from(*self.end - diff), + ) + } + + /// Get the next period, relative to this span's current alignment. + /// + /// For the `last*` relative modes this returns the matching `this*` relative span. + pub fn next(&self) -> Self { + let tz = self.tz(); + match self.mode { + SpanMode::Yesterday => return Span::make_rel(SpanMode::Today, tz), + SpanMode::LastWeek => return Span::make_rel(SpanMode::ThisWeek, tz), + SpanMode::LastMonth => return Span::make_rel(SpanMode::ThisMonth, tz), + SpanMode::LastQuarter => return Span::make_rel(SpanMode::ThisQuarter, tz), + SpanMode::LastYear => return Span::make_rel(SpanMode::ThisYear, tz), + _ => {} + } + + let (start, end) = (self.start.date_naive(), self.end.date_naive()); + if self.aligns_to_day() { + return Span::make_dates(SpanMode::Abs, add_days(start, 1), add_days(end, 1), tz); + } + if self.aligns_to_week() { + return Span::make_dates(SpanMode::Abs, add_days(start, 7), add_days(end, 7), tz); + } + if self.aligns_to_month() { + return Span::make_dates(SpanMode::Abs, end, first_of_next_month(end), tz); + } + if self.aligns_to_quarter() { + return Span::make_dates(SpanMode::Abs, end, first_of_next_quarter(end), tz); + } + if self.aligns_to_year() { + return Span::make_dates( + SpanMode::Abs, + first_of_year(end.year()), + first_of_year(end.year() + 1), + tz, + ); + } + if self.aligns_to_dates { + let days = self.num_days().unsigned_abs(); + return Span::make_dates( + SpanMode::Abs, + add_days(start, days), + add_days(end, days), + tz, + ); + } + let diff = *self.end - *self.start; + Span::make_date_times( + SpanMode::Abs, + DateTime::from(*self.start + diff), + DateTime::from(*self.end + diff), + ) + } + + /// Iterate over each day in the span. Empty spans invoke no callbacks. + pub fn each_day(&self, func: F) + where + F: FnMut(Date, i32), + { + if let Some(dates) = self.try_to_date_span() { + dates.each_day(func); + } + } + + /// Machine-parseable string representation, round-trippable through + /// [`from_str`](Span::from_str) for the same timezone. + /// + /// - relative span: the mode name, e.g. `"thisWeek"` + /// - single day: `"YYYY-MM-DD"` + /// - midnight-aligned range (including an empty one): `"YYYY-MM-DD,YYYY-MM-DD"` (the end + /// date is **exclusive**) + /// - anything else: `","` + pub fn to_str(&self) -> String { + if self.mode.is_rel() { + return self.mode.dis().to_string(); + } + if self.aligns_to_dates { + // An empty span (num_days == 0) must not collapse to a date, which parses as a full day. + if self.aligns_to_day() && self.num_days() == 1 { + return self.start.date_naive().format("%Y-%m-%d").to_string(); + } + return format!( + "{},{}", + self.start.date_naive().format("%Y-%m-%d"), + self.end.date_naive().format("%Y-%m-%d") + ); + } + format!("{},{}", self.start.to_rfc3339(), self.end.to_rfc3339()) + } + + /// Human-friendly display string for the console/REPL, e.g. `"01-Jul-2010..03-Jul-2010"`. + /// Always renders the explicit inclusive `start..end` date range (or datetime range, for a + /// span not aligned to midnight boundaries) with a zero-padded day and 4-digit year, + /// matching the format used by the Funcs.xeto docs' own examples, regardless of mode. + /// An empty span is rendered as a datetime range, so it does not read as a whole day. + pub fn dis(&self) -> String { + if !self.aligns_to_dates || self.is_empty() { + return format!( + "{}..{}", + fmt_datetime_dd_mmm_yyyy_hm(&self.start), + fmt_datetime_dd_mmm_yyyy_hm(&self.end) + ); + } + let date_span = self.to_date_span(); + format!( + "{}..{}", + fmt_date_dd_mmm_yyyy(&date_span.start), + fmt_date_dd_mmm_yyyy(&date_span.end) + ) + } + + /// Parse a `Span` from a string, resolving dates and local datetimes in `tz`. + /// + /// Supported formats: + /// - mode keywords: `"today"`, `"thisWeek"`, `"pastMonth"`, etc. + /// - single date: `"2026-04-01"` (midnight to midnight in `tz`) + /// - date range: `"2026-04-01,2026-05-01"` — note the end date is **exclusive**, so this is + /// the whole of April + /// - DateTime range: `"2026-04-01T10:00:00Z,2026-04-30T12:30:00+02:00"` + /// + /// Both `,` (canonical, as emitted by [`to_str`](Span::to_str)) and `..` are accepted as the + /// range separator. Timestamps may be RFC3339 (with a `Z` or a numeric offset, which are + /// honored and converted into `tz`) or a local `YYYY-MM-DDThh:mm:ss[.fff]` (interpreted in + /// `tz`). + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str, tz: Tz) -> Option { + Span::parse(s, tz, || local_today(tz)) + } + + /// Parse using a caller-supplied local date in `tz` to resolve relative modes, without + /// reading the system clock. Absolute input does not depend on `today`. + /// + /// Accepts the same formats as [`from_str`](Self::from_str). + pub fn from_str_on(s: &str, today: Date, tz: Tz) -> Option { + Span::parse(s, tz, || *today) + } + + /// `today` is only evaluated for relative mode keywords. + fn parse(s: &str, tz: Tz, today: impl FnOnce() -> NaiveDate) -> Option { + let s = s.trim(); + + if let Some(mode) = SpanMode::from_str(s) + && mode.is_rel() + { + return Some(Span::do_make_rel(mode, today(), tz)); + } + + if let Some((start_str, end_str)) = s + .split_once(',') + .or_else(|| s.split_once("..")) + .map(|(a, b)| (a.trim(), b.trim())) + { + let start = parse_date_time(start_str, tz)?; + let end = parse_date_time(end_str, tz)?; + return Span::make_abs(start, end).ok(); + } + + let date = NaiveDate::parse_from_str(s, "%Y-%m-%d").ok()?; + Some(Span::make_date(Date::from(date), tz)) + } +} + +/// Parse one side of a span range: either a date (midnight in `tz`) or a timestamp. +fn parse_date_time(s: &str, tz: Tz) -> Option { + if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") { + return Some(date_at_midnight(date, tz)); + } + // RFC3339 carries its own offset (`Z` or numeric), which identifies an absolute instant; + // re-express it in `tz`. + if let Ok(dt) = chrono::DateTime::::parse_from_rfc3339(s) { + return Some(DateTime::from(dt.with_timezone(&tz))); + } + // Otherwise treat it as a local time in `tz`. + for format in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M"] { + if let Ok(local) = NaiveDateTime::parse_from_str(s, format) { + return Some(local_to_date_time(local, tz)); + } + } + None +} + +/// Resolve a local (wall clock) datetime in `tz` to an absolute `DateTime`. +/// +/// DST makes this partial: a local time can be ambiguous (the clocks went back, so it happens +/// twice) or non-existent (the clocks went forward, skipping it). The earlier instant is used +/// when ambiguous; when the time falls in a gap, the first valid instant after the gap is used. +fn local_to_date_time(local: NaiveDateTime, tz: Tz) -> DateTime { + match tz.from_local_datetime(&local) { + LocalResult::Single(dt) => DateTime::from(dt), + LocalResult::Ambiguous(earlier, _) => DateTime::from(earlier), + LocalResult::None => { + // Step forward until the local time exists again. Transitions are aligned to + // whole minutes, and no real gap is longer than a few hours, but scan a full day + // so this always terminates with a valid instant. + // Drop seconds so stepping by whole minutes lands exactly on the transition instant. + let mut probe = local + .with_second(0) + .and_then(|t| t.with_nanosecond(0)) + .unwrap_or(local); + for _ in 0..(24 * 60) { + probe += TimeDelta::minutes(1); + match tz.from_local_datetime(&probe) { + LocalResult::Single(dt) => return DateTime::from(dt), + LocalResult::Ambiguous(earlier, _) => return DateTime::from(earlier), + LocalResult::None => {} + } + } + DateTime::from(local.and_utc().with_timezone(&tz)) + } + } +} + +/// Create a `DateTime` at midnight for a given date in a timezone. +/// +/// In zones where DST starts at midnight, that midnight does not exist; see +/// [`local_to_date_time`] for how the gap is resolved. +fn date_at_midnight(date: NaiveDate, tz: Tz) -> DateTime { + local_to_date_time(date.and_time(NaiveTime::MIN), tz) +} + +/// The current local date in `tz`, from the system clock. +fn local_today(tz: Tz) -> NaiveDate { + chrono::Utc::now().with_timezone(&tz).date_naive() +} + +/// Check if a DateTime is at local midnight. +fn is_midnight(dt: &DateTime) -> bool { + dt.time() == NaiveTime::MIN +} + +/// The [`START_OF_WEEK`] on or before `date`. +fn start_of_week(date: NaiveDate) -> NaiveDate { + let days = (date.weekday().num_days_from_sunday() as i32 + - START_OF_WEEK.num_days_from_sunday() as i32) + .rem_euclid(7); + sub_days(date, days as u64) +} + +impl PartialEq for Span { + fn eq(&self, other: &Self) -> bool { + if self.mode != other.mode { + return false; + } + self.mode.is_rel() || (self.start == other.start && self.end == other.end) + } +} + +impl Eq for Span {} + +impl From<&Span> for DateSpan { + fn from(span: &Span) -> Self { + span.to_date_span() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::NaiveDate; + + const LONDON: Tz = Tz::Europe__London; + /// Cairo's DST starts at midnight, so some dates have no local midnight at all. + const CAIRO: Tz = Tz::Africa__Cairo; + + fn d(y: i32, m: u32, day: u32) -> Date { + Date::from(NaiveDate::from_ymd_opt(y, m, day).unwrap()) + } + + fn nd(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() + } + + fn span(s: &str, tz: Tz) -> Span { + Span::from_str(s, tz).expect("span parses") + } + + #[test] + fn make_abs_creates_absolute_span() { + let start = date_at_midnight(nd(2026, 4, 1), Tz::UTC); + let end = date_at_midnight(nd(2026, 4, 30), Tz::UTC); + let span = Span::make_abs(start, end).unwrap(); + assert_eq!(span.mode(), SpanMode::Abs); + assert!(span.aligns_to_dates()); + } + + #[test] + fn make_abs_rejects_mismatched_timezones_and_reversed_range() { + let start = date_at_midnight(nd(2026, 4, 1), Tz::UTC); + let end_other_tz = date_at_midnight(nd(2026, 4, 30), LONDON); + assert!(Span::make_abs(start, end_other_tz).is_err()); + + let later = date_at_midnight(nd(2026, 4, 30), Tz::UTC); + assert!(Span::make_abs(later, start).is_err()); + } + + #[test] + fn make_date_creates_midnight_to_midnight() { + let span = Span::make_date(d(2026, 4, 15), Tz::UTC); + assert_eq!(span.start().date_naive(), nd(2026, 4, 15)); + assert_eq!(span.end().date_naive(), nd(2026, 4, 16)); + assert_eq!(span.mode(), SpanMode::Abs); + assert!(span.aligns_to_dates()); + } + + #[test] + fn contains_inclusive_start_exclusive_end() { + let span = span("2026-04-01,2026-04-30", Tz::UTC); + assert!(span.contains(span.start())); + assert!(!span.contains(span.end())); + } + + #[test] + fn to_date_span_converts_correctly() { + // Span end is exclusive (May 1), so DateSpan end should be Apr 30 + let ds = span("2026-04-01,2026-05-01", Tz::UTC).to_date_span(); + assert_eq!(ds.start, d(2026, 4, 1)); + assert_eq!(ds.end, d(2026, 4, 30)); + } + + #[test] + fn from_str_parses_mode_keyword() { + assert!(span("today", Tz::UTC).mode().is_rel()); + } + + #[test] + fn from_str_parses_date_range_with_either_separator() { + for text in ["2026-04-01,2026-04-30", "2026-04-01..2026-04-30"] { + let span = span(text, Tz::UTC); + assert_eq!(span.mode(), SpanMode::Abs); + assert!(span.aligns_to_dates()); + assert_eq!(span.num_days(), 29); + } + } + + #[test] + fn num_days_for_month_span() { + assert_eq!(span("2026-04-01,2026-05-01", Tz::UTC).num_days(), 30); + } + + #[test] + fn alignment_predicates() { + let april = span("2026-04-01,2026-05-01", Tz::UTC); + assert!(!april.aligns_to_day()); + assert!(april.aligns_to_month()); + assert!(!april.aligns_to_quarter()); + assert!(!april.aligns_to_week()); + assert!(!april.aligns_to_year()); + + let q2 = span("2026-04-01,2026-07-01", Tz::UTC); + assert!(q2.aligns_to_quarter()); + assert!(!q2.aligns_to_month()); + assert_eq!(q2.quarter(), 2); + + assert!(span("2026-01-01,2027-01-01", Tz::UTC).aligns_to_year()); + // 2026-04-05 is a Sunday + assert!(span("2026-04-05,2026-04-12", Tz::UTC).aligns_to_week()); + assert!(span("2026-04-05", Tz::UTC).aligns_to_day()); + } + + #[test] + fn dst_day_counts_as_one_calendar_day() { + // 2026-03-29 is the 23-hour spring-forward day in London. + let short_day = span("2026-03-29", LONDON); + assert_eq!(short_day.num_days(), 1); + assert!(short_day.aligns_to_day()); + let ds = short_day.to_date_span(); + assert_eq!(ds.start, d(2026, 3, 29)); + assert_eq!(ds.end, d(2026, 3, 29)); + assert_eq!(short_day.dis(), "29-Mar-2026..29-Mar-2026"); + + // 2026-10-25 is the 25-hour autumn fall-back day in London. + let long_day = span("2026-10-25", LONDON); + assert_eq!(long_day.num_days(), 1); + assert!(long_day.aligns_to_day()); + } + + #[test] + fn month_spanning_dst_has_correct_day_count_and_navigation() { + let march = span("2026-03-01,2026-04-01", LONDON); + assert_eq!(march.num_days(), 31); + assert!(march.aligns_to_month()); + assert_eq!(march.dis(), "01-Mar-2026..31-Mar-2026"); + + let february = march.prev(); + assert_eq!(february.start().date_naive(), nd(2026, 2, 1)); + assert_eq!(february.end().date_naive(), nd(2026, 3, 1)); + assert_eq!(february.num_days(), 28); + + let april = march.next(); + assert_eq!(april.start().date_naive(), nd(2026, 4, 1)); + assert_eq!(april.end().date_naive(), nd(2026, 5, 1)); + } + + #[test] + fn midnight_gap_timezone_keeps_span_timezone() { + // Cairo moves the clocks forward at midnight on 2026-04-24, so that midnight is skipped. + let span = span("2026-04-24", CAIRO); + assert_eq!(span.tz(), CAIRO); + assert_eq!(span.start().timezone(), CAIRO); + assert_eq!(span.end().timezone(), CAIRO); + // Start is pushed to the first instant that exists after the gap. + assert_eq!(span.start().date_naive(), nd(2026, 4, 24)); + assert_eq!(span.start().hour(), 1); + assert_eq!(span.num_days(), 1); + } + + #[test] + fn rfc3339_offsets_are_honored() { + // 10:00 UTC is 11:00 in London during BST. + let utc = span("2026-07-01T10:00:00Z,2026-07-01T12:00:00Z", LONDON); + assert_eq!(utc.start().hour(), 11); + assert_eq!(utc.start().naive_utc().hour(), 10); + assert!(!utc.aligns_to_dates()); + + // A local time with no offset is interpreted in the span's timezone. + let local = span("2026-07-01T10:00:00,2026-07-01T12:00:00", LONDON); + assert_eq!(local.start().hour(), 10); + assert_eq!(local.start().naive_utc().hour(), 9); + } + + #[test] + fn to_str_round_trips() { + for (text, tz) in [ + ("today", LONDON), + ("thisMonth", LONDON), + ("2026-03-29", LONDON), + ("2026-03-01,2026-04-01", LONDON), + ("2026-07-01T10:00:00Z,2026-07-03T12:30:00Z", LONDON), + ] { + let original = span(text, tz); + let encoded = original.to_str(); + let parsed = Span::from_str(&encoded, tz) + .unwrap_or_else(|| panic!("{encoded} (from {text}) should re-parse")); + assert_eq!(parsed, original, "round trip of {text} via {encoded}"); + } + } + + #[test] + fn to_time_zone_recomputes_alignment() { + let april = span("2026-04-01,2026-05-01", LONDON); + let ny = april.to_time_zone(Tz::America__New_York); + assert_eq!(ny.tz(), Tz::America__New_York); + // Same instants, but no longer midnight-aligned in New York. + assert_eq!(*ny.start(), *april.start()); + assert!(!ny.aligns_to_dates()); + assert!(!ny.aligns_to_month()); + assert_eq!(ny.mode(), SpanMode::Abs); + } + + #[test] + fn relative_modes_resolve_against_today() { + let today = nd(2026, 4, 15); // a Wednesday + let cases = [ + (SpanMode::Today, nd(2026, 4, 15), nd(2026, 4, 16)), + (SpanMode::Yesterday, nd(2026, 4, 14), nd(2026, 4, 15)), + (SpanMode::ThisWeek, nd(2026, 4, 12), nd(2026, 4, 19)), + (SpanMode::LastWeek, nd(2026, 4, 5), nd(2026, 4, 12)), + (SpanMode::PastWeek, nd(2026, 4, 8), nd(2026, 4, 15)), + (SpanMode::ThisMonth, nd(2026, 4, 1), nd(2026, 5, 1)), + (SpanMode::LastMonth, nd(2026, 3, 1), nd(2026, 4, 1)), + (SpanMode::PastMonth, nd(2026, 3, 18), nd(2026, 4, 15)), + (SpanMode::ThisQuarter, nd(2026, 4, 1), nd(2026, 7, 1)), + (SpanMode::LastQuarter, nd(2026, 1, 1), nd(2026, 4, 1)), + (SpanMode::ThisYear, nd(2026, 1, 1), nd(2027, 1, 1)), + (SpanMode::LastYear, nd(2025, 1, 1), nd(2026, 1, 1)), + ]; + for (mode, start, end) in cases { + let span = Span::do_make_rel(mode, today, LONDON); + assert_eq!(span.start().date_naive(), start, "{} start", mode.dis()); + assert_eq!(span.end().date_naive(), end, "{} end", mode.dis()); + assert_eq!(span.mode(), mode); + } + } + + #[test] + fn each_day_covers_every_calendar_day_across_dst() { + let mut days = 0; + span("2026-03-01,2026-04-01", LONDON).each_day(|_, _| days += 1); + assert_eq!(days, 31); + } + + #[test] + fn non_aligned_span_uses_both_local_dates() { + let span = span("2026-07-01T10:00:00Z,2026-07-03T12:30:00Z", Tz::UTC); + let ds = span.to_date_span(); + assert_eq!(ds.start, d(2026, 7, 1)); + assert_eq!(ds.end, d(2026, 7, 3)); + assert_eq!(span.dis(), "01-Jul-2026 10:00..03-Jul-2026 12:30"); + } + + #[test] + fn prev_and_next_of_relative_modes_stay_relative() { + assert_eq!( + Span::make_rel(SpanMode::Today, LONDON).prev().mode(), + SpanMode::Yesterday + ); + assert_eq!( + Span::make_rel(SpanMode::LastMonth, LONDON).next().mode(), + SpanMode::ThisMonth + ); + } + + const ALL_MODES: [SpanMode; 15] = [ + SpanMode::Abs, + SpanMode::Today, + SpanMode::Yesterday, + SpanMode::ThisWeek, + SpanMode::LastWeek, + SpanMode::PastWeek, + SpanMode::ThisMonth, + SpanMode::LastMonth, + SpanMode::PastMonth, + SpanMode::ThisQuarter, + SpanMode::LastQuarter, + SpanMode::PastQuarter, + SpanMode::ThisYear, + SpanMode::LastYear, + SpanMode::PastYear, + ]; + + fn dates(span: &Span) -> (NaiveDate, NaiveDate) { + (span.start().date_naive(), span.end().date_naive()) + } + + #[test] + fn calendar_helpers_saturate_and_roll_over() { + assert_eq!(add_days(NaiveDate::MAX, 1), NaiveDate::MAX); + assert_eq!(sub_days(NaiveDate::MIN, 1), NaiveDate::MIN); + assert_eq!(first_of_month(nd(2026, 4, 15)), nd(2026, 4, 1)); + assert_eq!(first_of_next_month(nd(2026, 12, 15)), nd(2027, 1, 1)); + assert_eq!(first_of_next_month(nd(2026, 4, 15)), nd(2026, 5, 1)); + assert_eq!(first_of_quarter(nd(2026, 11, 10)), nd(2026, 10, 1)); + assert_eq!(first_of_next_quarter(nd(2026, 11, 10)), nd(2027, 1, 1)); + assert_eq!(first_of_next_quarter(nd(2026, 5, 10)), nd(2026, 7, 1)); + assert_eq!(first_of_year(2026), nd(2026, 1, 1)); + } + + #[test] + fn start_of_week_is_sunday() { + assert_eq!(start_of_week(nd(2026, 4, 12)), nd(2026, 4, 12)); // Sunday + assert_eq!(start_of_week(nd(2026, 4, 18)), nd(2026, 4, 12)); // Saturday + } + + #[test] + fn span_mode_helpers() { + for mode in ALL_MODES { + assert_eq!(SpanMode::from_str(mode.dis()), Some(mode)); + assert_eq!(mode.is_abs(), mode == SpanMode::Abs); + assert_eq!(mode.is_rel(), mode != SpanMode::Abs); + } + assert_eq!(SpanMode::from_str("bogus"), None); + + assert_eq!(SpanMode::Abs.period(), SpanModePeriod::Abs); + assert_eq!(SpanMode::Yesterday.period(), SpanModePeriod::Day); + assert_eq!(SpanMode::PastWeek.period(), SpanModePeriod::Week); + assert_eq!(SpanMode::LastMonth.period(), SpanModePeriod::Month); + assert_eq!(SpanMode::PastQuarter.period(), SpanModePeriod::Quarter); + assert_eq!(SpanMode::ThisYear.period(), SpanModePeriod::Year); + } + + #[test] + fn do_make_rel_remaining_modes_and_rollovers() { + let today = nd(2026, 4, 15); + let past_quarter = Span::do_make_rel(SpanMode::PastQuarter, today, Tz::UTC); + assert_eq!(dates(&past_quarter), (nd(2026, 1, 15), nd(2026, 4, 15))); + let past_year = Span::do_make_rel(SpanMode::PastYear, today, Tz::UTC); + assert_eq!(dates(&past_year), (nd(2025, 4, 15), nd(2026, 4, 15))); + let abs = Span::do_make_rel(SpanMode::Abs, today, Tz::UTC); + assert_eq!(dates(&abs), (nd(2026, 4, 15), nd(2026, 4, 16))); + + let last_quarter = Span::do_make_rel(SpanMode::LastQuarter, nd(2026, 1, 10), Tz::UTC); + assert_eq!(dates(&last_quarter), (nd(2025, 10, 1), nd(2026, 1, 1))); + let this_quarter = Span::do_make_rel(SpanMode::ThisQuarter, nd(2026, 11, 10), Tz::UTC); + assert_eq!(dates(&this_quarter), (nd(2026, 10, 1), nd(2027, 1, 1))); + let this_month = Span::do_make_rel(SpanMode::ThisMonth, nd(2026, 12, 10), Tz::UTC); + assert_eq!(dates(&this_month), (nd(2026, 12, 1), nd(2027, 1, 1))); + let last_month = Span::do_make_rel(SpanMode::LastMonth, nd(2026, 1, 10), Tz::UTC); + assert_eq!(dates(&last_month), (nd(2025, 12, 1), nd(2026, 1, 1))); + } + + #[test] + fn today_and_fresh() { + let today = Span::today(Tz::UTC); + assert_eq!(today.mode(), SpanMode::Today); + assert_eq!(today.num_days(), 1); + assert_eq!(today.fresh().mode(), SpanMode::Today); + + let abs = span("2026-04-01,2026-05-01", Tz::UTC); + assert_eq!(abs.fresh(), abs); + } + + #[test] + fn equality_of_relative_spans_is_by_mode() { + let april = Span::do_make_rel(SpanMode::ThisMonth, nd(2026, 4, 15), LONDON); + let may = Span::do_make_rel(SpanMode::ThisMonth, nd(2026, 5, 15), Tz::UTC); + assert_eq!(april, may); + assert_ne!( + april, + Span::do_make_rel(SpanMode::LastMonth, nd(2026, 5, 15), LONDON) + ); + + // An absolute span with the same dates as a relative one is still different. + let abs = span("2026-04-01,2026-05-01", LONDON); + assert_eq!(dates(&abs), dates(&april)); + assert_ne!(abs, april); + assert_ne!(abs, span("2026-04-01,2026-05-02", LONDON)); + } + + #[test] + fn start_and_end_dates() { + let april = span("2026-04-01,2026-05-01", Tz::UTC); + assert_eq!(april.start_date(), d(2026, 4, 1)); + assert_eq!(april.end_date(), d(2026, 5, 1)); + } + + #[test] + fn to_time_zone_same_zone_is_identity() { + let april = span("2026-04-01,2026-05-01", LONDON); + assert_eq!(april.to_time_zone(LONDON), april); + } + + #[test] + fn to_date_span_period_detection() { + let week = span("2026-04-05,2026-04-12", Tz::UTC).to_date_span(); + assert!(week.is_week()); + assert_eq!((week.start, week.end), (d(2026, 4, 5), d(2026, 4, 11))); + + let month = span("2026-04-01,2026-05-01", Tz::UTC).to_date_span(); + assert!(month.is_month()); + + let year = span("2026-01-01,2027-01-01", Tz::UTC).to_date_span(); + assert!(year.is_year()); + assert_eq!((year.start, year.end), (d(2026, 1, 1), d(2026, 12, 31))); + + let range = span("2026-04-01,2026-04-10", Tz::UTC).to_date_span(); + assert!(range.is_range()); + assert_eq!((range.start, range.end), (d(2026, 4, 1), d(2026, 4, 9))); + + let quarter = span("2026-04-01,2026-07-01", Tz::UTC).to_date_span(); + assert!(quarter.is_quarter()); + assert_eq!( + (quarter.start, quarter.end), + (d(2026, 4, 1), d(2026, 6, 30)) + ); + } + + #[test] + fn from_span_for_date_span() { + let april = span("2026-04-01,2026-05-01", Tz::UTC); + assert_eq!(DateSpan::from(&april), april.to_date_span()); + } + + #[test] + fn quarter_numbers() { + assert_eq!(span("2026-01-01,2026-02-01", Tz::UTC).quarter(), 1); + assert_eq!(span("2026-05-01,2026-06-01", Tz::UTC).quarter(), 2); + assert_eq!(span("2026-08-01,2026-09-01", Tz::UTC).quarter(), 3); + assert_eq!(span("2026-11-01,2026-12-01", Tz::UTC).quarter(), 4); + } + + #[test] + fn alignment_negative_cases() { + let may = span("2026-05-01,2026-06-01", Tz::UTC); + assert!(may.aligns_to_month()); + assert!(!may.aligns_to_quarter()); + + assert!(span("2026-10-01,2027-01-01", Tz::UTC).aligns_to_quarter()); + assert!(!span("2026-04-02,2026-07-01", Tz::UTC).aligns_to_quarter()); + assert!(!span("2026-04-02,2026-05-01", Tz::UTC).aligns_to_month()); + assert!(!span("2026-01-01,2026-12-01", Tz::UTC).aligns_to_year()); + // 2026-04-06 is a Monday + assert!(!span("2026-04-06,2026-04-13", Tz::UTC).aligns_to_week()); + + let timed = span("2026-07-01T10:00:00Z,2026-07-01T12:00:00Z", Tz::UTC); + assert!(!timed.aligns_to_day()); + assert!(!timed.aligns_to_week()); + assert!(!timed.aligns_to_month()); + assert!(!timed.aligns_to_quarter()); + assert!(!timed.aligns_to_year()); + } + + #[test] + fn prev_next_of_relative_modes() { + let prev_cases = [ + (SpanMode::Today, SpanMode::Yesterday), + (SpanMode::ThisWeek, SpanMode::LastWeek), + (SpanMode::ThisMonth, SpanMode::LastMonth), + (SpanMode::ThisQuarter, SpanMode::LastQuarter), + (SpanMode::ThisYear, SpanMode::LastYear), + ]; + for (mode, expected) in prev_cases { + assert_eq!(Span::make_rel(mode, Tz::UTC).prev().mode(), expected); + assert_eq!(Span::make_rel(expected, Tz::UTC).next().mode(), mode); + } + } + + #[test] + fn prev_next_of_aligned_absolute_spans() { + let day = span("2026-04-15", Tz::UTC); + assert_eq!(dates(&day.prev()), (nd(2026, 4, 14), nd(2026, 4, 15))); + assert_eq!(dates(&day.next()), (nd(2026, 4, 16), nd(2026, 4, 17))); + + let week = span("2026-04-05,2026-04-12", Tz::UTC); + assert_eq!(dates(&week.prev()), (nd(2026, 3, 29), nd(2026, 4, 5))); + assert_eq!(dates(&week.next()), (nd(2026, 4, 12), nd(2026, 4, 19))); + + let april = span("2026-04-01,2026-05-01", Tz::UTC); + assert_eq!(dates(&april.prev()), (nd(2026, 3, 1), nd(2026, 4, 1))); + assert_eq!(dates(&april.next()), (nd(2026, 5, 1), nd(2026, 6, 1))); + + let q2 = span("2026-04-01,2026-07-01", Tz::UTC); + assert_eq!(dates(&q2.prev()), (nd(2026, 1, 1), nd(2026, 4, 1))); + assert_eq!(dates(&q2.next()), (nd(2026, 7, 1), nd(2026, 10, 1))); + + let year = span("2026-01-01,2027-01-01", Tz::UTC); + assert_eq!(dates(&year.prev()), (nd(2025, 1, 1), nd(2026, 1, 1))); + assert_eq!(dates(&year.next()), (nd(2027, 1, 1), nd(2028, 1, 1))); + } + + #[test] + fn prev_next_of_generic_ranges() { + let range = span("2026-04-01,2026-04-11", Tz::UTC); + assert_eq!(dates(&range.prev()), (nd(2026, 3, 22), nd(2026, 4, 1))); + assert_eq!(dates(&range.next()), (nd(2026, 4, 11), nd(2026, 4, 21))); + + let timed = span("2026-07-01T10:00:00Z,2026-07-01T12:00:00Z", Tz::UTC); + let (prev, next) = (timed.prev(), timed.next()); + assert_eq!((prev.start().hour(), prev.end().hour()), (8, 10)); + assert_eq!((next.start().hour(), next.end().hour()), (12, 14)); + assert_eq!(prev.mode(), SpanMode::Abs); + } + + #[test] + fn to_str_forms() { + assert_eq!(span("thisWeek", Tz::UTC).to_str(), "thisWeek"); + assert_eq!(span("2026-04-15", Tz::UTC).to_str(), "2026-04-15"); + assert_eq!( + span("2026-04-01,2026-05-01", Tz::UTC).to_str(), + "2026-04-01,2026-05-01" + ); + let timed = span("2026-07-01T10:00:00Z,2026-07-01T12:00:00Z", Tz::UTC).to_str(); + assert!( + timed.contains("T10:00:00") && timed.contains("T12:00:00"), + "{timed}" + ); + } + + #[test] + fn from_str_rejects_invalid_input() { + for text in [ + "garbage", + "abs", + "", + "2026-04-01,garbage", + "garbage,2026-04-01", + "2026-05-01,2026-04-01", + "2026-13-01", + ] { + assert!(Span::from_str(text, Tz::UTC).is_none(), "{text}"); + } + } + + #[test] + fn from_str_accepts_flexible_timestamps() { + let spaced = span(" 2026-04-01 , 2026-05-01 ", Tz::UTC); + assert!(spaced.aligns_to_month()); + + let minutes = span("2026-07-01T10:00,2026-07-01T12:30", LONDON); + assert_eq!(minutes.start().hour(), 10); + assert_eq!(minutes.end().minute(), 30); + + let fractional = span("2026-07-01T10:00:00.500,2026-07-01T11:00:00.500", LONDON); + assert_eq!(fractional.start().hour(), 10); + + let offset = span( + "2026-07-01T10:00:00+02:00,2026-07-01T12:00:00+02:00", + Tz::UTC, + ); + assert_eq!(offset.start().hour(), 8); + + let mixed = span("2026-07-01,2026-07-01T12:00:00Z", Tz::UTC); + assert!(!mixed.aligns_to_dates()); + } + + #[test] + fn local_time_resolution_across_dst() { + // 01:30 happens twice in London on 2026-10-25; the earlier (BST) instant is used. + let ambiguous = local_to_date_time(nd(2026, 10, 25).and_hms_opt(1, 30, 0).unwrap(), LONDON); + assert_eq!(ambiguous.naive_utc().hour(), 0); + assert_eq!(ambiguous.naive_utc().minute(), 30); + + // 01:30 does not exist in London on 2026-03-29; the first instant after the gap is used. + let gap = local_to_date_time(nd(2026, 3, 29).and_hms_opt(1, 30, 0).unwrap(), LONDON); + assert_eq!((gap.hour(), gap.minute()), (2, 0)); + assert_eq!(gap.second(), 0); + + // Seconds are dropped when resolving a gap. + let gap = local_to_date_time(nd(2026, 3, 29).and_hms_opt(1, 30, 30).unwrap(), LONDON); + assert_eq!((gap.hour(), gap.minute(), gap.second()), (2, 0, 0)); + } + + #[test] + fn empty_midnight_span_round_trips_as_empty() { + let empty = span("2026-04-01,2026-04-01", Tz::UTC); + assert_eq!(empty.num_days(), 0); + let encoded = empty.to_str(); + assert_eq!(encoded, "2026-04-01,2026-04-01"); + assert_eq!(span(&encoded, Tz::UTC), empty); + } + + #[test] + fn quarter_aligned_span_converts_to_quarter_date_span() { + let q4 = span("2026-10-01,2027-01-01", Tz::UTC).to_date_span(); + assert!(q4.is_quarter()); + assert_eq!((q4.start, q4.end), (d(2026, 10, 1), d(2026, 12, 31))); + + let this_quarter = Span::make_rel(SpanMode::ThisQuarter, Tz::UTC).to_date_span(); + assert!(this_quarter.is_quarter()); + } + + #[test] + fn caller_date_resolves_every_relative_mode_without_losing_mode_or_timezone() { + for mode in ALL_MODES.into_iter().filter(SpanMode::is_rel) { + let actual = Span::make_rel_on(mode, d(2028, 2, 29), LONDON); + let expected = Span::do_make_rel(mode, nd(2028, 2, 29), LONDON); + assert_eq!(actual.start(), expected.start()); + assert_eq!(actual.end(), expected.end()); + assert_eq!(actual.mode(), mode); + assert_eq!(actual.tz(), LONDON); + } + let today = Span::make_rel_on(SpanMode::Today, d(2028, 2, 29), LONDON); + assert_eq!(dates(&today), (nd(2028, 2, 29), nd(2028, 3, 1))); + + let abs = Span::make_rel_on(SpanMode::Abs, d(2028, 2, 29), LONDON); + assert_eq!(abs.mode(), SpanMode::Abs); + assert_eq!(dates(&abs), (nd(2028, 2, 29), nd(2028, 3, 1))); + } + + #[test] + fn caller_date_refreshes_bounds_despite_mode_based_equality() { + let april = Span::make_rel_on(SpanMode::ThisMonth, d(2026, 4, 15), LONDON); + let may = april.fresh_on(d(2026, 5, 15)); + assert_eq!(may.mode(), SpanMode::ThisMonth); + assert_eq!(may.tz(), LONDON); + assert_eq!(dates(&may), (nd(2026, 5, 1), nd(2026, 6, 1))); + assert_eq!(dates(&april), (nd(2026, 4, 1), nd(2026, 5, 1))); + let absolute = span("2026-04-01,2026-05-01", LONDON); + assert_eq!(absolute.fresh_on(d(2030, 1, 1)), absolute); + } + + #[test] + fn caller_date_parsing_resolves_keywords_and_preserves_absolute_input() { + for mode in ALL_MODES.into_iter().filter(SpanMode::is_rel) { + let parsed = Span::from_str_on(mode.dis(), d(2026, 3, 29), LONDON).unwrap(); + let expected = Span::make_rel_on(mode, d(2026, 3, 29), LONDON); + assert_eq!(parsed.start(), expected.start()); + assert_eq!(parsed.end(), expected.end()); + assert_eq!(parsed.mode(), mode); + assert_eq!(parsed.tz(), LONDON); + } + for input in [ + "2026-04-01", + "2026-04-01,2026-05-01", + "2026-04-01T10:00:00Z,2026-04-02T10:00:00Z", + ] { + let parsed = Span::from_str_on(input, d(2030, 1, 1), LONDON).unwrap(); + assert_eq!(parsed, span(input, LONDON)); + } + assert!(Span::from_str_on("invalid", d(2030, 1, 1), LONDON).is_none()); + } + + #[test] + fn empty_spans_have_no_date_conversion_or_iteration() { + for input in [ + "2026-04-01,2026-04-01", + "2026-04-01T12:30:00Z,2026-04-01T12:30:00Z", + ] { + let empty = span(input, LONDON); + assert!(empty.is_empty()); + assert!(empty.try_to_date_span().is_none()); + empty.each_day(|_, _| panic!("empty span must not visit a date")); + let utc = empty.to_time_zone(Tz::UTC); + assert!(utc.is_empty()); + assert!(utc.try_to_date_span().is_none()); + } + } + + #[test] + fn empty_span_dis_shows_instants_not_a_day() { + let empty = span("2026-04-01,2026-04-01", LONDON); + assert_eq!(empty.dis(), "01-Apr-2026 00:00..01-Apr-2026 00:00"); + assert_eq!(span("2026-04-01", LONDON).dis(), "01-Apr-2026..01-Apr-2026"); + } + + #[test] + fn nonempty_conversion_and_iteration_preserve_dst_calendar_days() { + let range = span("2026-03-28,2026-03-31", LONDON); + assert!(!range.is_empty()); + assert_eq!(range.try_to_date_span(), Some(range.to_date_span())); + let mut visited = Vec::new(); + range.each_day(|date, index| visited.push((date, index))); + assert_eq!( + visited, + vec![ + (d(2026, 3, 28), 0), + (d(2026, 3, 29), 1), + (d(2026, 3, 30), 2) + ] + ); + let short = span("2026-03-29T10:00:00Z,2026-03-29T10:00:01Z", LONDON); + assert!(!short.is_empty()); + assert!(short.try_to_date_span().is_some()); + let mut count = 0; + short.each_day(|_, _| count += 1); + assert_eq!(count, 1); + } +}