1use std::str::FromStr;
2use std::ops::Deref;
3use std::fmt;
4use std::time::{Duration as StdDuration, SystemTime};
5
6use crate::duration::{self, parse_duration, format_duration};
7use crate::date::{self, parse_rfc3339_weak, format_rfc3339};
8
9/// A wrapper for duration that has `FromStr` implementation
10///
11/// This is useful if you want to use it somewhere where `FromStr` is
12/// expected.
13///
14/// See `parse_duration` for the description of the format.
15///
16/// # Example
17///
18/// ```
19/// use std::time::Duration;
20/// let x: Duration;
21/// x = "12h 5min 2ns".parse::<humantime::Duration>().unwrap().into();
22/// assert_eq!(x, Duration::new(12*3600 + 5*60, 2))
23/// ```
24///
25#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
26pub struct Duration(StdDuration);
27
28/// A wrapper for SystemTime that has `FromStr` implementation
29///
30/// This is useful if you want to use it somewhere where `FromStr` is
31/// expected.
32///
33/// See `parse_rfc3339_weak` for the description of the format. The "weak"
34/// format is used as it's more pemissive for human input as this is the
35/// expected use of the type (e.g. command-line parsing).
36///
37/// # Example
38///
39/// ```
40/// use std::time::SystemTime;
41/// let x: SystemTime;
42/// x = "2018-02-16T00:31:37Z".parse::<humantime::Timestamp>().unwrap().into();
43/// assert_eq!(humantime::format_rfc3339(x).to_string(), "2018-02-16T00:31:37Z");
44/// ```
45///
46#[derive(Debug, PartialEq, Eq, Clone)]
47pub struct Timestamp(SystemTime);
48
49impl AsRef<StdDuration> for Duration {
50 fn as_ref(&self) -> &StdDuration { &self.0 }
51}
52
53impl Deref for Duration {
54 type Target = StdDuration;
55 fn deref(&self) -> &StdDuration { &self.0 }
56}
57
58impl Into<StdDuration> for Duration {
59 fn into(self) -> StdDuration { self.0 }
60}
61
62impl From<StdDuration> for Duration {
63 fn from(dur: StdDuration) -> Duration { Duration(dur) }
64}
65
66impl FromStr for Duration {
67 type Err = duration::Error;
68 fn from_str(s: &str) -> Result<Duration, Self::Err> {
69 parse_duration(s).map(op:Duration)
70 }
71}
72
73impl fmt::Display for Duration {
74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 format_duration(self.0).fmt(f)
76 }
77}
78
79impl AsRef<SystemTime> for Timestamp {
80 fn as_ref(&self) -> &SystemTime { &self.0 }
81}
82
83impl Deref for Timestamp {
84 type Target = SystemTime;
85 fn deref(&self) -> &SystemTime { &self.0 }
86}
87
88impl Into<SystemTime> for Timestamp {
89 fn into(self) -> SystemTime { self.0 }
90}
91
92impl From<SystemTime> for Timestamp {
93 fn from(dur: SystemTime) -> Timestamp { Timestamp(dur) }
94}
95
96impl FromStr for Timestamp {
97 type Err = date::Error;
98 fn from_str(s: &str) -> Result<Timestamp, Self::Err> {
99 parse_rfc3339_weak(s).map(op:Timestamp)
100 }
101}
102
103impl fmt::Display for Timestamp {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 format_rfc3339(self.0).fmt(f)
106 }
107}
108