product-os-async-executor 0.0.18

Product OS : Async Executor provides a set of tools to handle async execution generically so that the desired async library (e.g. tokio, smol) to be used can be chosen at compile time.
Documentation
//! Time abstraction for testable time operations.
//!
//! The `Moment` struct provides a way to abstract the current time, making it easier
//! to write testable code that depends on time.

#[cfg(feature = "moment")]
use core::fmt;
#[cfg(feature = "moment")]
use core::fmt::Formatter;


/// A time abstraction that allows for custom time sources.
///
/// `Moment` wraps a function that returns the current time, allowing you to
/// inject custom time sources for testing or other purposes.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "moment")]
/// # {
/// use product_os_async_executor::moment::Moment;
///
/// // Use the default system time
/// let moment = Moment::default();
/// let now = moment.now();
///
/// // Use a custom time source
/// let custom_moment = Moment::new(Some(|| {
///     chrono::Utc::now()
/// }));
/// # }
/// ```
#[cfg(feature = "moment")]
#[derive(Clone)]
pub struct Moment {
    generator: alloc::sync::Arc<fn() -> chrono::DateTime<chrono::Utc>>
}

#[cfg(feature = "moment")]
impl Moment {
    /// Creates a new `Moment` with the given time function.
    ///
    /// If `None` is provided and the `default` feature is enabled, uses `chrono::Utc::now`.
    /// Otherwise, panics if no function is provided.
    ///
    /// # Panics
    ///
    /// Panics if `func` is `None` and the `default` feature is not enabled.
    #[must_use]
    pub fn new(func: Option<fn() -> chrono::DateTime<chrono::Utc>>) -> Self {
        let time_func = {
            #[cfg(feature = "default")] {
                match func {
                    Some(f) => f,
                    None => chrono::Utc::now
                }
            }
            #[cfg(not(feature = "default"))] {
                match func {
                    Some(f) => f,
                    None => panic!("No time function supplied")
                }
            }
        };

        Self {
            generator: alloc::sync::Arc::new(time_func)
        }
    }

    /// Returns the current time according to this `Moment`'s time source.
    #[must_use]
    pub fn now(&self) -> chrono::DateTime<chrono::Utc> {
        (self.generator)()
    }

    /// Gets the underlying time function.
    #[must_use]
    pub fn get_function(&self) -> fn() -> chrono::DateTime<chrono::Utc> {
        *self.generator.clone()
    }
}

#[cfg(all(feature = "moment", feature = "default"))]
impl Default for Moment {
    fn default() -> Self {
        Self {
            generator: alloc::sync::Arc::new(chrono::Utc::now)
        }
    }
}

#[cfg(feature = "moment")]
impl core::fmt::Debug for Moment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Moment")
            .field("generator", &"<fn>")
            .finish()
    }
}