duration_str/
lib.rs

1#![doc(
2    html_logo_url = "https://raw.githubusercontent.com/baoyachi/duration-str/master/duration-str.png"
3)]
4//! Parse string to `Duration` .
5//!
6//! The String value unit support for one of:["y","mon","w","d","h","m","s", "ms", "µs", "ns"]
7//!
8//! - y:Year. Support string value: ["y" | "year" | "Y" | "YEAR" | "Year"]. e.g. 1y
9//!
10//! - mon:Month.Support string value: ["mon" | "MON" | "Month" | "month" | "MONTH"]. e.g. 1mon
11//!
12//! - w:Week.Support string value: ["w" | "W" | "Week" | "WEEK" | "week"]. e.g. 1w
13//!
14//! - d:Day.Support string value: ["d" | "D" | "Day" | "DAY" | "day"]. e.g. 1d
15//!
16//! - h:Hour.Support string value: ["h" | "H" | "hr" | "Hour" | "HOUR" | "hour"]. e.g. 1h
17//!
18//! - m:Minute.Support string value: ["m" | "M" | "Minute" | "MINUTE" | "minute" | "min" | "MIN"]. e.g. 1m
19//!
20//! - s:Second.Support string value: ["s" | "S" | "Second" | "SECOND" | "second" | "sec" | "SEC"]. e.g. 1s
21//!
22//! - ms:Millisecond.Support string value: ["ms" | "MS" | "Millisecond" | "MilliSecond" | "MILLISECOND" | "millisecond" | "mSEC" ]. e.g. 1ms
23//!
24//! - µs:Microsecond.Support string value: ["µs" | "µS" | "µsecond" | "us" | "uS" | "usecond" | "Microsecond" | "MicroSecond" | "MICROSECOND" | "microsecond" | "µSEC"]. e.g. 1µs
25//!
26//! - ns:Nanosecond.Support string value: ["ns" | "NS" | "Nanosecond" | "NanoSecond" | "NANOSECOND" | "nanosecond" | "nSEC"]. e.g. 1ns
27//!
28//! Also, `duration_str` support time duration simple evaluation(+,*). See examples below.
29//!
30//! # Example
31//! ```rust
32//! use duration_str::parse;
33//! use std::time::Duration;
34//!
35//! let duration = parse("1d").unwrap();
36//! assert_eq!(duration, Duration::new(24 * 60 * 60, 0));
37//!
38//! let duration = parse("3m+31").unwrap(); //the default duration unit is second.
39//! assert_eq!(duration, Duration::new(211, 0));
40//!
41//! let duration = parse("3m + 31").unwrap(); //the default duration unit is second.
42//! assert_eq!(duration, Duration::new(211, 0));
43//!
44//! let duration = parse("3m + 13s + 29ms").unwrap();
45//! assert_eq!(duration, Duration::new(193, 29 * 1000 * 1000 + 0 + 0));
46//!
47//! let duration = parse("3m + 1s + 29ms +17µs").unwrap();
48//! assert_eq!(
49//!     duration,
50//!     Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
51//! );
52//!
53//! let duration = parse("3m 1s 29ms 17µs").unwrap();
54//! assert_eq!(
55//!     duration,
56//!     Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
57//! );
58//!
59//! let duration = parse("3m1s29ms17us").unwrap();
60//! assert_eq!(
61//!     duration,
62//!     Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
63//! );
64//!
65//! let duration = parse("1m*10").unwrap(); //the default duration unit is second.
66//! assert_eq!(duration, Duration::new(600, 0));
67//!
68//! let duration = parse("1m*10ms").unwrap();
69//! assert_eq!(duration, Duration::new(0, 600 * 1000 * 1000));
70//!
71//! let duration = parse("1m * 1ns").unwrap();
72//! assert_eq!(duration, Duration::new(0, 60));
73//!
74//! let duration = parse("1m * 1m").unwrap();
75//! assert_eq!(duration, Duration::new(3600, 0));
76//! let duration = parse("42µs").unwrap();
77//! assert_eq!(duration,Duration::from_micros(42));
78//! ```
79//!
80//! # deserialize to std::time::Duration
81//!
82#![cfg_attr(not(feature = "serde"), doc = "This requires the `serde` feature")]
83//!
84#![cfg_attr(not(feature = "serde"), doc = "```ignore")]
85#![cfg_attr(feature = "serde", doc = "```rust")]
86//! use duration_str::deserialize_duration;
87//! use serde::*;
88//! use std::time::Duration;
89//!
90//! /// Uses `deserialize_duration`.
91//! #[derive(Debug, Deserialize)]
92//! struct Config {
93//!     #[serde(deserialize_with = "deserialize_duration")]
94//!     time_ticker: Duration,
95//! }
96//!
97//! fn needless_main() {
98//!     let json = r#"{"time_ticker":"1m+30"}"#;
99//!     let config: Config = serde_json::from_str(json).unwrap();
100//!     assert_eq!(config.time_ticker, Duration::new(60 + 30, 0));
101//!
102//!     let json = r#"{"time_ticker":"1m+30s"}"#;
103//!     let config: Config = serde_json::from_str(json).unwrap();
104//!     assert_eq!(config.time_ticker, Duration::new(60 + 30, 0));
105//!
106//!     let json = r#"{"time_ticker":"3m 1s 29ms 17µs"}"#;
107//!     let config: Config = serde_json::from_str(json).unwrap();
108//!     assert_eq!(
109//!         config.time_ticker,
110//!         Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
111//!     );
112//!
113//!     let json = r#"{"time_ticker":"3m1s29ms17us"}"#;
114//!     let config: Config = serde_json::from_str(json).unwrap();
115//!     assert_eq!(
116//!         config.time_ticker,
117//!         Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
118//!     );
119//! }
120//! ```
121//!
122//! # deserialize to chrono::Duration
123#![cfg_attr(
124    not(all(feature = "chrono", feature = "serde")),
125    doc = "This requires both the `chrono` and `serde` features"
126)]
127//!
128#![cfg_attr(not(all(feature = "chrono", feature = "serde")), doc = "```ignore")]
129#![cfg_attr(all(feature = "chrono", feature = "serde"), doc = "```rust")]
130//! use chrono::Duration;
131//! use duration_str::deserialize_duration_chrono;
132//! use serde::*;
133//!
134//! #[derive(Debug, Deserialize)]
135//! struct Config {
136//!     #[serde(deserialize_with = "deserialize_duration_chrono")]
137//!     time_ticker: Duration,
138//! }
139//!
140//! fn needless_main() {
141//!     let json = r#"{"time_ticker":"1m+30"}"#;
142//!     let config: Config = serde_json::from_str(json).unwrap();
143//!     assert_eq!(config.time_ticker, Duration::seconds(60 + 30));
144//!
145//!     let json = r#"{"time_ticker":"1m+30s"}"#;
146//!     let config: Config = serde_json::from_str(json).unwrap();
147//!     assert_eq!(config.time_ticker, Duration::seconds(60 + 30));
148//!
149//!     let json = r#"{"time_ticker":"3m 1s 29ms 17µs"}"#;
150//!     let config: Config = serde_json::from_str(json).unwrap();
151//!     assert_eq!(
152//!         config.time_ticker,
153//!         Duration::minutes(3)
154//!             + Duration::seconds(1)
155//!             + Duration::milliseconds(29)
156//!             + Duration::microseconds(17)
157//!     );
158//!
159//!     let json = r#"{"time_ticker":"3m1s29ms17us"}"#;
160//!     let config: Config = serde_json::from_str(json).unwrap();
161//!     assert_eq!(
162//!         config.time_ticker,
163//!         Duration::minutes(3)
164//!             + Duration::seconds(1)
165//!             + Duration::milliseconds(29)
166//!             + Duration::microseconds(17)
167//!     );
168//! }
169//! ```
170
171mod error;
172pub(crate) mod ext;
173pub(crate) mod macros;
174mod parser;
175#[cfg(feature = "serde")]
176mod serde;
177mod unit;
178
179pub use parser::parse;
180#[cfg(feature = "serde")]
181pub use serde::*;
182use std::fmt::{Debug, Display};
183
184use rust_decimal::prelude::ToPrimitive;
185use rust_decimal::Decimal;
186use std::str::FromStr;
187use std::time::Duration;
188
189pub use crate::error::DError;
190use crate::unit::TimeUnit;
191#[cfg(feature = "chrono")]
192pub use naive_date::{
193    after_naive_date, after_naive_date_time, before_naive_date, before_naive_date_time,
194};
195
196pub use ext::*;
197
198pub type DResult<T> = Result<T, DError>;
199
200const ONE_MICROSECOND_NANOSECOND: u64 = 1000;
201const ONE_MILLISECOND_NANOSECOND: u64 = 1000 * ONE_MICROSECOND_NANOSECOND;
202const ONE_SECOND_NANOSECOND: u64 = 1000 * ONE_MILLISECOND_NANOSECOND;
203const ONE_MINUTE_NANOSECOND: u64 = 60 * ONE_SECOND_NANOSECOND;
204const ONE_HOUR_NANOSECOND: u64 = 60 * ONE_MINUTE_NANOSECOND;
205const ONE_DAY_NANOSECOND: u64 = 24 * ONE_HOUR_NANOSECOND;
206const ONE_WEEK_NANOSECOND: u64 = 7 * ONE_DAY_NANOSECOND;
207const ONE_MONTH_NANOSECOND: u64 = 30 * ONE_DAY_NANOSECOND;
208const ONE_YEAR_NANOSECOND: u64 = 365 * ONE_DAY_NANOSECOND;
209
210// const ONE_SECOND_DECIMAL: Decimal = 1_000_000_000.into();
211fn one_second_decimal() -> Decimal {
212    1_000_000_000.into()
213}
214
215const PLUS: &str = "+";
216const STAR: &str = "*";
217
218trait ExpectErr {
219    type Output: Debug;
220
221    fn expect_val() -> Self::Output;
222    fn expect_err<S: AsRef<str> + Display>(s: S) -> String;
223}
224
225#[derive(Debug, Eq, PartialEq, Clone)]
226enum CondUnit {
227    Plus,
228    Star,
229}
230
231impl FromStr for CondUnit {
232    type Err = String;
233
234    fn from_str(s: &str) -> Result<Self, Self::Err> {
235        match s {
236            "+" => Ok(CondUnit::Plus),
237            "*" => Ok(CondUnit::Star),
238            _ => Err(Self::expect_err(s)),
239        }
240    }
241}
242
243impl ExpectErr for CondUnit {
244    type Output = [char; 2];
245
246    fn expect_val() -> Self::Output {
247        ['+', '*']
248    }
249
250    fn expect_err<S: AsRef<str> + Display>(s: S) -> String {
251        format!("expect one of:{:?}, but find:{}", Self::expect_val(), s)
252    }
253}
254
255impl CondUnit {
256    fn init() -> (Self, u64) {
257        (CondUnit::Star, ONE_SECOND_NANOSECOND)
258    }
259
260    fn contain(c: char) -> bool {
261        Self::expect_val().contains(&c)
262    }
263
264    fn change_duration(&self) -> u64 {
265        match self {
266            CondUnit::Plus => 0,
267            CondUnit::Star => ONE_SECOND_NANOSECOND,
268        }
269    }
270
271    fn calc(&self, x: u64, y: u64) -> DResult<Duration> {
272        let nano_second = match self {
273            CondUnit::Plus => x.checked_add(y).ok_or(DError::OverflowError)?,
274            CondUnit::Star => {
275                let x: Decimal = x.into();
276                let y: Decimal = y.into();
277                let ret = (x / one_second_decimal())
278                    .checked_mul(y / one_second_decimal())
279                    .ok_or(DError::OverflowError)?
280                    .checked_mul(one_second_decimal())
281                    .ok_or(DError::OverflowError)?;
282                ret.to_u64().ok_or(DError::OverflowError)?
283            }
284        };
285        Ok(Duration::from_nanos(nano_second))
286    }
287}
288
289trait Calc<T> {
290    fn calc(&self) -> DResult<T>;
291}
292
293impl Calc<(CondUnit, u64)> for Vec<(&str, CondUnit, TimeUnit)> {
294    fn calc(&self) -> DResult<(CondUnit, u64)> {
295        let (mut init_cond, mut init_duration) = CondUnit::init();
296        for (index, (val, cond, time_unit)) in self.iter().enumerate() {
297            if index == 0 {
298                init_cond = cond.clone();
299                init_duration = init_cond.change_duration();
300            } else if &init_cond != cond {
301                return Err(DError::ParseError(format!(
302                    "not support '{}' with '{}' calculate",
303                    init_cond, cond
304                )));
305            }
306            match init_cond {
307                CondUnit::Plus => {
308                    init_duration = init_duration
309                        .checked_add(time_unit.duration(val)?)
310                        .ok_or(DError::OverflowError)?;
311                }
312                CondUnit::Star => {
313                    let time: Decimal = time_unit.duration(val)?.into();
314                    let i = time / one_second_decimal();
315                    let mut init: Decimal = init_duration.into();
316                    init = init.checked_mul(i).ok_or(DError::OverflowError)?;
317                    init_duration = init.to_u64().ok_or(DError::OverflowError)?;
318                }
319            }
320        }
321        Ok((init_cond, init_duration))
322    }
323}
324
325impl Display for CondUnit {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        let str = match self {
328            Self::Plus => PLUS.to_string(),
329            Self::Star => STAR.to_string(),
330        };
331        write!(f, "{}", str)
332    }
333}
334
335/// convert `Into<String>` to `std::time::Duration`
336///
337/// # Example
338///
339/// ```rust
340/// use duration_str::parse;
341/// use std::time::Duration;
342///
343/// // supports units
344/// let duration = parse("1d").unwrap();
345/// assert_eq!(duration,Duration::new(24*60*60,0));
346///
347/// // supports addition
348/// let duration = parse("3m+31").unwrap();
349/// assert_eq!(duration,Duration::new(211,0));
350///
351/// // spaces are optional
352/// let duration = parse("3m + 31").unwrap();
353/// assert_eq!(duration,Duration::new(211,0));
354///
355/// // plus sign is optional
356/// let duration = parse("3m  31").unwrap();
357/// assert_eq!(duration,Duration::new(211,0));
358///
359/// // both plus and spaces are optional
360/// let duration = parse("3m31").unwrap();
361/// assert_eq!(duration,Duration::new(211,0));
362///
363/// // supports multiplication
364/// let duration = parse("1m*10").unwrap();
365/// assert_eq!(duration,Duration::new(600,0));
366///
367/// // spaces are optional
368/// let duration = parse("1m * 10").unwrap();
369/// assert_eq!(duration,Duration::new(600,0));
370/// ```
371pub fn parse_std(input: impl AsRef<str>) -> Result<Duration, String> {
372    parse(input.as_ref())
373}
374
375/// convert `Into<String>` to `chrono::Duration`
376///
377/// # Example
378///
379/// ```rust
380/// use duration_str::parse_chrono;
381/// use chrono::Duration;
382///
383/// // supports units
384/// let duration = parse_chrono("1d").unwrap();
385/// assert_eq!(duration,Duration::seconds(24*60*60));
386///
387/// // supports addition
388/// let duration = parse_chrono("3m+31").unwrap();
389/// assert_eq!(duration,Duration::seconds(211));
390///
391/// // spaces are optional
392/// let duration = parse_chrono("3m + 31").unwrap();
393/// assert_eq!(duration,Duration::seconds(211));
394///
395/// // plus sign is optional
396/// let duration = parse_chrono("3m  31").unwrap();
397/// assert_eq!(duration,Duration::seconds(211));
398///
399/// // both plus and spaces are optional
400/// let duration = parse_chrono("3m31").unwrap();
401/// assert_eq!(duration,Duration::seconds(211));
402///
403/// // supports multiplication
404/// let duration = parse_chrono("1m*10").unwrap();
405/// assert_eq!(duration,Duration::seconds(600));
406///
407/// // spaces are optional
408/// let duration = parse_chrono("1m * 10").unwrap();
409/// assert_eq!(duration,Duration::seconds(600));
410/// ```
411#[cfg(feature = "chrono")]
412pub fn parse_chrono(input: impl AsRef<str>) -> Result<chrono::Duration, String> {
413    let std_duration = parse_std(input)?;
414    let duration = chrono::Duration::from_std(std_duration).map_err(|e| e.to_string())?;
415    Ok(duration)
416}
417
418/// convert `Into<String>` to `time::Duration`
419///
420/// # Example
421///
422/// ```rust
423/// use duration_str::parse_time;
424/// use time::Duration;
425///
426/// // supports units
427/// let duration = parse_time("1d").unwrap();
428/// assert_eq!(duration,Duration::seconds(24*60*60));
429///
430/// // supports addition
431/// let duration = parse_time("3m+31").unwrap();
432/// assert_eq!(duration,Duration::seconds(211));
433///
434/// // spaces are optional
435/// let duration = parse_time("3m + 31").unwrap();
436/// assert_eq!(duration,Duration::seconds(211));
437///
438/// // plus sign is optional
439/// let duration = parse_time("3m  31").unwrap();
440/// assert_eq!(duration,Duration::seconds(211));
441///
442/// // both plus and spaces are optional
443/// let duration = parse_time("3m31").unwrap();
444/// assert_eq!(duration,Duration::seconds(211));
445///
446/// // supports multiplication
447/// let duration = parse_time("1m*10").unwrap();
448/// assert_eq!(duration,Duration::seconds(600));
449///
450/// // spaces are optional
451/// let duration = parse_time("1m * 10").unwrap();
452/// assert_eq!(duration,Duration::seconds(600));
453/// ```
454#[cfg(feature = "time")]
455pub fn parse_time(input: impl AsRef<str>) -> Result<time::Duration, String> {
456    let std_duration = parse_std(input)?;
457    let duration = time::Duration::try_from(std_duration).map_err(|e| e.to_string())?;
458    Ok(duration)
459}
460
461#[cfg(feature = "chrono")]
462mod naive_date {
463    use crate::parse_chrono;
464    use chrono::Utc;
465
466    #[allow(dead_code)]
467    pub enum TimeHistory {
468        Before,
469        After,
470    }
471
472    #[cfg(feature = "chrono")]
473    pub fn calc_naive_date_time(
474        input: impl AsRef<str>,
475        history: TimeHistory,
476    ) -> Result<chrono::NaiveDateTime, String> {
477        let duration = parse_chrono(input)?;
478        let time = match history {
479            TimeHistory::Before => (Utc::now() - duration).naive_utc(),
480            TimeHistory::After => (Utc::now() + duration).naive_utc(),
481        };
482        Ok(time)
483    }
484
485    macro_rules! gen_naive_date_func {
486        ($date_time:ident,$date:ident,$history:expr) => {
487            #[allow(dead_code)]
488            #[cfg(feature = "chrono")]
489            pub fn $date_time(input: impl AsRef<str>) -> Result<chrono::NaiveDateTime, String> {
490                calc_naive_date_time(input, $history)
491            }
492
493            #[allow(dead_code)]
494            #[cfg(feature = "chrono")]
495            pub fn $date(input: impl AsRef<str>) -> Result<chrono::NaiveDate, String> {
496                let date: chrono::NaiveDateTime = calc_naive_date_time(input, $history)?;
497                Ok(date.date())
498            }
499        };
500    }
501
502    gen_naive_date_func!(
503        before_naive_date_time,
504        before_naive_date,
505        TimeHistory::Before
506    );
507
508    gen_naive_date_func!(after_naive_date_time, after_naive_date, TimeHistory::After);
509}