expressive-cron 0.1.0

A fluent builder for cron expressions, inspired by Laravel.
Documentation
use std::fmt::Display;

/// Conversion from a Rust value into a single cron-expression field.
///
/// Implemented for integers (`u32`, `i32`), strings (`&str`, `String`),
/// fixed-size arrays and slices (which are joined with commas), and [`DayOfWeek`].
///
/// Methods that accept a cron field — such as [`Cron::hourly_at`][crate::Cron::hourly_at] — take any `impl IntoCronValue`,
/// so `hourly_at(37)`, `hourly_at("*/10")`, and `hourly_at([15, 30, 45])` all work.
pub trait IntoCronValue {
	/// Render the value as a cron-field string (e.g. `"37"`, `"*/10"`, `"15,30,45"`).
	fn into_cron_value(self) -> String;
}

/// A day of the week, using cron's numeric convention where Sunday is `0` and Saturday is `6`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DayOfWeek {
	Sunday = 0,
	Monday = 1,
	Tuesday = 2,
	Wednesday = 3,
	Thursday = 4,
	Friday = 5,
	Saturday = 6,
}

impl IntoCronValue for DayOfWeek {
	fn into_cron_value(self) -> String {
		(self as u32).to_string()
	}
}

impl IntoCronValue for u32 {
	fn into_cron_value(self) -> String {
		self.to_string()
	}
}

impl IntoCronValue for i32 {
	fn into_cron_value(self) -> String {
		self.to_string()
	}
}

impl IntoCronValue for &str {
	fn into_cron_value(self) -> String {
		self.to_string()
	}
}

impl IntoCronValue for String {
	fn into_cron_value(self) -> String {
		self
	}
}

impl<T: Display> IntoCronValue for &[T] {
	fn into_cron_value(self) -> String {
		self.iter()
			.map(ToString::to_string)
			.collect::<Vec<_>>()
			.join(",")
	}
}

impl<T: Display, const N: usize> IntoCronValue for [T; N] {
	fn into_cron_value(self) -> String {
		self.iter()
			.map(ToString::to_string)
			.collect::<Vec<_>>()
			.join(",")
	}
}

impl<T: Display, const N: usize> IntoCronValue for &[T; N] {
	fn into_cron_value(self) -> String {
		self.iter()
			.map(ToString::to_string)
			.collect::<Vec<_>>()
			.join(",")
	}
}