Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement optimized Serialize and Deserialize for Schedule #129

Merged
merged 6 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ name = "cron"
chrono = { version = "~0.4", default-features = false, features = ["clock"] }
nom = "~7"
once_cell = "1.10"
serde = {version = "1.0.164", optional = true }

[dev-dependencies]
chrono-tz = "~0.6"
serde_test = "1.0.164"

[features]
serde = ["dep:serde"]


84 changes: 81 additions & 3 deletions src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,20 @@ use chrono::offset::TimeZone;
use chrono::{DateTime, Datelike, Timelike, Utc};
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Bound::{Included, Unbounded};
use std::str::FromStr;

#[cfg(feature = "serde")]
use core::fmt;
#[cfg(feature = "serde")]
use serde::{
de::{self, Visitor},
Deserialize, Serialize, Serializer,
};

#[cfg(test)]
use serde_test::{assert_tokens, Token};

use crate::error::Error;
use crate::ordinal::*;
use crate::queries::*;
use crate::time_unit::*;
Expand Down Expand Up @@ -522,13 +535,80 @@ fn days_in_month(month: Ordinal, year: Ordinal) -> u32 {
}
}

#[cfg(feature = "serde")]
struct ScheduleVisitor;
#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for ScheduleVisitor {
type Value = Schedule;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a valid cron expression")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match Schedule::from_str(v) {
Ok(value) => Ok(value.into()),
Err(err) => Err(de::Error::custom(err)),
}
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: de::Error,
{
self.visit_str(&v)
}
}

#[cfg(feature = "serde")]
impl Serialize for Schedule {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}

impl<'de> Deserialize<'de> for Schedule {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_string(ScheduleVisitor)
}
}

#[cfg(test)]
mod test {
use chrono::Duration;

use super::*;
use std::str::FromStr;

#[cfg(feature = "serde")]
#[test]
fn test_ser_de_schedule() {
let cron_value = Schedule::from_str("* * * * * * *").expect("Valid Format");
assert_tokens(&cron_value, &[Token::String("* * * * * * *")])
}

#[cfg(feature = "serde")]
#[test]
fn test_invalid_ser_de_schedule() {
use serde_test::assert_de_tokens_error;

assert_de_tokens_error::<Schedule>(
&[Token::String(
"definitively an invalid value for a cron schedule!",
)],
"Invalid expression: Invalid cron expression.",
);
}

#[test]
fn test_next_and_prev_from() {
let expression = "0 5,13,40-42 17 1 Jan *";
Expand Down Expand Up @@ -556,9 +636,7 @@ mod test {
#[test]
fn test_next_after_past_date_next_year() {
// Schedule after 2021-10-27
let starting_point = Utc
.with_ymd_and_hms(2021, 10, 27, 0, 0, 0)
.unwrap();
let starting_point = Utc.with_ymd_and_hms(2021, 10, 27, 0, 0, 0).unwrap();
LeoniePhiline marked this conversation as resolved.
Show resolved Hide resolved

// Triggers on 2022-06-01. Note that the month and day are smaller than
// the month and day in `starting_point`.
Expand Down