| 1 |
//! Implements `DateRule` - an iterator yielding evenly spaced dates. |
| 2 |
use std::iter::Iterator; |
| 3 |
|
| 4 |
use super::delta::with_day; |
| 5 |
use super::relative_duration::RelativeDuration; |
| 6 |
use chrono::{Date, DateTime, Datelike, NaiveDate, NaiveDateTime, TimeZone}; |
| 7 |
|
| 8 |
/// DateRule is an iterator for yielding evenly spaced dates |
| 9 |
/// according to a given RelativeDuration. It avoids some |
| 10 |
/// of the pitfalls that naive usage of RelativeDuration |
| 11 |
/// can incur. |
| 12 |
#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 13 |
pub struct DateRule<D: Datelike> { |
| 14 |
freq: RelativeDuration, |
| 15 |
start: D, |
| 16 |
end: Option<D>, |
| 17 |
count: Option<usize>, |
| 18 |
rolling_day: Option<u32>, |
| 19 |
_current_count: usize, |
| 20 |
} |
| 21 |
|
| 22 |
impl<D> DateRule<D> |
| 23 |
where |
| 24 |
D: Datelike + Copy, |
| 25 |
{ |
| 26 |
/// Creates a new `DateRule` from an initial date and relative duration. |
| 27 |
#[inline] |
| 28 |
pub fn new(start: D, freq: RelativeDuration) -> Self { |
| 29 |
Self { |
| 30 |
freq, |
| 31 |
start, |
| 32 |
end: None, |
| 33 |
count: None, |
| 34 |
rolling_day: None, |
| 35 |
_current_count: 0, |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
/// Creates a `DateRule` yielding dates one second appart. |
| 40 |
#[inline] |
| 41 |
pub fn secondly(from: D) -> Self { |
| 42 |
Self::new(from, RelativeDuration::seconds(1)) |
| 43 |
} |
| 44 |
|
| 45 |
/// Creates a `DateRule` yielding dates one minute appart. |
| 46 |
#[inline] |
| 47 |
pub fn minutely(from: D) -> Self { |
| 48 |
Self::new(from, RelativeDuration::minutes(1)) |
| 49 |
} |
| 50 |
|
| 51 |
/// Creates a `DateRule` yielding dates one hour appart. |
| 52 |
#[inline] |
| 53 |
pub fn hourly(from: D) -> Self { |
| 54 |
Self::new(from, RelativeDuration::hours(1)) |
| 55 |
} |
| 56 |
|
| 57 |
/// Creates a `DateRule` yielding dates one day appart. |
| 58 |
#[inline] |
| 59 |
pub fn daily(from: D) -> Self { |
| 60 |
Self::new(from, RelativeDuration::days(1)) |
| 61 |
} |
| 62 |
|
| 63 |
/// Creates a `DateRule` yielding dates one week appart. |
| 64 |
#[inline] |
| 65 |
pub fn weekly(from: D) -> Self { |
| 66 |
Self::new(from, RelativeDuration::weeks(1)) |
| 67 |
} |
| 68 |
|
| 69 |
/// Creates a `DateRule` yielding dates one month appart. |
| 70 |
/// Ambiguous month-ends are shifted backwards as necessary. |
| 71 |
#[inline] |
| 72 |
pub fn monthly(from: D) -> Self { |
| 73 |
Self::new(from, RelativeDuration::months(1)) |
| 74 |
} |
| 75 |
|
| 76 |
/// Creates a `DateRule` yielding dates one year appart. |
| 77 |
/// Ambiguous month-ends are shifted backwards as necessary. |
| 78 |
#[inline] |
| 79 |
pub fn yearly(from: D) -> Self { |
| 80 |
Self::new(from, RelativeDuration::years(1)) |
| 81 |
} |
| 82 |
|
| 83 |
/// Limits the `DateRule` to a given number of dates. |
| 84 |
pub fn with_count(&self, number: usize) -> Self { |
| 85 |
Self { |
| 86 |
freq: self.freq, |
| 87 |
start: self.start, |
| 88 |
end: None, |
| 89 |
count: Some(number), |
| 90 |
rolling_day: self.rolling_day, |
| 91 |
_current_count: 0, |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
/// Limits the `DateRule` to an extremal date (exclusive). |
| 96 |
/// |
| 97 |
/// If using a `RelativeDuration` which shifts dates backwards, the `end` date should |
| 98 |
/// be before the current date. |
| 99 |
/// |
| 100 |
/// WARNING: a forward-shifting duration with an end-date before the initial date |
| 101 |
/// will result in an iterator which does not terminate. |
| 102 |
pub fn with_end(&self, end: D) -> Self { |
| 103 |
Self { |
| 104 |
freq: self.freq, |
| 105 |
start: self.start, |
| 106 |
end: Some(end), |
| 107 |
count: None, |
| 108 |
rolling_day: self.rolling_day, |
| 109 |
_current_count: 0, |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
/// Ensure the `DateRule` yields new dates which are *always* fall on the |
| 114 |
/// given rolling day (modulo backwards shifting for month ends). Returns |
| 115 |
/// Err if the rolling day is not in the range 1-31. |
| 116 |
/// |
| 117 |
/// For example: |
| 118 |
/// ```rust |
| 119 |
/// # use chrono::NaiveDate; |
| 120 |
/// # use chronoutil::DateRule; |
| 121 |
/// let start = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap(); |
| 122 |
/// let mut rule = DateRule::monthly(start).with_rolling_day(31).unwrap(); |
| 123 |
/// |
| 124 |
/// assert_eq!(rule.next().unwrap(), NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()); |
| 125 |
/// assert_eq!(rule.next().unwrap(), NaiveDate::from_ymd_opt(2020, 3, 31).unwrap()); |
| 126 |
/// assert_eq!(rule.next().unwrap(), NaiveDate::from_ymd_opt(2020, 4, 30).unwrap()); |
| 127 |
/// assert_eq!(rule.next().unwrap(), NaiveDate::from_ymd_opt(2020, 5, 31).unwrap()); |
| 128 |
/// // etc. |
| 129 |
/// ``` |
| 130 |
/// |
| 131 |
/// It produces values equivalent to |
| 132 |
/// ```ignore |
| 133 |
/// rule.map(|d| with_day(d, rolling_day).unwrap()) |
| 134 |
/// ``` |
| 135 |
pub fn with_rolling_day(&self, rolling_day: u32) -> Result<Self, String> { |
| 136 |
if rolling_day == 0 || rolling_day > 31 { |
| 137 |
Err(format!("Rolling day {} not in range 1-31", rolling_day)) |
| 138 |
} else { |
| 139 |
Ok(Self { |
| 140 |
freq: self.freq, |
| 141 |
start: self.start, |
| 142 |
end: self.end, |
| 143 |
count: self.count, |
| 144 |
rolling_day: Some(rolling_day), |
| 145 |
_current_count: self._current_count, |
| 146 |
}) |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// The following is just copy-pasta, mostly because we |
| 152 |
// can't impl<T> Add<RelativeDuration> for T with T: Datelike |
| 153 |
impl Iterator for DateRule<NaiveDate> { |
| 154 |
type Item = NaiveDate; |
| 155 |
|
| 156 |
fn next(&mut self) -> Option<Self::Item> { |
| 157 |
if self.count.is_some() && self._current_count >= self.count.unwrap() { |
| 158 |
return None; |
| 159 |
} |
| 160 |
|
| 161 |
let mut current_date = self.start + self.freq * self._current_count as i32; |
| 162 |
if let Some(rolling_day) = self.rolling_day { |
| 163 |
current_date = with_day(current_date, rolling_day).unwrap(); |
| 164 |
} |
| 165 |
|
| 166 |
if let Some(end) = &self.end { |
| 167 |
if (*end >= self.start && current_date >= *end) |
| 168 |
|| (*end < self.start && current_date <= *end) |
| 169 |
{ |
| 170 |
return None; |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
self._current_count += 1; |
| 175 |
Some(current_date) |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
impl Iterator for DateRule<NaiveDateTime> { |
| 180 |
type Item = NaiveDateTime; |
| 181 |
|
| 182 |
fn next(&mut self) -> Option<Self::Item> { |
| 183 |
if self.count.is_some() && self._current_count >= self.count.unwrap() { |
| 184 |
return None; |
| 185 |
} |
| 186 |
|
| 187 |
let mut current_date = self.start + self.freq * self._current_count as i32; |
| 188 |
if let Some(rolling_day) = self.rolling_day { |
| 189 |
current_date = with_day(current_date, rolling_day).unwrap(); |
| 190 |
} |
| 191 |
|
| 192 |
if let Some(end) = &self.end { |
| 193 |
if (*end >= self.start && current_date >= *end) |
| 194 |
|| (*end < self.start && current_date <= *end) |
| 195 |
{ |
| 196 |
return None; |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
self._current_count += 1; |
| 201 |
Some(current_date) |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
impl<Tz> Iterator for DateRule<Date<Tz>> |
| 206 |
where |
| 207 |
Tz: TimeZone, |
| 208 |
{ |
| 209 |
type Item = Date<Tz>; |
| 210 |
|
| 211 |
fn next(&mut self) -> Option<Self::Item> { |
| 212 |
if self.count.is_some() && self._current_count >= self.count.unwrap() { |
| 213 |
return None; |
| 214 |
} |
| 215 |
|
| 216 |
let mut current_date = self.start.clone() + self.freq * self._current_count as i32; |
| 217 |
if let Some(rolling_day) = self.rolling_day { |
| 218 |
current_date = with_day(current_date, rolling_day).unwrap(); |
| 219 |
} |
| 220 |
|
| 221 |
if let Some(end) = &self.end { |
| 222 |
if (*end >= self.start && current_date >= *end) |
| 223 |
|| (*end < self.start && current_date <= *end) |
| 224 |
{ |
| 225 |
return None; |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
self._current_count += 1; |
| 230 |
Some(current_date) |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
impl<Tz> Iterator for DateRule<DateTime<Tz>> |
| 235 |
where |
| 236 |
Tz: TimeZone, |
| 237 |
{ |
| 238 |
type Item = DateTime<Tz>; |
| 239 |
|
| 240 |
fn next(&mut self) -> Option<Self::Item> { |
| 241 |
if self.count.is_some() && self._current_count >= self.count.unwrap() { |
| 242 |
return None; |
| 243 |
} |
| 244 |
|
| 245 |
let mut current_date = self.start.clone() + self.freq * self._current_count as i32; |
| 246 |
if let Some(rolling_day) = self.rolling_day { |
| 247 |
current_date = with_day(current_date, rolling_day).unwrap(); |
| 248 |
} |
| 249 |
|
| 250 |
if let Some(end) = &self.end { |
| 251 |
if (*end >= self.start && current_date >= *end) |
| 252 |
|| (*end < self.start && current_date <= *end) |
| 253 |
{ |
| 254 |
return None; |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
self._current_count += 1; |
| 259 |
Some(current_date) |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
#[cfg(test)] |
| 264 |
mod tests { |
| 265 |
use super::*; |
| 266 |
|
| 267 |
use chrono::{Duration, NaiveDateTime, NaiveTime}; |
| 268 |
|
| 269 |
#[test] |
| 270 |
fn test_rrule_with_date() { |
| 271 |
let start = NaiveDate::from_ymd_opt(2020, 1, 1).unwrap(); |
| 272 |
|
| 273 |
// Seconds, hours, minutes etc |
| 274 |
for (i, date) in DateRule::secondly(start) |
| 275 |
.with_count(24 * 60 * 60 * 2) |
| 276 |
.enumerate() |
| 277 |
{ |
| 278 |
if i < 24 * 60 * 60 { |
| 279 |
assert_eq!(date, start, "Expected {} seconds to be on first day", i); |
| 280 |
} else { |
| 281 |
assert_eq!( |
| 282 |
date, |
| 283 |
start + Duration::days(1), |
| 284 |
"Expected {} seconds to be on second day", |
| 285 |
i |
| 286 |
); |
| 287 |
} |
| 288 |
} |
| 289 |
for (i, date) in DateRule::minutely(start) |
| 290 |
.with_count(24 * 60 * 2) |
| 291 |
.enumerate() |
| 292 |
{ |
| 293 |
if i < 24 * 60 { |
| 294 |
assert_eq!(date, start, "Expected {} minutes to be on first day", i); |
| 295 |
} else { |
| 296 |
assert_eq!( |
| 297 |
date, |
| 298 |
start + Duration::days(1), |
| 299 |
"Expected {} minutes to be on second day", |
| 300 |
i |
| 301 |
); |
| 302 |
} |
| 303 |
} |
| 304 |
for (i, date) in DateRule::hourly(start).with_count(24 * 2).enumerate() { |
| 305 |
if i < 24 { |
| 306 |
assert_eq!(date, start, "Expected {} hours to be on first day", i); |
| 307 |
} else { |
| 308 |
assert_eq!( |
| 309 |
date, |
| 310 |
start + Duration::days(1), |
| 311 |
"Expected {} hours to be on second day", |
| 312 |
i |
| 313 |
); |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
// Days, weeks |
| 318 |
let days: Vec<NaiveDate> = DateRule::daily(start).with_count(5).collect(); |
| 319 |
assert_eq!(days[0], start, "DateRule should start at the initial day"); |
| 320 |
assert_eq!( |
| 321 |
days[1], |
| 322 |
start + Duration::days(1), |
| 323 |
"DateRule should increment in days" |
| 324 |
); |
| 325 |
assert_eq!( |
| 326 |
days.len(), |
| 327 |
5, |
| 328 |
"DateRule should finish before the count is up" |
| 329 |
); |
| 330 |
|
| 331 |
let finish = NaiveDate::from_ymd_opt(2020, 1, 29).unwrap(); |
| 332 |
let weeks: Vec<NaiveDate> = DateRule::weekly(start).with_end(finish).collect(); |
| 333 |
assert_eq!(weeks[0], start, "DateRule should start at the initial day"); |
| 334 |
assert_eq!( |
| 335 |
weeks[1], |
| 336 |
start + Duration::days(7), |
| 337 |
"DateRule should increment in weeks" |
| 338 |
); |
| 339 |
assert_eq!( |
| 340 |
weeks.len(), |
| 341 |
4, |
| 342 |
"DateRule should finish before the final day" |
| 343 |
); |
| 344 |
|
| 345 |
// Months, years |
| 346 |
let interesting = NaiveDate::from_ymd_opt(2020, 1, 30).unwrap(); // The day will change each month |
| 347 |
|
| 348 |
let months: Vec<NaiveDate> = DateRule::monthly(interesting).with_count(5).collect(); |
| 349 |
assert_eq!( |
| 350 |
months[0], interesting, |
| 351 |
"DateRule should start at the initial day" |
| 352 |
); |
| 353 |
assert_eq!( |
| 354 |
months[1], |
| 355 |
NaiveDate::from_ymd_opt(2020, 2, 29).unwrap(), |
| 356 |
"DateRule should handle Feb" |
| 357 |
); |
| 358 |
assert_eq!( |
| 359 |
months[2], |
| 360 |
NaiveDate::from_ymd_opt(2020, 3, 30).unwrap(), |
| 361 |
"DateRule should not loose days" |
| 362 |
); |
| 363 |
assert_eq!( |
| 364 |
months.len(), |
| 365 |
5, |
| 366 |
"DateRule should finish before the count is up" |
| 367 |
); |
| 368 |
|
| 369 |
let years: Vec<NaiveDate> = DateRule::yearly(interesting).with_count(3).collect(); |
| 370 |
assert_eq!( |
| 371 |
years[0], interesting, |
| 372 |
"DateRule should start at the initial day" |
| 373 |
); |
| 374 |
assert_eq!( |
| 375 |
years[1], |
| 376 |
NaiveDate::from_ymd_opt(2021, 1, 30).unwrap(), |
| 377 |
"DateRule should increment in years" |
| 378 |
); |
| 379 |
assert_eq!( |
| 380 |
years.len(), |
| 381 |
3, |
| 382 |
"DateRule should finish before the count is up" |
| 383 |
); |
| 384 |
} |
| 385 |
|
| 386 |
#[test] |
| 387 |
fn test_rrule_with_datetime() { |
| 388 |
// Seconds |
| 389 |
let o_clock = NaiveTime::from_hms_opt(1, 2, 3).unwrap(); |
| 390 |
let day = NaiveDate::from_ymd_opt(2020, 1, 1).unwrap(); |
| 391 |
let start = NaiveDateTime::new(day, o_clock); |
| 392 |
|
| 393 |
let seconds_passed = 60 * 60 + 2 * 60 + 3; |
| 394 |
|
| 395 |
for (i, date) in DateRule::secondly(start) |
| 396 |
.with_count(24 * 60 * 60 * 2) |
| 397 |
.enumerate() |
| 398 |
{ |
| 399 |
if i > 0 { |
| 400 |
assert!(date > start, "Time should increase"); |
| 401 |
} |
| 402 |
|
| 403 |
if i < 24 * 60 * 60 - seconds_passed { |
| 404 |
assert_eq!( |
| 405 |
date.date(), |
| 406 |
day, |
| 407 |
"Expected {} seconds to be on first day", |
| 408 |
date |
| 409 |
); |
| 410 |
} else if i < 2 * 24 * 60 * 60 - seconds_passed { |
| 411 |
assert_eq!( |
| 412 |
date.date(), |
| 413 |
day + Duration::days(1), |
| 414 |
"Expected {} to be on second day", |
| 415 |
date |
| 416 |
); |
| 417 |
} else { |
| 418 |
assert_eq!( |
| 419 |
date.date(), |
| 420 |
day + Duration::days(2), |
| 421 |
"Expected {} to be on third day", |
| 422 |
date |
| 423 |
); |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
// Months |
| 428 |
let interesting = NaiveDate::from_ymd_opt(2020, 1, 30).unwrap(); // The day will change each month |
| 429 |
let istart = NaiveDateTime::new(interesting, o_clock); |
| 430 |
|
| 431 |
let months: Vec<NaiveDateTime> = DateRule::monthly(istart).with_count(5).collect(); |
| 432 |
assert_eq!( |
| 433 |
months[0], istart, |
| 434 |
"DateRule should start at the initial day" |
| 435 |
); |
| 436 |
assert_eq!( |
| 437 |
months[1].date(), |
| 438 |
NaiveDate::from_ymd_opt(2020, 2, 29).unwrap(), |
| 439 |
"DateRule should handle Feb" |
| 440 |
); |
| 441 |
assert_eq!(months[1].time(), o_clock, "Time should remain the same"); |
| 442 |
assert_eq!( |
| 443 |
months[2].date(), |
| 444 |
NaiveDate::from_ymd_opt(2020, 3, 30).unwrap(), |
| 445 |
"DateRule should not loose days" |
| 446 |
); |
| 447 |
assert_eq!(months[2].time(), o_clock, "Time should remain the same"); |
| 448 |
} |
| 449 |
|
| 450 |
#[test] |
| 451 |
fn test_rrule_edge_cases() { |
| 452 |
let start = NaiveDate::from_ymd_opt(2020, 1, 1).unwrap(); |
| 453 |
|
| 454 |
// Zero count |
| 455 |
let mut dates: Vec<NaiveDate> = DateRule::daily(start).with_count(0).collect(); |
| 456 |
assert_eq!(dates.len(), 0); |
| 457 |
|
| 458 |
// End equals start |
| 459 |
dates = DateRule::daily(start).with_end(start).collect(); |
| 460 |
assert_eq!(dates.len(), 0); |
| 461 |
|
| 462 |
// End before start |
| 463 |
// TODO: the only way to know to stop is to determine the forward/backwardness of the duration. |
| 464 |
// This is a concept which is ill formed (e.g. +1 month - 30 days) so needs thought. |
| 465 |
// dates = DateRule::daily(start).with_end(start - Duration::days(1)).collect(); |
| 466 |
// assert_eq!(dates.len(), 0); |
| 467 |
} |
| 468 |
|
| 469 |
#[test] |
| 470 |
fn test_backwards_rrule() { |
| 471 |
let start = NaiveDate::from_ymd_opt(2020, 3, 31).unwrap(); |
| 472 |
let end = NaiveDate::from_ymd_opt(2019, 12, 31).unwrap(); |
| 473 |
let freq = RelativeDuration::months(-1); |
| 474 |
|
| 475 |
let dates1: Vec<NaiveDate> = DateRule::new(start, freq).with_count(3).collect(); |
| 476 |
assert_eq!(dates1.len(), 3); |
| 477 |
assert_eq!(dates1[0], NaiveDate::from_ymd_opt(2020, 3, 31).unwrap()); |
| 478 |
assert_eq!(dates1[1], NaiveDate::from_ymd_opt(2020, 2, 29).unwrap()); |
| 479 |
assert_eq!(dates1[2], NaiveDate::from_ymd_opt(2020, 1, 31).unwrap()); |
| 480 |
|
| 481 |
let dates2: Vec<NaiveDate> = DateRule::new(start, freq).with_end(end).collect(); |
| 482 |
|
| 483 |
assert_eq!(dates1.len(), dates2.len()); |
| 484 |
for k in 0..dates1.len() { |
| 485 |
assert_eq!(dates1[k], dates2[k]); |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
#[test] |
| 490 |
fn test_long_running_rules() { |
| 491 |
// Sanity tests for long-running shifts with various start months |
| 492 |
for month in &[1, 3, 5, 7, 8, 10, 12] { |
| 493 |
let start = NaiveDate::from_ymd_opt(2020, *month as u32, 31).unwrap(); |
| 494 |
let mut rule = DateRule::monthly(start); |
| 495 |
|
| 496 |
for _ in 0..120 { |
| 497 |
let shifted = rule.next().unwrap(); |
| 498 |
if shifted.month() == 1 { |
| 499 |
assert_eq!(shifted.day(), 31) |
| 500 |
} else if shifted.month() == 4 { |
| 501 |
assert_eq!(shifted.day(), 30) |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
let freq = RelativeDuration::months(-1); |
| 506 |
let mut rule = DateRule::new(start, freq); |
| 507 |
|
| 508 |
for _ in 0..120 { |
| 509 |
let shifted = rule.next().unwrap(); |
| 510 |
if shifted.month() == 1 { |
| 511 |
assert_eq!(shifted.day(), 31) |
| 512 |
} else if shifted.month() == 4 { |
| 513 |
assert_eq!(shifted.day(), 30) |
| 514 |
} |
| 515 |
} |
| 516 |
} |
| 517 |
} |
| 518 |
} |