1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
//! Duration types/units creation and conversion. use crate::{numerical_duration::TimeRep, Period}; use core::{convert::TryFrom, fmt, mem::size_of, prelude::v1::*}; use num::{traits::WrappingSub, Bounded, CheckedDiv}; /// A duration of time with generic storage /// /// Each implementation defines a constant fraction/ratio representing the period of the LSbit /// /// # Implementation Example /// ```rust,no_run /// # use embedded_time::{Duration, Period, TimeRep}; /// # use core::{fmt, fmt::Formatter}; /// # /// #[derive(Copy, Clone)] /// struct Milliseconds<T: TimeRep>(pub T); /// /// impl<T: TimeRep> Duration for Milliseconds<T> { /// type Rep = T; // set the storage type /// const PERIOD: Period = Period::new_raw(1, 1_000); // set LSbit period to 1 millisecond /// /// fn new(value: Self::Rep) -> Self { /// Self(value) /// } /// /// fn count(self) -> Self::Rep { /// self.0 /// } /// } /// /// impl<T: TimeRep> fmt::Display for Milliseconds<T> { /// fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { /// unimplemented!() /// } /// /// } /// ``` pub trait Duration: Sized + Copy + fmt::Display { type Rep: TimeRep; const PERIOD: Period; /// Not generally useful or needed as the duration can be instantiated like this: /// ```no_run /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// Seconds(123); /// 123.seconds(); /// ``` /// It only exists to allow Duration methods with default definitions to create a /// new duration fn new(value: Self::Rep) -> Self; /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Seconds(123).count(), 123); /// ``` fn count(self) -> Self::Rep; /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// # use embedded_time::Period; /// assert_eq!(Microseconds::<i32>::from_ticks(5_i64, Period::new_raw(1, 1_000)), Some(Microseconds(5_000_i32))); /// assert_eq!(Microseconds::<i64>::from_ticks(i32::MAX, Period::new_raw(1, 1_000)), Some(Microseconds((i32::MAX as i64) * 1_000))); /// assert_eq!(Milliseconds::<i32>::from_ticks((i32::MAX as i64) + 1, Period::new_raw(1, 1_000_000)), Some(Milliseconds((((i32::MAX as i64) + 1) / 1_000) as i32))); /// ``` fn from_ticks<Rep>(ticks: Rep, period: Period) -> Option<Self> where Self::Rep: TimeRep + TryFrom<Rep>, Rep: TimeRep, { if size_of::<Self::Rep>() > size_of::<Rep>() { let converted_ticks = Self::Rep::try_from(ticks).ok()?; if period > Period::new_raw(1, 1) { Some(Self::new(TimeRep::checked_div( &converted_ticks.checked_mul(&period)?, &Self::PERIOD, )?)) } else { Some(Self::new( converted_ticks.checked_mul(&period.checked_div(&Self::PERIOD)?)?, )) } } else { let ticks = if period > Period::new_raw(1, 1) { TimeRep::checked_div(&TimeRep::checked_mul(&ticks, &period)?, &Self::PERIOD)? } else { TimeRep::checked_mul(&ticks, &period.checked_div(&Self::PERIOD)?)? }; let converted_ticks = Self::Rep::try_from(ticks).ok()?; Some(Self::new(converted_ticks)) } } /// Create an integer representation with LSbit period of that provided /// /// # Errors /// - the conversion of periods causes an overflow /// - the Self integer cast to that of the provided type fails /// /// # Examples /// ```rust /// # use embedded_time::{prelude::*, time_units::*, Period}; /// assert_eq!(Microseconds(5_000_i32).into_ticks::<i32>(Period::new_raw(1, 1_000)), Some(5_i32)); /// assert_eq!(Microseconds(5_000_i32).into_ticks::<i32>(Period::new_raw(1, 200)), Some(1_i32)); /// assert_eq!(Microseconds::<i32>(i32::MAX).into_ticks::<i64>(Period::new_raw(1, 2_000_000)), Some((i32::MAX as i64) * 2)); /// assert_eq!(Microseconds::<i64>((i32::MAX as i64) + 2).into_ticks::<i32>(Period::new_raw(1, 500_000)), Some(i32::MAX / 2 + 1)); /// assert_eq!(Microseconds::<i64>(i32::MAX as i64).into_ticks::<i32>(Period::new_raw(1, 500_000)), Some(i32::MAX / 2)); /// ``` fn into_ticks<Rep>(self, period: Period) -> Option<Rep> where Self::Rep: TimeRep, Rep: TimeRep + TryFrom<Self::Rep>, { if size_of::<Rep>() > size_of::<Self::Rep>() { let ticks = Rep::try_from(self.count()).ok()?; if period > Period::new_raw(1, 1) { Some(TimeRep::checked_div( &TimeRep::checked_mul(&ticks, &Self::PERIOD)?, &period, )?) } else { Some(TimeRep::checked_mul( &ticks, &Self::PERIOD.checked_div(&period)?, )?) } } else { let ticks = if Self::PERIOD > Period::new_raw(1, 1) { TimeRep::checked_div( &TimeRep::checked_mul(&self.count(), &Self::PERIOD)?, &period, )? } else { TimeRep::checked_mul(&self.count(), &Self::PERIOD.checked_div(&period)?)? }; Rep::try_from(ticks).ok() } } /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Seconds::<i32>::min_value(), i32::MIN); /// ``` #[must_use] fn min_value() -> Self::Rep { Self::Rep::min_value() } /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Seconds::<i32>::max_value(), i32::MAX); /// ``` #[must_use] fn max_value() -> Self::Rep { Self::Rep::max_value() } /// Apply wrapping subtraction /// /// # Example /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Seconds(1).wrapping_sub(Seconds(u32::MAX as i32)), Some(Seconds(2))); /// ``` fn wrapping_sub<Rhs>(self, rhs: Rhs) -> Option<Self> where Self: TryConvertFrom<Rhs>, Self::Rep: TryFrom<Rhs::Rep, Error: fmt::Debug>, Rhs::Rep: TimeRep, Rhs: Duration, { let rhs = Self::try_convert_from(rhs)?; Some(Self::new(self.count().wrapping_sub(&rhs.count()))) } } pub trait TryConvertFrom<Source>: Sized { fn try_convert_from(other: Source) -> Option<Self>; } pub trait TryConvertInto<Dest> { fn try_convert_into(self) -> Option<Dest>; } impl<Source, Dest> TryConvertFrom<Source> for Dest where Dest: Duration, Dest::Rep: TimeRep + TryFrom<Source::Rep, Error: fmt::Debug>, Source: Duration, Source::Rep: TimeRep, { /// Attempt to convert from one duration type to another /// /// Both the underlying storage type and the LSbit period can be converted /// /// # Errors /// - unable to cast underlying types /// - LSbit period conversion overflow /// /// # Examples /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// # use embedded_time::duration::TryConvertFrom; /// assert_eq!(Seconds::<i32>::try_convert_from(Milliseconds(23_000_i64)), Some(Seconds(23_i32))); /// assert_eq!(Seconds::<i64>::try_convert_from(Milliseconds(23_000_i32)), Some(Seconds(23_i64))); /// ``` fn try_convert_from(source: Source) -> Option<Self> { Some(Self::from_ticks(source.count(), Source::PERIOD)?) } } /// The reciprocal of [`TryConvertFrom`] /// /// # Examples /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// # use embedded_time::duration::TryConvertInto; /// assert_eq!(Seconds(23_000_i64).try_convert_into(), Some(Seconds(23_000_i32))); /// assert_eq!(Seconds(23_000_i32).try_convert_into(), Some(Seconds(23_000_i32))); /// assert_eq!(Some(Seconds(23_000_i64)), (Seconds(23_000_i32).try_convert_into())); /// assert_eq!(Milliseconds(23_000_i64).try_convert_into(), Some(Seconds(23_i32))); /// assert_eq!(Milliseconds(23_000_i32).try_convert_into(), Some(Seconds(23_i64))); /// ``` impl<Source, Dest> TryConvertInto<Dest> for Source where Source: Duration, Dest: Duration + TryConvertFrom<Source>, { fn try_convert_into(self) -> Option<Dest> { Dest::try_convert_from(self) } } /// Implementations of the [`Duration`] trait. /// /// # Constructing a duration /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Milliseconds::<i32>::new(23), Milliseconds(23_i32)); /// assert_eq!(Milliseconds(23), 23.milliseconds()); /// ``` /// /// # Get the integer count /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Milliseconds(23).count(), 23); /// ``` /// /// # Formatting /// Just forwards the underlying integer to [`core::fmt::Display::fmt()`] /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(format!("{}", Seconds(123)), "123"); /// ``` /// /// /// # Add/Sub /// /// ## Panics /// Panics if the rhs duration cannot be converted into the lhs duration type /// /// In this example, the maximum `i32` value of seconds is stored as `i32` and /// converting that value to milliseconds (with `i32` storage type) causes an overflow. /// ```rust,should_panic /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// let _ = Milliseconds(24) + Seconds(i32::MAX); /// ``` /// /// This example works just fine as the seconds value is first cast to `i64`, then /// converted to milliseconds. /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// let _ = Milliseconds(24_i64) + Seconds(i32::MAX); /// ``` /// /// Here, there is no units conversion to worry about, but `i32::MAX + 1` cannot be /// cast to an `i32`. /// ```rust,should_panic /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// let _ = Seconds(i32::MAX) - Seconds(i32::MAX as i64 + 1); /// ``` /// /// ## Examples /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!((Milliseconds(3_234) - Seconds(2)), Milliseconds(1_234)); /// assert_eq!((Milliseconds(3_234_i64) - Seconds(2_i32)), Milliseconds(1_234_i64)); /// assert_eq!((Seconds(i32::MAX) - Milliseconds((i32::MAX as i64) + 1)), Seconds(2_145_336_164_i32)); /// ``` /// /// # Equality /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert_eq!(Seconds(123), Seconds(123)); /// assert_eq!(Seconds(123), Milliseconds(123_000)); /// assert_ne!(Seconds(123), Milliseconds(123_001)); /// assert_ne!(Milliseconds(123_001), Seconds(123)); /// assert_ne!(Milliseconds(123_001_i64), Seconds(123_i64)); /// assert_ne!(Seconds(123_i64), Milliseconds(123_001_i64)); /// assert_ne!(Seconds(123_i64), Milliseconds(123_001_i32)); /// ``` /// /// # Comparisons /// ```rust /// # use embedded_time::prelude::*; /// # use embedded_time::time_units::*; /// assert!(Seconds(2) < Seconds(3)); /// assert!(Seconds(2) < Milliseconds(2_001)); /// assert!(Seconds(2) == Milliseconds(2_000)); /// assert!(Seconds(2) > Milliseconds(1_999)); /// assert!(Seconds(2_i32) < Milliseconds(2_001_i64)); /// assert!(Seconds(2_i64) < Milliseconds(2_001_i32)); /// ``` pub mod time_units { //! Implementations of the [`Duration`] trait. //! //! # Constructing a duration //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert_eq!(Milliseconds::<i32>::new(23), Milliseconds(23_i32)); //! assert_eq!(Milliseconds(23), 23.milliseconds()); //! ``` //! //! # Get the integer count //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert_eq!(Milliseconds(23).count(), 23); //! ``` //! //! # Formatting //! Just forwards the underlying integer to [`core::fmt::Display::fmt()`] //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert_eq!(format!("{}", Seconds(123)), "123"); //! ``` //! //! //! # Add/Sub //! //! ## Panics //! Panics if the rhs duration cannot be converted into the lhs duration type //! //! In this example, the maximum `i32` value of seconds is stored as `i32` and //! converting that value to milliseconds (with `i32` storage type) causes an overflow. //! ```rust,should_panic //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! let _ = Milliseconds(24) + Seconds(i32::MAX); //! ``` //! //! This example works just fine as the seconds value is first cast to `i64`, then //! converted to milliseconds. //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! let _ = Milliseconds(24_i64) + Seconds(i32::MAX); //! ``` //! //! Here, there is no units conversion to worry about, but `i32::MAX + 1` cannot be //! cast to an `i32`. //! ```rust,should_panic //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! let _ = Seconds(i32::MAX) + Seconds(i32::MAX as i64 + 1); //! # //todo: perhaps initially convert types to largest storage, do the op, then convert to lhs type //! ``` //! //! ## Examples //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert_eq!((Milliseconds(3_234) - Seconds(2)), Milliseconds(1_234)); //! assert_eq!((Milliseconds(3_234_i64) - Seconds(2_i32)), Milliseconds(1_234_i64)); //! ``` //! //! # Equality //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert_eq!(Seconds(123), Seconds(123)); //! assert_eq!(Seconds(123), Milliseconds(123_000)); //! assert_ne!(Seconds(123), Milliseconds(123_001)); //! assert_ne!(Milliseconds(123_001), Seconds(123)); //! assert_ne!(Milliseconds(123_001_i64), Seconds(123_i64)); //! assert_ne!(Seconds(123_i64), Milliseconds(123_001_i64)); //! assert_ne!(Seconds(123_i64), Milliseconds(123_001_i32)); //! ``` //! //! # Comparisons //! ```rust //! # use embedded_time::prelude::*; //! # use embedded_time::time_units::*; //! assert!(Seconds(2) < Seconds(3)); //! assert!(Seconds(2) < Milliseconds(2_001)); //! assert!(Seconds(2) == Milliseconds(2_000)); //! assert!(Seconds(2) > Milliseconds(1_999)); //! assert!(Seconds(2_i32) < Milliseconds(2_001_i64)); //! assert!(Seconds(2_i64) < Milliseconds(2_001_i32)); //! ``` use crate::{ duration::{Duration, TryConvertFrom}, numerical_duration::TimeRep, Period, }; use core::{ cmp, convert::TryFrom, fmt::{self, Formatter}, ops, }; macro_rules! durations { ( $( $name:ident, ($numer:expr, $denom:expr) );+ ) => { $( /// See module-level documentation for details about this type #[derive(Copy, Clone, Debug, Eq, Ord)] pub struct $name<T: TimeRep>(pub T); impl<Rep: TimeRep> Duration for $name<Rep> { type Rep = Rep; const PERIOD: Period = Period::new_raw($numer, $denom); fn new(value: Self::Rep) -> Self { Self(value) } fn count(self) -> Self::Rep { self.0 } } /// See module-level documentation for details about this type impl<T: TimeRep> fmt::Display for $name<T> { /// See module-level documentation for details about this type fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// See module-level documentation for details about this type impl<Rep, RhsDur> ops::Add<RhsDur> for $name<Rep> where RhsDur: Duration, RhsDur::Rep: TimeRep, Rep: TimeRep + TryFrom<RhsDur::Rep, Error: fmt::Debug>, { type Output = Self; /// See module-level documentation for details about this type #[inline] fn add(self, rhs: RhsDur) -> Self::Output { Self(self.count() + Self::try_convert_from(rhs).unwrap().count()) } } /// See module-level documentation for details about this type impl<Rep, RhsDur> ops::Sub<RhsDur> for $name<Rep> where Rep: TimeRep + TryFrom<RhsDur::Rep, Error: fmt::Debug>, RhsDur: Duration, { type Output = Self; /// See module-level documentation for details about this type #[inline] fn sub(self, rhs: RhsDur) -> Self::Output { Self(self.count() - Self::try_convert_from(rhs).unwrap().count()) } } /// See module-level documentation for details about this type impl<Rep, OtherDur> cmp::PartialEq<OtherDur> for $name<Rep> where Rep: TimeRep + TryFrom<OtherDur::Rep, Error: fmt::Debug>, OtherDur: Duration, OtherDur::Rep: TryFrom<Rep, Error: fmt::Debug>, { /// See module-level documentation for details about this type fn eq(&self, other: &OtherDur) -> bool { if Self::PERIOD < OtherDur::PERIOD { self.count() == Self::try_convert_from(*other).unwrap().count() } else { OtherDur::try_convert_from(*self).unwrap().count() == other.count() } } } /// See module-level documentation for details about this type impl<Rep, OtherDur> PartialOrd<OtherDur> for $name<Rep> where Rep: TimeRep + TryFrom<OtherDur::Rep, Error: fmt::Debug>, OtherDur: Duration, OtherDur::Rep: TryFrom<Rep, Error: fmt::Debug>, { /// See module-level documentation for details about this type fn partial_cmp(&self, other: &OtherDur) -> Option<core::cmp::Ordering> { if Self::PERIOD < OtherDur::PERIOD { Some(self.count().cmp(&Self::try_convert_from(*other).unwrap().count())) } else { Some( OtherDur::try_convert_from(*self) .unwrap() .count() .cmp(&other.count()), ) } } } )+ }; } durations![ Hours, (3600, 1); Minutes, (60, 1); Seconds, (1, 1); Milliseconds, (1, 1_000); Microseconds, (1, 1_000_000); Nanoseconds, (1, 1_000_000_000) ]; }