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