1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use chrono::{Datelike, DateTime, Local, Timelike, TimeZone};

use time_unit::{Hour, Minute, Month, MonthDay, TimeUnit, WeekDay};

use crate::error::CronError;
use crate::error::CronErrorKind::{InvalidSyntax, InvalidTimeUnit};

mod time_unit;
mod error;

#[derive(Debug)]
pub struct CronExpr {
    minute: Minute,
    hour: Hour,
    day_of_month: MonthDay,
    month: Month,
    day_of_week: WeekDay
}

#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for CronExpr {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
        use std::fmt;

        struct Visitor {}

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = CronExpr;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "string")
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> where
                E: serde::de::Error, {
                CronExpr::parse(v).map_err(|err| E::custom(format!("{}", err)))
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where
                E: serde::de::Error, {
                CronExpr::parse(&v).map_err(|err| E::custom(format!("{}", err)))
            }
        }

        deserializer.deserialize_string(Visitor {})
    }
}

fn next_month<T: TimeZone>(dt: &DateTime<T>) -> DateTime<T> {
    dt.with_month(dt.month() + 1)
        .or(dt.with_year(dt.year() + 1)
            .and_then(|d| d.with_month0(0)))
        .and_then(|d| d.with_day0(0))
        .and_then(|d| d.with_hour(0))
        .and_then(|d| d.with_minute(0))
        .and_then(|d| d.with_second(0))
        .and_then(|d| d.with_nanosecond(0))
        .unwrap()
}

fn next_day<T: TimeZone>(dt: &DateTime<T>) -> DateTime<T> {
    dt.with_day(dt.day() + 1)
        .and_then(|d| d.with_hour(0))
        .and_then(|d| d.with_minute(0))
        .and_then(|d| d.with_second(0))
        .and_then(|d| d.with_nanosecond(0))
        .unwrap_or(next_month(dt))
}

fn next_hour<T: TimeZone>(dt: &DateTime<T>) -> DateTime<T> {
    dt.with_hour(dt.hour() + 1)
        .and_then(|d| d.with_minute(0))
        .and_then(|d| d.with_second(0))
        .and_then(|d| d.with_nanosecond(0))
        .unwrap_or(next_day(dt))
}

fn next_minute<T: TimeZone>(dt: &DateTime<T>) -> DateTime<T> {
    dt.with_minute(dt.minute() + 1)
        .and_then(|d| d.with_second(0))
        .and_then(|d| d.with_nanosecond(0))
        .unwrap_or(next_hour(dt))
}

impl CronExpr {
    pub fn parse(input: &str) -> Result<CronExpr, CronError> {
        let split: Vec<&str> = input.split(" ").collect();

        if split.len() != 5 {
            return Err(InvalidSyntax.err(input))
        }

        fn parse_time_unit<T: TimeUnit>(input: &str) -> Result<T, CronError> {
            T::parse(input).map_err(|err| InvalidTimeUnit(T::kind(), err).err(input))
        }

        Ok(CronExpr {
            minute: parse_time_unit(split[0])?,
            hour: parse_time_unit(split[1])?,
            day_of_month: parse_time_unit(split[2])?,
            month: parse_time_unit(split[3])?,
            day_of_week: parse_time_unit(split[4])?,
        })
    }

    pub fn next<T: TimeZone>(&self, after: &DateTime<T>) -> DateTime<T> {
        let mut next = next_minute(after);
        loop {
            if !self.month.value().includes(next.month()) {
                next = next_month(&next);
                continue;
            }

            if !((!self.day_of_month.value().is_wildcard() && self.day_of_month.value().includes(next.day())) ||
                (!self.day_of_week.value().is_wildcard() && self.day_of_week.value().includes(next.weekday().number_from_monday())) ||
                (self.day_of_month.value().is_wildcard() && self.day_of_week.value().is_wildcard())) {
                next = next_day(&next);
                continue;
            }

            if !self.hour.value().includes(next.hour()) {
                next = next_hour(&next);
                continue;
            }

            if !self.minute.value().includes(next.minute()) {
                next = next_minute(&next);
                continue;
            }

            break;
        }

        return next;
    }

    pub fn next_after_now(&self) -> DateTime<Local> {
        self.next(&Local::now())
    }
}