time.rs 13 KB

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