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#[cfg(feature = "std")]
18use {ring, std};
19
20/// The time type.
21///
22/// Internally this is merely a UNIX timestamp: a count of non-leap
23/// seconds since the start of 1970. This type exists to assist
24/// unit-of-measure correctness.
25#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
26pub struct Time(u64);
27
28impl Time {
29 /// Create a `webpki::Time` from a `std::time::SystemTime`.
30 ///
31 /// This will be replaced with a real `TryFrom<std::time::SystemTime>`
32 /// implementation when `TryFrom` is added to Rust Stable.
33 ///
34 /// # Example:
35 ///
36 /// Construct a `webpki::Time` from the current system time:
37 ///
38 /// ```
39 /// # extern crate ring;
40 /// # extern crate webpki;
41 /// #
42 /// #[cfg(feature = "std")]
43 /// # fn foo() -> Result<(), ring::error::Unspecified> {
44 /// let time = webpki::Time::try_from(std::time::SystemTime::now())?;
45 /// # Ok(())
46 /// # }
47 /// ```
48 #[cfg(feature = "std")]
49 pub fn try_from(time: std::time::SystemTime) -> Result<Time, ring::error::Unspecified> {
50 time.duration_since(std::time::UNIX_EPOCH)
51 .map(|d| Time::from_seconds_since_unix_epoch(d.as_secs()))
52 .map_err(|_| ring::error::Unspecified)
53 }
54
55 /// Create a `webpki::Time` from a unix timestamp.
56 ///
57 /// It is usually better to use the less error-prone
58 /// `webpki::Time::try_from(time: &std::time::SystemTime)` instead when
59 /// `std::time::SystemTime` is available (when `#![no_std]` isn't being
60 /// used).
61 pub fn from_seconds_since_unix_epoch(secs: u64) -> Time { Time(secs) }
62}