webpki/
time.rs

1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15//! Conversions into the library's time type.
16
17/// The time type.
18///
19/// Internally this is merely a UNIX timestamp: a count of non-leap
20/// seconds since the start of 1970.  This type exists to assist
21/// unit-of-measure correctness.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
23pub struct Time(u64);
24
25impl Time {
26    /// Create a `webpki::Time` from a unix timestamp.
27    ///
28    /// It is usually better to use the less error-prone
29    /// `webpki::Time::try_from(time: std::time::SystemTime)` instead when
30    /// `std::time::SystemTime` is available (when `#![no_std]` isn't being
31    /// used).
32    #[allow(clippy::must_use_candidate)]
33    pub fn from_seconds_since_unix_epoch(secs: u64) -> Self {
34        Self(secs)
35    }
36}
37
38#[cfg(feature = "std")]
39#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
40impl TryFrom<std::time::SystemTime> for Time {
41    type Error = std::time::SystemTimeError;
42
43    /// Create a `webpki::Time` from a `std::time::SystemTime`.
44    ///
45    /// # Example:
46    ///
47    /// Construct a `webpki::Time` from the current system time:
48    ///
49    /// ```
50    /// # extern crate ring;
51    /// # extern crate webpki;
52    /// #
53    /// #![cfg(feature = "std")]
54    /// use std::time::SystemTime;
55    ///
56    /// # fn foo() -> Result<(), std::time::SystemTimeError> {
57    /// let time = webpki::Time::try_from(SystemTime::now())?;
58    /// # Ok(())
59    /// # }
60    /// ```
61    fn try_from(value: std::time::SystemTime) -> Result<Self, Self::Error> {
62        value
63            .duration_since(std::time::UNIX_EPOCH)
64            .map(|d| Self::from_seconds_since_unix_epoch(d.as_secs()))
65    }
66}