Skip to main content

expressive_cron/
types.rs

1use std::fmt::Display;
2
3/// Conversion from a Rust value into a single cron-expression field.
4///
5/// Implemented for integers (`u32`, `i32`), strings (`&str`, `String`),
6/// fixed-size arrays and slices (which are joined with commas), and [`DayOfWeek`].
7///
8/// Methods that accept a cron field — such as [`Cron::hourly_at`][crate::Cron::hourly_at] — take any `impl IntoCronValue`,
9/// so `hourly_at(37)`, `hourly_at("*/10")`, and `hourly_at([15, 30, 45])` all work.
10pub trait IntoCronValue {
11	/// Render the value as a cron-field string (e.g. `"37"`, `"*/10"`, `"15,30,45"`).
12	fn into_cron_value(self) -> String;
13}
14
15/// A day of the week, using cron's numeric convention where Sunday is `0` and Saturday is `6`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum DayOfWeek {
18	Sunday = 0,
19	Monday = 1,
20	Tuesday = 2,
21	Wednesday = 3,
22	Thursday = 4,
23	Friday = 5,
24	Saturday = 6,
25}
26
27impl IntoCronValue for DayOfWeek {
28	fn into_cron_value(self) -> String {
29		(self as u32).to_string()
30	}
31}
32
33impl IntoCronValue for u32 {
34	fn into_cron_value(self) -> String {
35		self.to_string()
36	}
37}
38
39impl IntoCronValue for i32 {
40	fn into_cron_value(self) -> String {
41		self.to_string()
42	}
43}
44
45impl IntoCronValue for &str {
46	fn into_cron_value(self) -> String {
47		self.to_string()
48	}
49}
50
51impl IntoCronValue for String {
52	fn into_cron_value(self) -> String {
53		self
54	}
55}
56
57impl<T: Display> IntoCronValue for &[T] {
58	fn into_cron_value(self) -> String {
59		self.iter()
60			.map(ToString::to_string)
61			.collect::<Vec<_>>()
62			.join(",")
63	}
64}
65
66impl<T: Display, const N: usize> IntoCronValue for [T; N] {
67	fn into_cron_value(self) -> String {
68		self.iter()
69			.map(ToString::to_string)
70			.collect::<Vec<_>>()
71			.join(",")
72	}
73}
74
75impl<T: Display, const N: usize> IntoCronValue for &[T; N] {
76	fn into_cron_value(self) -> String {
77		self.iter()
78			.map(ToString::to_string)
79			.collect::<Vec<_>>()
80			.join(",")
81	}
82}