summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorPro <twisted.fall@gmail.com>2024-02-09 21:53:42 +0100
committerPro <twisted.fall@gmail.com>2024-02-09 21:53:42 +0100
commit1ba7fa469d04530444eb0bc6d7c9ee2fd41457f6 (patch)
treecc732a509acad26a5f484246eefaddddde776154 /src
parent3fe862d63b4be68f62f8de737c5322ce22ea8dd9 (diff)
Bump edition to 2021 and introduce rustfmt
Diffstat (limited to 'src')
-rw-r--r--src/error.rs6
-rw-r--r--src/indicator.rs56
-rw-r--r--src/iter.rs211
-rw-r--r--src/lib.rs23
-rw-r--r--src/matcher.rs27
-rw-r--r--src/parser/iterator.rs203
-rw-r--r--src/parser/mod.rs22
-rw-r--r--src/parser/timetype.rs356
-rw-r--r--src/timetype.rs1161
-rw-r--r--src/util.rs48
10 files changed, 1050 insertions, 1063 deletions
diff --git a/src/error.rs b/src/error.rs
index bb1aa80..979a76b 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,12 +1,11 @@
-use timetype::TimeType;
-
use thiserror::Error;
+use crate::timetype::TimeType;
+
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub enum Error {
-
#[error("Unknown Error")]
UnknownError,
@@ -46,4 +45,3 @@ pub enum Error {
#[error("Tokenizer error")]
NomError(String),
}
-
diff --git a/src/indicator.rs b/src/indicator.rs
index 39bd371..a89b0f0 100644
--- a/src/indicator.rs
+++ b/src/indicator.rs
@@ -1,14 +1,12 @@
#[cfg(feature = "with-filters")]
+use chrono::Datelike;
+#[cfg(feature = "with-filters")]
use filters::filter::Filter;
-
#[cfg(feature = "with-filters")]
use filters::filter::IntoFilter;
#[cfg(feature = "with-filters")]
-use timetype::TimeType;
-
-#[cfg(feature = "with-filters")]
-use chrono::Datelike;
+use crate::timetype::TimeType;
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub enum Day {
@@ -24,13 +22,13 @@ pub enum Day {
impl From<Day> for chrono::Weekday {
fn from(val: Day) -> Self {
match val {
- Day::Monday => chrono::Weekday::Mon,
- Day::Tuesday => chrono::Weekday::Tue,
+ Day::Monday => chrono::Weekday::Mon,
+ Day::Tuesday => chrono::Weekday::Tue,
Day::Wednesday => chrono::Weekday::Wed,
- Day::Thursday => chrono::Weekday::Thu,
- Day::Friday => chrono::Weekday::Fri,
- Day::Saturday => chrono::Weekday::Sat,
- Day::Sunday => chrono::Weekday::Sun,
+ Day::Thursday => chrono::Weekday::Thu,
+ Day::Friday => chrono::Weekday::Fri,
+ Day::Saturday => chrono::Weekday::Sat,
+ Day::Sunday => chrono::Weekday::Sun,
}
}
}
@@ -54,18 +52,18 @@ pub enum Month {
impl From<Month> for u32 {
fn from(val: Month) -> Self {
match val {
- Month::January => 1,
- Month::February => 2,
- Month::March => 3,
- Month::April => 4,
- Month::May => 5,
- Month::June => 6,
- Month::July => 7,
- Month::August => 8,
- Month::September => 9,
- Month::October => 10,
- Month::November => 11,
- Month::December => 12,
+ Month::January => 1,
+ Month::February => 2,
+ Month::March => 3,
+ Month::April => 4,
+ Month::May => 5,
+ Month::June => 6,
+ Month::July => 7,
+ Month::August => 8,
+ Month::September => 9,
+ Month::October => 10,
+ Month::November => 11,
+ Month::December => 12,
}
}
}
@@ -76,7 +74,9 @@ pub struct DayFilter(Day);
#[cfg(feature = "with-filters")]
impl Filter<TimeType> for DayFilter {
fn filter(&self, tt: &TimeType) -> bool {
- tt.get_moment().map(|mom| mom.weekday() == self.0.clone().into()).unwrap_or(false)
+ tt.get_moment()
+ .map(|mom| mom.weekday() == self.0.clone().into())
+ .unwrap_or(false)
}
}
@@ -87,17 +87,17 @@ impl IntoFilter<TimeType> for Day {
fn into_filter(self) -> Self::IntoFilt {
DayFilter(self)
}
-
}
-
#[cfg(feature = "with-filters")]
pub struct MonthFilter(Month);
#[cfg(feature = "with-filters")]
impl Filter<TimeType> for MonthFilter {
fn filter(&self, tt: &TimeType) -> bool {
- tt.get_moment().map(|mom| mom.month() == self.0.clone().into()).unwrap_or(false)
+ tt.get_moment()
+ .map(|mom| mom.month() == self.0.clone().into())
+ .unwrap_or(false)
}
}
@@ -108,6 +108,4 @@ impl IntoFilter<TimeType> for Month {
fn into_filter(self) -> Self::IntoFilt {
MonthFilter(self)
}
-
}
-
diff --git a/src/iter.rs b/src/iter.rs
index ee32d6d..d027083 100644
--- a/src/iter.rs
+++ b/src/iter.rs
@@ -3,10 +3,10 @@
use chrono::NaiveDateTime;
-use error::Result;
-use error::Error;
-use timetype::TimeType;
-use matcher::Matcher;
+use crate::error::Error;
+use crate::error::Result;
+use crate::matcher::Matcher;
+use crate::timetype::TimeType;
#[derive(Debug)]
pub struct Iter {
@@ -23,13 +23,12 @@ pub struct Iter {
// Performing the computation on the yielded `TimeType` instances can be done by transforming this
// iterator into a `CalculatingIter`.
impl Iter {
-
pub fn build(base: NaiveDateTime, inc: TimeType) -> Result<Iter> {
if !inc.is_a_amount() {
Err(Error::ArgumentErrorNotAnAmount(inc))
} else {
Ok(Iter {
- base: TimeType::moment(base),
+ base: TimeType::moment(base),
increment: inc,
had_first: false,
})
@@ -53,14 +52,10 @@ impl Iter {
}
fn recalculate(&mut self) -> Result<()> {
- self.base
- .clone()
- .calculate()
- .map(|res| {
- self.base = res;
- })
+ self.base.clone().calculate().map(|res| {
+ self.base = res;
+ })
}
-
}
/// # Warning
@@ -84,17 +79,18 @@ impl Iterator for Iter {
Some(self.skip().map(|_| self.base.clone()))
}
}
-
}
#[derive(Debug)]
pub struct FilterIter<I, M>(I, M)
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher;
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher;
impl<I, M> FilterIter<I, M>
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
fn new(i: I, m: M) -> FilterIter<I, M> {
FilterIter(i, m)
@@ -102,33 +98,35 @@ impl<I, M> FilterIter<I, M>
}
impl<I, M> Iterator for FilterIter<I, M>
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
type Item = Result<TimeType>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.0.next() {
- None => return None,
+ None => return None,
Some(Err(e)) => return Some(Err(e)),
Some(Ok(tt)) => match self.1.matches(&tt) {
Ok(false) => continue,
- Ok(true) => return Some(Ok(tt)),
- Err(e) => return Some(Err(e)),
- }
+ Ok(true) => return Some(Ok(tt)),
+ Err(e) => return Some(Err(e)),
+ },
}
}
}
}
-pub trait EveryFilter<M: Matcher> : Iterator<Item = Result<TimeType>> + Sized {
+pub trait EveryFilter<M: Matcher>: Iterator<Item = Result<TimeType>> + Sized {
fn every(self, matcher: M) -> FilterIter<Self, M>;
}
impl<I, M> EveryFilter<M> for I
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
fn every(self, matcher: M) -> FilterIter<Self, M> {
FilterIter::new(self, matcher)
@@ -137,12 +135,14 @@ impl<I, M> EveryFilter<M> for I
#[derive(Debug)]
pub struct WithoutIter<I, M>(I, M)
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher;
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher;
impl<I, M> WithoutIter<I, M>
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
fn new(i: I, m: M) -> WithoutIter<I, M> {
WithoutIter(i, m)
@@ -150,33 +150,35 @@ impl<I, M> WithoutIter<I, M>
}
impl<I, M> Iterator for WithoutIter<I, M>
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
type Item = Result<TimeType>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.0.next() {
- None => return None,
+ None => return None,
Some(Err(e)) => return Some(Err(e)),
Some(Ok(tt)) => match self.1.matches(&tt) {
Ok(false) => return Some(Ok(tt)),
- Ok(true) => continue,
- Err(e) => return Some(Err(e)),
- }
+ Ok(true) => continue,
+ Err(e) => return Some(Err(e)),
+ },
}
}
}
}
-pub trait WithoutFilter<M: Matcher> : Iterator<Item = Result<TimeType>> + Sized {
+pub trait WithoutFilter<M: Matcher>: Iterator<Item = Result<TimeType>> + Sized {
fn without(self, matcher: M) -> WithoutIter<Self, M>;
}
impl<I, M> WithoutFilter<M> for I
- where I: Iterator<Item = Result<TimeType>>,
- M: Matcher
+where
+ I: Iterator<Item = Result<TimeType>>,
+ M: Matcher,
{
fn without(self, matcher: M) -> WithoutIter<Self, M> {
WithoutIter::new(self, matcher)
@@ -185,10 +187,12 @@ impl<I, M> WithoutFilter<M> for I
#[derive(Debug)]
pub struct UntilIter<I>(I, NaiveDateTime)
- where I: Iterator<Item = Result<TimeType>>;
+where
+ I: Iterator<Item = Result<TimeType>>;
impl<I> UntilIter<I>
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
fn new(i: I, date: NaiveDateTime) -> UntilIter<I> {
UntilIter(i, date)
@@ -196,36 +200,40 @@ impl<I> UntilIter<I>
}
impl<I> Iterator for UntilIter<I>
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
type Item = Result<TimeType>;
fn next(&mut self) -> Option<Self::Item> {
match self.0.next() {
- None => None,
+ None => None,
Some(Err(e)) => Some(Err(e)),
Some(Ok(tt)) => match tt.calculate() {
Err(e) => Some(Err(e)),
- Ok(tt) => if tt.is_moment() {
- if tt.get_moment().unwrap() < &self.1 {
- Some(Ok(tt))
+ Ok(tt) => {
+ if tt.is_moment() {
+ if tt.get_moment().unwrap() < &self.1 {
+ Some(Ok(tt))
+ } else {
+ None
+ }
} else {
- None
+ Some(Err(Error::ArgumentErrorNotAMoment(tt.name())))
}
- } else {
- Some(Err(Error::ArgumentErrorNotAMoment(tt.name())))
- }
- }
+ },
+ },
}
}
}
-pub trait Until : Iterator<Item = Result<TimeType>> + Sized {
+pub trait Until: Iterator<Item = Result<TimeType>> + Sized {
fn until(self, ending: NaiveDateTime) -> UntilIter<Self>;
}
impl<I> Until for I
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
fn until(self, ending: NaiveDateTime) -> UntilIter<Self> {
UntilIter::new(self, ending)
@@ -234,7 +242,8 @@ impl<I> Until for I
#[derive(Debug)]
pub struct TimesIter<I>
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
inner: I,
times: i64,
@@ -242,7 +251,8 @@ pub struct TimesIter<I>
}
impl<I> TimesIter<I>
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
fn new(i: I, times: i64) -> TimesIter<I> {
TimesIter {
@@ -254,7 +264,8 @@ impl<I> TimesIter<I>
}
impl<I> Iterator for TimesIter<I>
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
type Item = Result<TimeType>;
@@ -268,12 +279,13 @@ impl<I> Iterator for TimesIter<I>
}
}
-pub trait Times : Iterator<Item = Result<TimeType>> + Sized {
+pub trait Times: Iterator<Item = Result<TimeType>> + Sized {
fn times(self, times: i64) -> TimesIter<Self>;
}
impl<I> Times for I
- where I: Iterator<Item = Result<TimeType>>
+where
+ I: Iterator<Item = Result<TimeType>>,
{
fn times(self, times: i64) -> TimesIter<Self> {
TimesIter::new(self, times)
@@ -281,10 +293,11 @@ impl<I> Times for I
}
pub mod extensions {
- use timetype::TimeType as TT;
+ use crate::error::Error;
+ use crate::error::Result;
+ use crate::timetype::TimeType as TT;
+
use super::Iter;
- use error::Result;
- use error::Error;
pub trait Minutely {
fn minutely(self, i: i64) -> Result<Iter>;
@@ -298,7 +311,7 @@ pub mod extensions {
fn daily(self, i: i64) -> Result<Iter>;
}
- pub trait Weekly : Sized {
+ pub trait Weekly: Sized {
fn weekly(self, i: i64) -> Result<Iter>;
}
@@ -315,7 +328,6 @@ pub mod extensions {
}
impl Minutely for TT {
-
fn minutely(self, i: i64) -> Result<Iter> {
match self {
TT::Moment(mom) => {
@@ -326,11 +338,9 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
impl Hourly for TT {
-
fn hourly(self, i: i64) -> Result<Iter> {
match self {
TT::Moment(mom) => {
@@ -341,11 +351,9 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
impl Daily for TT {
-
fn daily(self, i: i64) -> Result<Iter> {
match self {
TT::Moment(mom) => {
@@ -356,11 +364,9 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
impl Weekly for TT {
-
/// Conveniance function over `Daily::daily( n * 7 )`
fn weekly(self, i: i64) -> Result<Iter> {
match self {
@@ -372,11 +378,9 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
impl Monthly for TT {
-
fn monthly(self, i: i64) -> Result<Iter> {
match self {
TT::Moment(mom) => {
@@ -387,11 +391,9 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
impl Yearly for TT {
-
fn yearly(self, i: i64) -> Result<Iter> {
match self {
TT::Moment(mom) => {
@@ -402,10 +404,8 @@ pub mod extensions {
_ => Err(Error::ArgumentErrorNotAnAmount(self)),
}
}
-
}
-
impl Every for TT {
fn every(self, inc: TT) -> Result<Iter> {
match self {
@@ -417,10 +417,12 @@ pub mod extensions {
#[cfg(test)]
mod tests {
- use super::*;
- use timetype::TimeType as TT;
use chrono::NaiveDate as ND;
+ use crate::timetype::TimeType as TT;
+
+ use super::*;
+
fn ymd_hms(y: i32, m: u32, d: u32, h: u32, mi: u32, s: u32) -> TT {
TT::moment(ND::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, mi, s).unwrap())
}
@@ -465,9 +467,9 @@ pub mod extensions {
assert_eq!(ymd_hms(2000, 1, 1, 1, 0, 0), *minutes[0].as_ref().unwrap());
assert_eq!(ymd_hms(2000, 1, 8, 1, 0, 0), *minutes[1].as_ref().unwrap());
- assert_eq!(ymd_hms(2000, 1,15, 1, 0, 0), *minutes[2].as_ref().unwrap());
- assert_eq!(ymd_hms(2000, 1,22, 1, 0, 0), *minutes[3].as_ref().unwrap());
- assert_eq!(ymd_hms(2000, 1,29, 1, 0, 0), *minutes[4].as_ref().unwrap());
+ assert_eq!(ymd_hms(2000, 1, 15, 1, 0, 0), *minutes[2].as_ref().unwrap());
+ assert_eq!(ymd_hms(2000, 1, 22, 1, 0, 0), *minutes[3].as_ref().unwrap());
+ assert_eq!(ymd_hms(2000, 1, 29, 1, 0, 0), *minutes[4].as_ref().unwrap());
}
#[test]
@@ -499,15 +501,13 @@ pub mod extensions {
assert_eq!(ymd_hms(2003, 1, 1, 0, 0, 0), *minutes[3].as_ref().unwrap());
assert_eq!(ymd_hms(2004, 1, 1, 0, 0, 0), *minutes[4].as_ref().unwrap());
}
-
}
-
}
#[cfg(test)]
mod type_tests {
- use super::*;
use super::extensions::*;
+ use super::*;
#[test]
fn test_iterator_every_once() {
@@ -515,7 +515,7 @@ mod type_tests {
let _ = TimeType::today()
.yearly(1)
.unwrap()
- .every(::indicator::Day::Monday);
+ .every(crate::indicator::Day::Monday);
}
#[test]
@@ -524,25 +524,30 @@ mod type_tests {
let _ = TimeType::today()
.yearly(1) // collecting makes us stack-overflow because of the heavy filtering!
.unwrap()
- .every(::indicator::Day::Monday)
- .every(::indicator::Month::January);
+ .every(crate::indicator::Day::Monday)
+ .every(crate::indicator::Month::January);
}
}
#[cfg(all(feature = "with-filters", test))]
mod type_tests_filter_interface {
- use super::*;
- use super::extensions::*;
use filters::filter::Filter;
use filters::filter::IntoFilter;
+ use super::extensions::*;
+ use super::*;
+
#[test]
fn test_compile() {
// This test is solely to check whether this compiles and the API is nice
let _ = TimeType::today()
.daily(1)
.unwrap()
- .every(::indicator::Day::Monday.into_filter().or(::indicator::Month::January))
+ .every(
+ crate::indicator::Day::Monday
+ .into_filter()
+ .or(crate::indicator::Month::January),
+ )
.take(12)
.collect::<Vec<_>>();
}
@@ -554,8 +559,8 @@ mod type_tests_filter_interface {
.daily(1)
.unwrap()
.take(20)
- .every(::indicator::Day::Monday)
- .without(::indicator::Day::Monday)
+ .every(crate::indicator::Day::Monday)
+ .without(crate::indicator::Day::Monday)
.collect::<Vec<_>>();
assert_eq!(0, v.len());
@@ -564,8 +569,8 @@ mod type_tests_filter_interface {
#[cfg(test)]
mod test_until {
- use super::*;
use super::extensions::*;
+ use super::*;
#[test]
fn test_until() {
@@ -575,11 +580,7 @@ mod test_until {
.get_moment()
.unwrap();
- let v = TimeType::today()
- .daily(1)
- .unwrap()
- .until(yesterday)
- .collect::<Vec<_>>();
+ let v = TimeType::today().daily(1).unwrap().until(yesterday).collect::<Vec<_>>();
assert!(v.is_empty());
}
@@ -592,11 +593,7 @@ mod test_until {
.get_moment()
.unwrap();
- let v = TimeType::today()
- .daily(1)
- .unwrap()
- .until(end)
- .collect::<Vec<_>>();
+ let v = TimeType::today().daily(1).unwrap().until(end).collect::<Vec<_>>();
assert_eq!(v.len(), 1);
}
@@ -609,14 +606,8 @@ mod test_until {
.get_moment()
.unwrap();
- let v = TimeType::today()
- .hourly(1)
- .unwrap()
- .until(end)
- .collect::<Vec<_>>();
+ let v = TimeType::today().hourly(1).unwrap().until(end).collect::<Vec<_>>();
assert_eq!(v.len(), 48);
}
-
}
-
diff --git a/src/lib.rs b/src/lib.rs
index b9e85c1..5b37f8a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,26 +1,9 @@
-#![recursion_limit="256"]
-
-extern crate thiserror;
-extern crate chrono;
-
-extern crate nom;
-extern crate iso8601;
-
-#[cfg(feature = "with-filters")]
-extern crate filters;
-
-#[cfg(test)]
-extern crate env_logger;
-
-#[cfg(test)]
-#[macro_use]
-extern crate log;
+#![recursion_limit = "256"]
pub mod error;
-pub mod iter;
-pub mod timetype;
pub mod indicator;
+pub mod iter;
pub mod matcher;
pub mod parser;
+pub mod timetype;
mod util;
-
diff --git a/src/matcher.rs b/src/matcher.rs
index 2676201..965a08c 100644
--- a/src/matcher.rs
+++ b/src/matcher.rs
@@ -1,11 +1,12 @@
-
use chrono::Datelike;
+#[cfg(feature = "with-filters")]
+use filters::filter::*;
-use error::Error;
-use error::Result;
-use indicator::Day;
-use indicator::Month;
-use timetype::TimeType;
+use crate::error::Error;
+use crate::error::Result;
+use crate::indicator::Day;
+use crate::indicator::Month;
+use crate::timetype::TimeType;
/// A trait to extend indicator::* to be able to match them with a TimeType object
pub trait Matcher {
@@ -13,9 +14,8 @@ pub trait Matcher {
}
impl Matcher for Day {
-
fn matches(&self, tt: &TimeType) -> Result<bool> {
- let this : ::chrono::Weekday = self.clone().into();
+ let this: chrono::Weekday = self.clone().into();
tt.get_moment()
.map(|mom| this == mom.weekday())
.ok_or(Error::ArgumentErrorNotAMoment(tt.name()))
@@ -23,25 +23,20 @@ impl Matcher for Day {
}
impl Matcher for Month {
-
fn matches(&self, tt: &TimeType) -> Result<bool> {
- let this : u32 = self.clone().into();
+ let this: u32 = self.clone().into();
tt.get_moment()
.map(|mom| this == mom.month())
.ok_or(Error::ArgumentErrorNotAMoment(tt.name()))
}
-
}
#[cfg(feature = "with-filters")]
-use filters::filter::*;
-
-#[cfg(feature = "with-filters")]
impl<F> Matcher for F
- where F: Filter<TimeType>
+where
+ F: Filter<TimeType>,
{
fn matches(&self, tt: &TimeType) -> Result<bool> {
Ok(self.filter(tt))
}
}
-
diff --git a/src/parser/iterator.rs b/src/parser/iterator.rs
index 21bf8d5..06ecc2b 100644
--- a/src/parser/iterator.rs
+++ b/src/parser/iterator.rs
@@ -2,26 +2,29 @@ use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::{multispace0, multispace1};
use nom::combinator::{complete, map, opt};
-use nom::IResult;
use nom::sequence::tuple;
+use nom::IResult;
-use error::Result;
-use error::Error;
-use parser::timetype::*;
-use timetype::IntoTimeType;
-use timetype;
-use iter;
+use crate::error::Error;
+use crate::error::Result;
+use crate::iter;
+use crate::timetype;
+use crate::timetype::IntoTimeType;
+
+use super::timetype::*;
pub fn iter_spec(i: &[u8]) -> IResult<&[u8], Iterspec> {
complete(alt((
map(tag("secondly"), |_| Iterspec::Secondly),
map(tag("minutely"), |_| Iterspec::Minutely),
- map(tag("hourly"), |_| Iterspec::Hourly),
- map(tag("daily"), |_| Iterspec::Daily),
- map(tag("weekly"), |_| Iterspec::Weekly),
- map(tag("monthly"), |_| Iterspec::Monthly),
- map(tag("yearly"), |_| Iterspec::Yearly),
- map(tuple((tag("every"), integer, unit_parser)), |(_, number, unit)| Iterspec::Every(number, unit))
+ map(tag("hourly"), |_| Iterspec::Hourly),
+ map(tag("daily"), |_| Iterspec::Daily),
+ map(tag("weekly"), |_| Iterspec::Weekly),
+ map(tag("monthly"), |_| Iterspec::Monthly),
+ map(tag("yearly"), |_| Iterspec::Yearly),
+ map(tuple((tag("every"), integer, unit_parser)), |(_, number, unit)| {
+ Iterspec::Every(number, unit)
+ }),
)))(i)
}
@@ -41,25 +44,31 @@ pub fn until_spec(i: &[u8]) -> IResult<&[u8], UntilSpec> {
complete(alt((
map(
tuple((tag("until"), multispace1, exact_date_parser)),
- |(_, _, exact)| UntilSpec::Exact(exact)
+ |(_, _, exact)| UntilSpec::Exact(exact),
),
- map(
- tuple((integer, multispace1, tag("times"))),
- |(num, _, _)| UntilSpec::Times(num)
- )
+ map(tuple((integer, multispace1, tag("times"))), |(num, _, _)| {
+ UntilSpec::Times(num)
+ }),
)))(i)
}
#[derive(Debug, PartialEq, Eq)]
pub enum UntilSpec {
Exact(ExactDate),
- Times(i64)
+ Times(i64),
}
pub fn iterator(i: &[u8]) -> IResult<&[u8], Iterator> {
map(
- tuple((multispace0, date, multispace0, iter_spec, multispace0, opt(complete(until_spec)))),
- |(_, d, _, spec, _, until)| { Iterator(d, spec, until) },
+ tuple((
+ multispace0,
+ date,
+ multispace0,
+ iter_spec,
+ multispace0,
+ opt(complete(until_spec)),
+ )),
+ |(_, d, _, spec, _, until)| Iterator(d, spec, until),
)(i)
}
@@ -74,37 +83,38 @@ impl Iterator {
let unit_to_amount = |i, unit| match unit {
Unit::Second => timetype::TimeType::seconds(i),
Unit::Minute => timetype::TimeType::minutes(i),
- Unit::Hour => timetype::TimeType::hours(i),
- Unit::Day => timetype::TimeType::days(i),
- Unit::Week => timetype::TimeType::weeks(i),
- Unit::Month => timetype::TimeType::months(i),
- Unit::Year => timetype::TimeType::years(i),
+ Unit::Hour => timetype::TimeType::hours(i),
+ Unit::Day => timetype::TimeType::days(i),
+ Unit::Week => timetype::TimeType::weeks(i),
+ Unit::Month => timetype::TimeType::months(i),
+ Unit::Year => timetype::TimeType::years(i),
};
let recur = match self.1 {
Iterspec::Every(i, unit) => unit_to_amount(i, unit),
Iterspec::Secondly => unit_to_amount(1, Unit::Second),
Iterspec::Minutely => unit_to_amount(1, Unit::Minute),
- Iterspec::Hourly => unit_to_amount(1, Unit::Hour),
- Iterspec::Daily => unit_to_amount(1, Unit::Day),
- Iterspec::Weekly => unit_to_amount(1, Unit::Week),
- Iterspec::Monthly => unit_to_amount(1, Unit::Month),
- Iterspec::Yearly => unit_to_amount(1, Unit::Year),
+ Iterspec::Hourly => unit_to_amount(1, Unit::Hour),
+ Iterspec::Daily => unit_to_amount(1, Unit::Day),
+ Iterspec::Weekly => unit_to_amount(1, Unit::Week),
+ Iterspec::Monthly => unit_to_amount(1, Unit::Month),
+ Iterspec::Yearly => unit_to_amount(1, Unit::Year),
};
- let into_ndt = |e: timetype::TimeType| e.calculate()?
- .get_moment()
- .ok_or(Error::NotADateInsideIterator)
- .map_err(Error::from)
- .map(Clone::clone);
+ let into_ndt = |e: timetype::TimeType| {
+ e.calculate()?
+ .get_moment()
+ .ok_or(Error::NotADateInsideIterator)
+ .map_err(Error::from)
+ .map(Clone::clone)
+ };
match self.2 {
Some(UntilSpec::Exact(e)) => {
let base = into_ndt(self.0.into_timetype()?)?;
- let e = into_ndt(e.into_timetype()?)?;
+ let e = into_ndt(e.into_timetype()?)?;
- iter::Iter::build(base, recur)
- .map(|it| UserIterator::UntilIterator(it.until(e)))
+ iter::Iter::build(base, recur).map(|it| UserIterator::UntilIterator(it.until(e)))
},
Some(UntilSpec::Times(i)) => {
@@ -116,8 +126,7 @@ impl Iterator {
None => {
let base = into_ndt(self.0.into_timetype()?)?;
- iter::Iter::build(base, recur)
- .map(UserIterator::Iterator)
+ iter::Iter::build(base, recur).map(UserIterator::Iterator)
},
}
}
@@ -126,35 +135,37 @@ impl Iterator {
// names are hard
#[derive(Debug)]
pub enum UserIterator<I>
- where I: ::std::iter::Iterator<Item = Result<timetype::TimeType>>
+where
+ I: std::iter::Iterator<Item = Result<timetype::TimeType>>,
{
Iterator(iter::Iter),
TimesIter(iter::TimesIter<I>),
- UntilIterator(iter::UntilIter<I>)
+ UntilIterator(iter::UntilIter<I>),
}
-impl<I> ::std::iter::Iterator for UserIterator<I>
- where I: ::std::iter::Iterator<Item = Result<timetype::TimeType>>
+impl<I> std::iter::Iterator for UserIterator<I>
+where
+ I: std::iter::Iterator<Item = Result<timetype::TimeType>>,
{
type Item = Result<timetype::TimeType>;
fn next(&mut self) -> Option<Self::Item> {
match *self {
- UserIterator::Iterator(ref mut i) => i.next(),
- UserIterator::TimesIter(ref mut i) => i.next(),
+ UserIterator::Iterator(ref mut i) => i.next(),
+ UserIterator::TimesIter(ref mut i) => i.next(),
UserIterator::UntilIterator(ref mut i) => i.next(),
}
}
}
-
#[cfg(test)]
mod tests {
use std::iter::Iterator;
- use super::*;
- use chrono::Timelike;
use chrono::Datelike;
+ use chrono::Timelike;
+
+ use super::*;
#[test]
fn test_iterspec() {
@@ -165,7 +176,10 @@ mod tests {
assert_eq!(iter_spec(&b"weekly"[..]), Ok((&b""[..], Iterspec::Weekly)));
assert_eq!(iter_spec(&b"monthly"[..]), Ok((&b""[..], Iterspec::Monthly)));
assert_eq!(iter_spec(&b"yearly"[..]), Ok((&b""[..], Iterspec::Yearly)));
- assert_eq!(iter_spec(&b"every 5min"[..]), Ok((&b""[..], Iterspec::Every(5, Unit::Minute))));
+ assert_eq!(
+ iter_spec(&b"every 5min"[..]),
+ Ok((&b""[..], Iterspec::Every(5, Unit::Minute)))
+ );
}
#[test]
@@ -175,18 +189,19 @@ mod tests {
let (_, i) = res.unwrap();
println!("{:#?}", i);
- let ui : Result<UserIterator<iter::Iter>> = i.into_user_iterator();
+ let ui: Result<UserIterator<iter::Iter>> = i.into_user_iterator();
assert!(ui.is_ok(), "Not okay: {:#?}", ui);
let mut ui = ui.unwrap();
- for hour in 0..10 { // 10 is randomly chosen (fair dice roll... )
+ for hour in 0..10 {
+ // 10 is randomly chosen (fair dice roll... )
let n = ui.next().unwrap();
assert!(n.is_ok(), "Not ok: {:#?}", n);
let tt = n.unwrap();
- assert_eq!(tt.get_moment().unwrap().year() , 2017);
- assert_eq!(tt.get_moment().unwrap().month() , 1);
- assert_eq!(tt.get_moment().unwrap().day() , 1);
- assert_eq!(tt.get_moment().unwrap().hour() , hour);
+ assert_eq!(tt.get_moment().unwrap().year(), 2017);
+ assert_eq!(tt.get_moment().unwrap().month(), 1);
+ assert_eq!(tt.get_moment().unwrap().day(), 1);
+ assert_eq!(tt.get_moment().unwrap().hour(), hour);
assert_eq!(tt.get_moment().unwrap().minute(), 0);
assert_eq!(tt.get_moment().unwrap().second(), 0);<