orphanage 0.5.6

Random collection of stuff that is still searching for a home.
Documentation
use std::time::{Duration, Instant};

pub fn timeit<F, R, T>(f: F, t: T) -> R
where
  F: FnOnce() -> R,
  T: FnOnce(Duration)
{
  let start = Instant::now();
  let ret = f();
  let dur = start.elapsed();
  t(dur);
  ret
}


/// A drop guard that measures the time between its creation and destruction,
/// and calls an application-supplied closure when dropped.
///
/// ```
/// use orphanage::timing::TimeIt;
///
/// fn initdb() {
///   let _tmit = TimeIt::new("initialize database", |action, dur| {
///     println!("{action} took {dur:?}");
///   });
///   // .. initialize database here ..
/// }
/// ```
pub struct TimeIt<'a> {
  start: Instant,
  action: &'a str,

  #[allow(clippy::type_complexity)]
  cb: Option<Box<dyn FnOnce(&str, Duration) + Send>>
}

impl<'a> TimeIt<'a> {
  pub fn new(
    action: &'a str,
    cb: impl FnOnce(&str, Duration) + Send + 'static
  ) -> Self {
    Self {
      start: Instant::now(),
      action,
      cb: Some(Box::new(cb))
    }
  }
}

impl Drop for TimeIt<'_> {
  fn drop(&mut self) {
    let dur = self.start.elapsed();
    let Some(cb) = self.cb.take() else { return };
    cb(self.action, dur);
  }
}


#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn tmit() {
    let _tmit = TimeIt::new("initialize", |action, dur| {
      println!("{action} took {dur:?}");
    });
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :