time.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*! Time structures.
  2. The `time` module contains structures used to represent both
  3. absolute and relative time.
  4. - [Instant] is used to represent absolute time.
  5. - [Duration] is used to represet relative time.
  6. [Instant]: struct.Instant.html
  7. [Duration]: struct.Duration.html
  8. */
  9. use core::{ops, fmt};
  10. /// A representation of an absolute time value.
  11. ///
  12. /// The `Instant` type is a wrapper around a `i64` value that
  13. /// represents a number of milliseconds, monotonically increasing
  14. /// since an arbitrary moment in time, such as system startup.
  15. ///
  16. /// * A value of `0` is inherently arbitrary.
  17. /// * A value less than `0` indicates a time before the starting
  18. /// point.
  19. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
  20. pub struct Instant {
  21. millis: i64,
  22. }
  23. impl Instant {
  24. /// Create a new `Instant` from a number of milliseconds.
  25. pub fn from_millis(millis: i64) -> Instant {
  26. Instant { millis }
  27. }
  28. /// Create a new `Instant` from the current `SystemTime`.
  29. #[cfg(feature = "std")]
  30. pub fn now() -> Result<Instant, ::std::time::SystemTimeError> {
  31. Self::from_system_time(::std::time::SystemTime::now())
  32. }
  33. /// Create a new `Instant` from a `SystemTime`.
  34. #[cfg(feature = "std")]
  35. pub fn from_system_time(time: ::std::time::SystemTime) -> Result<Instant, ::std::time::SystemTimeError> {
  36. let n = ::std::time::UNIX_EPOCH.duration_since(time)?;
  37. Ok(Self::from_millis(n.as_secs() as i64 * 1000 + (n.subsec_nanos() / 1_000_000) as i64))
  38. }
  39. /// The fractional number of milliseconds that have passed
  40. /// since the beginning of time.
  41. pub fn millis(&self) -> i64 {
  42. self.millis % 1000
  43. }
  44. /// The number of whole seconds that have passed since the
  45. /// beginning of time.
  46. pub fn secs(&self) -> i64 {
  47. self.millis / 1000
  48. }
  49. /// The total number of milliseconds that have passed since
  50. /// the biginning of time.
  51. pub fn total_millis(&self) -> i64 {
  52. self.millis
  53. }
  54. }
  55. #[cfg(feature = "std")]
  56. impl Into<::std::time::SystemTime> for Instant {
  57. fn into(self) -> ::std::time::SystemTime {
  58. ::std::time::UNIX_EPOCH + ::std::time::Duration::from_millis(self.millis as u64)
  59. }
  60. }
  61. impl fmt::Display for Instant {
  62. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  63. write!(f, "{}.{}s", self.secs(), self.millis())
  64. }
  65. }
  66. impl ops::Add<Duration> for Instant {
  67. type Output = Instant;
  68. fn add(self, rhs: Duration) -> Instant {
  69. Instant::from_millis(self.millis + rhs.total_millis() as i64)
  70. }
  71. }
  72. impl ops::Sub<Duration> for Instant {
  73. type Output = Instant;
  74. fn sub(self, rhs: Duration) -> Instant {
  75. Instant::from_millis(self.millis - rhs.total_millis() as i64)
  76. }
  77. }
  78. /// A relative amount of time.
  79. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
  80. pub struct Duration {
  81. millis: u64,
  82. }
  83. impl Duration {
  84. /// Create a new `Duration` from a number of milliseconds.
  85. pub fn from_millis(millis: u64) -> Duration {
  86. Duration { millis }
  87. }
  88. /// The fractional number of milliseconds in this `Duration`.
  89. pub fn millis(&self) -> u64 {
  90. self.millis % 1000
  91. }
  92. /// The number of whole seconds in this `Duration`.
  93. pub fn secs(&self) -> u64 {
  94. self.millis / 1000
  95. }
  96. /// The total number of milliseconds in this `Duration`.
  97. pub fn total_millis(&self) -> u64 {
  98. self.millis
  99. }
  100. }
  101. impl fmt::Display for Duration {
  102. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  103. write!(f, "{}.{}s", self.secs(), self.millis())
  104. }
  105. }
  106. impl ops::Add<Duration> for Duration {
  107. type Output = Duration;
  108. fn add(self, rhs: Duration) -> Duration {
  109. Duration::from_millis(self.millis + rhs.total_millis())
  110. }
  111. }
  112. impl ops::AddAssign<Duration> for Duration {
  113. fn add_assign(&mut self, rhs: Duration) {
  114. self.millis += rhs.total_millis();
  115. }
  116. }
  117. impl ops::Sub<Duration> for Duration {
  118. type Output = Duration;
  119. fn sub(self, rhs: Duration) -> Duration {
  120. Duration::from_millis(
  121. self.millis.checked_sub(rhs.total_millis()).expect("overflow when subtracting durations"))
  122. }
  123. }
  124. impl ops::SubAssign<Duration> for Duration {
  125. fn sub_assign(&mut self, rhs: Duration) {
  126. self.millis = self.millis.checked_sub(
  127. rhs.total_millis()).expect("overflow when subtracting durations");
  128. }
  129. }
  130. impl ops::Mul<u32> for Duration {
  131. type Output = Duration;
  132. fn mul(self, rhs: u32) -> Duration {
  133. Duration::from_millis(self.millis * rhs as u64)
  134. }
  135. }
  136. impl ops::MulAssign<u32> for Duration {
  137. fn mul_assign(&mut self, rhs: u32) {
  138. self.millis *= rhs as u64;
  139. }
  140. }
  141. impl ops::Div<u32> for Duration {
  142. type Output = Duration;
  143. fn div(self, rhs: u32) -> Duration {
  144. Duration::from_millis(self.millis / rhs as u64)
  145. }
  146. }
  147. impl ops::DivAssign<u32> for Duration {
  148. fn div_assign(&mut self, rhs: u32) {
  149. self.millis /= rhs as u64;
  150. }
  151. }
  152. #[cfg(feature = "std")]
  153. impl From<::std::time::Duration> for Duration {
  154. fn from(other: ::std::time::Duration) -> Duration {
  155. Duration::from_millis(
  156. other.as_secs() * 1000 + (other.subsec_nanos() / 1_000_000) as u64
  157. )
  158. }
  159. }
  160. #[cfg(feature = "std")]
  161. impl Into<::std::time::Duration> for Duration {
  162. fn into(self) -> ::std::time::Duration {
  163. ::std::time::Duration::from_millis(
  164. self.total_millis()
  165. )
  166. }
  167. }
  168. #[cfg(test)]
  169. mod test {
  170. use super::*;
  171. #[test]
  172. fn test_instant_ops() {
  173. // std::ops::Add
  174. assert_eq!(Instant::from_millis(4) + Duration::from_millis(6), Instant::from_millis(10));
  175. // std::ops::Sub
  176. assert_eq!(Instant::from_millis(7) - Duration::from_millis(5), Instant::from_millis(2));
  177. }
  178. #[test]
  179. fn test_instant_getters() {
  180. let instant = Instant::from_millis(5674);
  181. assert_eq!(instant.secs(), 5);
  182. assert_eq!(instant.millis(), 674);
  183. assert_eq!(instant.total_millis(), 5674);
  184. }
  185. #[test]
  186. fn test_instant_display() {
  187. assert_eq!(format!("{}", Instant::from_millis(5674)), "5.674s");
  188. assert_eq!(format!("{}", Instant::from_millis(5000)), "5.0s");
  189. }
  190. #[test]
  191. #[cfg(feature = "std")]
  192. fn test_instant_conversions() {
  193. let mut epoc: ::std::time::SystemTime = Instant::from_millis(0).into();
  194. assert_eq!(Instant::from_system_time(::std::time::UNIX_EPOCH).unwrap(),
  195. Instant::from_millis(0));
  196. assert_eq!(epoc, ::std::time::UNIX_EPOCH);
  197. epoc = Instant::from_millis(2085955200 * 1000).into();
  198. assert_eq!(epoc, ::std::time::UNIX_EPOCH + ::std::time::Duration::from_secs(2085955200));
  199. }
  200. #[test]
  201. fn test_duration_ops() {
  202. // std::ops::Add
  203. assert_eq!(Duration::from_millis(40) + Duration::from_millis(2), Duration::from_millis(42));
  204. // std::ops::Sub
  205. assert_eq!(Duration::from_millis(555) - Duration::from_millis(42), Duration::from_millis(513));
  206. // std::ops::Mul
  207. assert_eq!(Duration::from_millis(13) * 22, Duration::from_millis(286));
  208. // std::ops::Div
  209. assert_eq!(Duration::from_millis(53) / 4, Duration::from_millis(13));
  210. }
  211. #[test]
  212. fn test_duration_assign_ops() {
  213. let mut duration = Duration::from_millis(4735);
  214. duration += Duration::from_millis(1733);
  215. assert_eq!(duration, Duration::from_millis(6468));
  216. duration -= Duration::from_millis(1234);
  217. assert_eq!(duration, Duration::from_millis(5234));
  218. duration *= 4;
  219. assert_eq!(duration, Duration::from_millis(20936));
  220. duration /= 5;
  221. assert_eq!(duration, Duration::from_millis(4187));
  222. }
  223. #[test]
  224. #[should_panic(expected = "overflow when subtracting durations")]
  225. fn test_sub_from_zero_overflow() {
  226. Duration::from_millis(0) - Duration::from_millis(1);
  227. }
  228. #[test]
  229. #[should_panic(expected = "attempt to divide by zero")]
  230. fn test_div_by_zero() {
  231. Duration::from_millis(4) / 0;
  232. }
  233. #[test]
  234. fn test_duration_getters() {
  235. let instant = Duration::from_millis(4934);
  236. assert_eq!(instant.secs(), 4);
  237. assert_eq!(instant.millis(), 934);
  238. assert_eq!(instant.total_millis(), 4934);
  239. }
  240. #[test]
  241. #[cfg(feature = "std")]
  242. fn test_duration_conversions() {
  243. let mut std_duration = ::std::time::Duration::from_millis(4934);
  244. let duration: Duration = std_duration.into();
  245. assert_eq!(duration, Duration::from_millis(4934));
  246. assert_eq!(Duration::from(std_duration), Duration::from_millis(4934));
  247. std_duration = duration.into();
  248. assert_eq!(std_duration, ::std::time::Duration::from_millis(4934));
  249. }
  250. }