Debian Codegraph @

third_party/rust/headers/src/util/seconds.rs

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