time.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 represent relative time.
  6. [Instant]: struct.Instant.html
  7. [Duration]: struct.Duration.html
  8. */
  9. use core::{fmt, ops};
  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. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  21. pub struct Instant {
  22. micros: i64,
  23. }
  24. impl Instant {
  25. pub const ZERO: Instant = Instant::from_micros_const(0);
  26. /// Create a new `Instant` from a number of microseconds.
  27. pub fn from_micros<T: Into<i64>>(micros: T) -> Instant {
  28. Instant {
  29. micros: micros.into(),
  30. }
  31. }
  32. pub const fn from_micros_const(micros: i64) -> Instant {
  33. Instant { micros }
  34. }
  35. /// Create a new `Instant` from a number of milliseconds.
  36. pub fn from_millis<T: Into<i64>>(millis: T) -> Instant {
  37. Instant {
  38. micros: millis.into() * 1000,
  39. }
  40. }
  41. /// Create a new `Instant` from a number of milliseconds.
  42. pub const fn from_millis_const(millis: i64) -> Instant {
  43. Instant {
  44. micros: millis * 1000,
  45. }
  46. }
  47. /// Create a new `Instant` from a number of seconds.
  48. pub fn from_secs<T: Into<i64>>(secs: T) -> Instant {
  49. Instant {
  50. micros: secs.into() * 1000000,
  51. }
  52. }
  53. /// Create a new `Instant` from the current [std::time::SystemTime].
  54. ///
  55. /// See [std::time::SystemTime::now]
  56. ///
  57. /// [std::time::SystemTime]: https://doc.rust-lang.org/std/time/struct.SystemTime.html
  58. /// [std::time::SystemTime::now]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.now
  59. #[cfg(feature = "std")]
  60. pub fn now() -> Instant {
  61. Self::from(::std::time::SystemTime::now())
  62. }
  63. /// The fractional number of milliseconds that have passed
  64. /// since the beginning of time.
  65. pub const fn millis(&self) -> i64 {
  66. self.micros % 1000000 / 1000
  67. }
  68. /// The fractional number of microseconds that have passed
  69. /// since the beginning of time.
  70. pub const fn micros(&self) -> i64 {
  71. self.micros % 1000000
  72. }
  73. /// The number of whole seconds that have passed since the
  74. /// beginning of time.
  75. pub const fn secs(&self) -> i64 {
  76. self.micros / 1000000
  77. }
  78. /// The total number of milliseconds that have passed since
  79. /// the beginning of time.
  80. pub const fn total_millis(&self) -> i64 {
  81. self.micros / 1000
  82. }
  83. /// The total number of milliseconds that have passed since
  84. /// the beginning of time.
  85. pub const fn total_micros(&self) -> i64 {
  86. self.micros
  87. }
  88. }
  89. #[cfg(feature = "std")]
  90. impl From<::std::time::Instant> for Instant {
  91. fn from(other: ::std::time::Instant) -> Instant {
  92. let elapsed = other.elapsed();
  93. Instant::from_micros((elapsed.as_secs() * 1_000000) as i64 + elapsed.subsec_micros() as i64)
  94. }
  95. }
  96. #[cfg(feature = "std")]
  97. impl From<::std::time::SystemTime> for Instant {
  98. fn from(other: ::std::time::SystemTime) -> Instant {
  99. let n = other
  100. .duration_since(::std::time::UNIX_EPOCH)
  101. .expect("start time must not be before the unix epoch");
  102. Self::from_micros(n.as_secs() as i64 * 1000000 + n.subsec_micros() as i64)
  103. }
  104. }
  105. #[cfg(feature = "std")]
  106. impl From<Instant> for ::std::time::SystemTime {
  107. fn from(val: Instant) -> Self {
  108. ::std::time::UNIX_EPOCH + ::std::time::Duration::from_micros(val.micros as u64)
  109. }
  110. }
  111. impl fmt::Display for Instant {
  112. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  113. write!(f, "{}.{}s", self.secs(), self.millis())
  114. }
  115. }
  116. impl ops::Add<Duration> for Instant {
  117. type Output = Instant;
  118. fn add(self, rhs: Duration) -> Instant {
  119. Instant::from_micros(self.micros + rhs.total_micros() as i64)
  120. }
  121. }
  122. impl ops::AddAssign<Duration> for Instant {
  123. fn add_assign(&mut self, rhs: Duration) {
  124. self.micros += rhs.total_micros() as i64;
  125. }
  126. }
  127. impl ops::Sub<Duration> for Instant {
  128. type Output = Instant;
  129. fn sub(self, rhs: Duration) -> Instant {
  130. Instant::from_micros(self.micros - rhs.total_micros() as i64)
  131. }
  132. }
  133. impl ops::SubAssign<Duration> for Instant {
  134. fn sub_assign(&mut self, rhs: Duration) {
  135. self.micros -= rhs.total_micros() as i64;
  136. }
  137. }
  138. impl ops::Sub<Instant> for Instant {
  139. type Output = Duration;
  140. fn sub(self, rhs: Instant) -> Duration {
  141. Duration::from_micros((self.micros - rhs.micros).unsigned_abs())
  142. }
  143. }
  144. /// A relative amount of time.
  145. #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
  146. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  147. pub struct Duration {
  148. micros: u64,
  149. }
  150. impl Duration {
  151. pub const ZERO: Duration = Duration::from_micros(0);
  152. /// Create a new `Duration` from a number of microseconds.
  153. pub const fn from_micros(micros: u64) -> Duration {
  154. Duration { micros }
  155. }
  156. /// Create a new `Duration` from a number of milliseconds.
  157. pub const fn from_millis(millis: u64) -> Duration {
  158. Duration {
  159. micros: millis * 1000,
  160. }
  161. }
  162. /// Create a new `Instant` from a number of seconds.
  163. pub const fn from_secs(secs: u64) -> Duration {
  164. Duration {
  165. micros: secs * 1000000,
  166. }
  167. }
  168. /// The fractional number of milliseconds in this `Duration`.
  169. pub const fn millis(&self) -> u64 {
  170. self.micros / 1000 % 1000
  171. }
  172. /// The fractional number of milliseconds in this `Duration`.
  173. pub const fn micros(&self) -> u64 {
  174. self.micros % 1000000
  175. }
  176. /// The number of whole seconds in this `Duration`.
  177. pub const fn secs(&self) -> u64 {
  178. self.micros / 1000000
  179. }
  180. /// The total number of milliseconds in this `Duration`.
  181. pub const fn total_millis(&self) -> u64 {
  182. self.micros / 1000
  183. }
  184. /// The total number of microseconds in this `Duration`.
  185. pub const fn total_micros(&self) -> u64 {
  186. self.micros
  187. }
  188. }
  189. impl fmt::Display for Duration {
  190. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  191. write!(f, "{}.{:03}s", self.secs(), self.millis())
  192. }
  193. }
  194. impl ops::Add<Duration> for Duration {
  195. type Output = Duration;
  196. fn add(self, rhs: Duration) -> Duration {
  197. Duration::from_micros(self.micros + rhs.total_micros())
  198. }
  199. }
  200. impl ops::AddAssign<Duration> for Duration {
  201. fn add_assign(&mut self, rhs: Duration) {
  202. self.micros += rhs.total_micros();
  203. }
  204. }
  205. impl ops::Sub<Duration> for Duration {
  206. type Output = Duration;
  207. fn sub(self, rhs: Duration) -> Duration {
  208. Duration::from_micros(
  209. self.micros
  210. .checked_sub(rhs.total_micros())
  211. .expect("overflow when subtracting durations"),
  212. )
  213. }
  214. }
  215. impl ops::SubAssign<Duration> for Duration {
  216. fn sub_assign(&mut self, rhs: Duration) {
  217. self.micros = self
  218. .micros
  219. .checked_sub(rhs.total_micros())
  220. .expect("overflow when subtracting durations");
  221. }
  222. }
  223. impl ops::Mul<u32> for Duration {
  224. type Output = Duration;
  225. fn mul(self, rhs: u32) -> Duration {
  226. Duration::from_micros(self.micros * rhs as u64)
  227. }
  228. }
  229. impl ops::MulAssign<u32> for Duration {
  230. fn mul_assign(&mut self, rhs: u32) {
  231. self.micros *= rhs as u64;
  232. }
  233. }
  234. impl ops::Div<u32> for Duration {
  235. type Output = Duration;
  236. fn div(self, rhs: u32) -> Duration {
  237. Duration::from_micros(self.micros / rhs as u64)
  238. }
  239. }
  240. impl ops::DivAssign<u32> for Duration {
  241. fn div_assign(&mut self, rhs: u32) {
  242. self.micros /= rhs as u64;
  243. }
  244. }
  245. impl ops::Shl<u32> for Duration {
  246. type Output = Duration;
  247. fn shl(self, rhs: u32) -> Duration {
  248. Duration::from_micros(self.micros << rhs)
  249. }
  250. }
  251. impl ops::ShlAssign<u32> for Duration {
  252. fn shl_assign(&mut self, rhs: u32) {
  253. self.micros <<= rhs;
  254. }
  255. }
  256. impl ops::Shr<u32> for Duration {
  257. type Output = Duration;
  258. fn shr(self, rhs: u32) -> Duration {
  259. Duration::from_micros(self.micros >> rhs)
  260. }
  261. }
  262. impl ops::ShrAssign<u32> for Duration {
  263. fn shr_assign(&mut self, rhs: u32) {
  264. self.micros >>= rhs;
  265. }
  266. }
  267. impl From<::core::time::Duration> for Duration {
  268. fn from(other: ::core::time::Duration) -> Duration {
  269. Duration::from_micros(other.as_secs() * 1000000 + other.subsec_micros() as u64)
  270. }
  271. }
  272. impl From<Duration> for ::core::time::Duration {
  273. fn from(val: Duration) -> Self {
  274. ::core::time::Duration::from_micros(val.total_micros())
  275. }
  276. }
  277. #[cfg(test)]
  278. mod test {
  279. use super::*;
  280. #[test]
  281. fn test_instant_ops() {
  282. // std::ops::Add
  283. assert_eq!(
  284. Instant::from_millis(4) + Duration::from_millis(6),
  285. Instant::from_millis(10)
  286. );
  287. // std::ops::Sub
  288. assert_eq!(
  289. Instant::from_millis(7) - Duration::from_millis(5),
  290. Instant::from_millis(2)
  291. );
  292. }
  293. #[test]
  294. fn test_instant_getters() {
  295. let instant = Instant::from_millis(5674);
  296. assert_eq!(instant.secs(), 5);
  297. assert_eq!(instant.millis(), 674);
  298. assert_eq!(instant.total_millis(), 5674);
  299. }
  300. #[test]
  301. fn test_instant_display() {
  302. assert_eq!(format!("{}", Instant::from_millis(5674)), "5.674s");
  303. assert_eq!(format!("{}", Instant::from_millis(5000)), "5.0s");
  304. }
  305. #[test]
  306. #[cfg(feature = "std")]
  307. fn test_instant_conversions() {
  308. let mut epoc: ::std::time::SystemTime = Instant::from_millis(0).into();
  309. assert_eq!(
  310. Instant::from(::std::time::UNIX_EPOCH),
  311. Instant::from_millis(0)
  312. );
  313. assert_eq!(epoc, ::std::time::UNIX_EPOCH);
  314. epoc = Instant::from_millis(2085955200i64 * 1000).into();
  315. assert_eq!(
  316. epoc,
  317. ::std::time::UNIX_EPOCH + ::std::time::Duration::from_secs(2085955200)
  318. );
  319. }
  320. #[test]
  321. fn test_duration_ops() {
  322. // std::ops::Add
  323. assert_eq!(
  324. Duration::from_millis(40) + Duration::from_millis(2),
  325. Duration::from_millis(42)
  326. );
  327. // std::ops::Sub
  328. assert_eq!(
  329. Duration::from_millis(555) - Duration::from_millis(42),
  330. Duration::from_millis(513)
  331. );
  332. // std::ops::Mul
  333. assert_eq!(Duration::from_millis(13) * 22, Duration::from_millis(286));
  334. // std::ops::Div
  335. assert_eq!(Duration::from_millis(53) / 4, Duration::from_micros(13250));
  336. }
  337. #[test]
  338. fn test_duration_assign_ops() {
  339. let mut duration = Duration::from_millis(4735);
  340. duration += Duration::from_millis(1733);
  341. assert_eq!(duration, Duration::from_millis(6468));
  342. duration -= Duration::from_millis(1234);
  343. assert_eq!(duration, Duration::from_millis(5234));
  344. duration *= 4;
  345. assert_eq!(duration, Duration::from_millis(20936));
  346. duration /= 5;
  347. assert_eq!(duration, Duration::from_micros(4187200));
  348. }
  349. #[test]
  350. #[should_panic(expected = "overflow when subtracting durations")]
  351. fn test_sub_from_zero_overflow() {
  352. let _ = Duration::from_millis(0) - Duration::from_millis(1);
  353. }
  354. #[test]
  355. #[should_panic(expected = "attempt to divide by zero")]
  356. fn test_div_by_zero() {
  357. let _ = Duration::from_millis(4) / 0;
  358. }
  359. #[test]
  360. fn test_duration_getters() {
  361. let instant = Duration::from_millis(4934);
  362. assert_eq!(instant.secs(), 4);
  363. assert_eq!(instant.millis(), 934);
  364. assert_eq!(instant.total_millis(), 4934);
  365. }
  366. #[test]
  367. fn test_duration_conversions() {
  368. let mut std_duration = ::core::time::Duration::from_millis(4934);
  369. let duration: Duration = std_duration.into();
  370. assert_eq!(duration, Duration::from_millis(4934));
  371. assert_eq!(Duration::from(std_duration), Duration::from_millis(4934));
  372. std_duration = duration.into();
  373. assert_eq!(std_duration, ::core::time::Duration::from_millis(4934));
  374. }
  375. }