Browse Source

initial commit

master
Adrian Malacoda 2 years ago
commit
0b1c6e3dff
2 changed files with 91 additions and 0 deletions
  1. +7
    -0
      Cargo.toml
  2. +84
    -0
      src/lib.rs

+ 7
- 0
Cargo.toml View File

@@ -0,0 +1,7 @@
[package]
name = "daterade"
version = "0.0.1"
authors = ["Adrian Malacoda <adrian.malacoda@monarch-pass.net>"]

[dependencies]
chrono = "0.4.0"

+ 84
- 0
src/lib.rs View File

@@ -0,0 +1,84 @@
extern crate chrono;
use chrono::{Datelike, Timelike, DateTime, Weekday, TimeZone};

pub enum Frequency {
Yearly,
Weekly,
Monthly,
Daily,
Hourly,
Minutely,
Secondly
}

pub struct ByDay {
pub num: i32,
pub weekday: Weekday
}

pub struct Recurrence<Tz: TimeZone> {
pub frequency: Frequency,
pub count: Option<u32>,
pub interval: Option<i32>,

pub byminute: Option<Vec<u32>>,
pub byhour: Option<Vec<u32>>,
pub byday: Option<Vec<ByDay>>,
pub byweekno: Option<Vec<u32>>,
pub bymonth: Option<Vec<u32>>,
pub bymonthday: Option<Vec<u32>>,

pub until: Option<DateTime<Tz>>
}

impl<Tz: TimeZone> Recurrence<Tz> {
pub fn iter (&self, start: DateTime<Tz>) -> DateTimeIterator<Tz> {
DateTimeIterator {
recurrence: &self,
start: start,
next_datetimes: vec![]
}
}
}

pub struct DateTimeIterator<'a, Tz: TimeZone + 'a> {
recurrence: &'a Recurrence<Tz>,
start: DateTime<Tz>,

next_datetimes: Vec<DateTime<Tz>>
}

impl<'a, Tz: TimeZone + 'a> DateTimeIterator<'a, Tz> {
fn generate_next_datetimes (&mut self) {
let interval = self.recurrence.interval.unwrap_or(1);
self.start = match self.recurrence.frequency {
Frequency::Yearly => self.start.with_year(self.start.year() + interval).unwrap(),
Frequency::Monthly => self.start.with_month(self.start.month() + interval as u32).unwrap(),
Frequency::Weekly => self.start.with_day(self.start.day() + (7 * interval as u32)).unwrap(),
Frequency::Daily => self.start.with_day(self.start.day() + interval as u32).unwrap(),
Frequency::Hourly => self.start.with_hour(self.start.hour() + interval as u32).unwrap(),
Frequency::Minutely => self.start.with_minute(self.start.minute() + interval as u32).unwrap(),
Frequency::Secondly => self.start.with_second(self.start.second() + interval as u32).unwrap()
}
}
}

impl<'a, Tz: TimeZone + 'a> Iterator for DateTimeIterator<'a, Tz> {
type Item = DateTime<Tz>;

fn next (&mut self) -> Option<DateTime<Tz>> {
if self.next_datetimes.is_empty() {
self.generate_next_datetimes();
}

self.next_datetimes.pop()
}
}

#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}

Loading…
Cancel
Save