1use std::fmt;
2use std::time::Duration;
3
4use http::HeaderValue;
5
6use crate::util::IterExt;
7use crate::Error;
8
9#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub(crate) struct Seconds(Duration);
11
12impl Seconds {
13 pub(crate) fn from_val(val: &HeaderValue) -> Option<Self> {
14 let secs = val.to_str().ok()?.parse().ok()?;
15
16 Some(Self::from_secs(secs))
17 }
18
19 pub(crate) fn from_secs(secs: u64) -> Self {
20 Self::from(Duration::from_secs(secs))
21 }
22
23 pub(crate) fn as_u64(&self) -> u64 {
24 self.0.as_secs()
25 }
26}
27
28impl super::TryFromValues for Seconds {
29 fn try_from_values<'i, I>(values: &mut I) -> Result<Self, Error>
30 where
31 I: Iterator<Item = &'i HeaderValue>,
32 {
33 values
34 .just_one()
35 .and_then(Seconds::from_val)
36 .ok_or_else(Error::invalid)
37 }
38}
39
40impl<'a> From<&'a Seconds> for HeaderValue {
41 fn from(secs: &'a Seconds) -> HeaderValue {
42 secs.0.as_secs().into()
43 }
44}
45
46impl From<Duration> for Seconds {
47 fn from(dur: Duration) -> Seconds {
48 debug_assert!(dur.subsec_nanos() == 0);
49 Seconds(dur)
50 }
51}
52
53impl From<Seconds> for Duration {
54 fn from(secs: Seconds) -> Duration {
55 secs.0
56 }
57}
58
59impl fmt::Debug for Seconds {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 write!(f, "{}s", self.0.as_secs())
62 }
63}
64
65impl fmt::Display for Seconds {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67 fmt::Display::fmt(&self.0.as_secs(), f)
68 }
69}