cron-expr 0.1.0

Cron expression parsing and evaluation
Documentation
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())
    }
}