aoko/standard/functions/
ext.rs

1use crate::no_std::functions::ext::AnyExt1;
2use std::{prelude::v1::*, fmt::{Debug, Display}, time::{Instant, Duration}};
3
4/// This trait is to implement some extension functions,
5/// which need a generic return type, for any sized type.
6pub trait StdAnyExt1<R>: Sized {
7    /// Executes the given closure block and returns the duration of elapsed time interval.
8    fn measure_time(self, f: impl FnOnce(Self) -> R) -> Duration {
9        Instant::now().also_ref(|_| f(self)).elapsed()
10    }
11
12    /// Executes the given closure block,
13    /// returns the result of the closure execution and the duration of elapsed time interval.
14    fn measure_time_with_value(self, f: impl FnOnce(Self) -> R) -> (R, Duration) {
15        Instant::now().let_owned(|s| (f(self), s.elapsed()))
16    }
17
18    /// Executes the given closure block,
19    /// returns the receiver `self` and the duration of elapsed time interval.
20    fn measure_time_with_self(self, f: impl FnOnce(&Self) -> R) -> (Self, Duration) {
21        Instant::now().also_ref(|_| f(&self)).let_owned(|s| (self, s.elapsed()))
22    }
23
24    /// Executes the given closure block,
25    /// returns the receiver `self` and the duration of elapsed time interval.
26    fn measure_time_with_mut_self(mut self, f: impl FnOnce(&mut Self) -> R) -> (Self, Duration) {
27        Instant::now().also_ref(|_| f(&mut self)).let_owned(|s| (self, s.elapsed()))
28    }
29}
30
31impl<T, R> StdAnyExt1<R> for T {}
32
33/// This trait is to implement some extension functions for any sized type.
34pub trait StdAnyExt: Sized {
35    /// System output -> with `:#?`'s `println!`.
36    ///
37    /// Consumes `self`, `println!` with `:#?`, returns `self`.
38    fn dbg(self) -> Self where Self: Debug {
39        self.also_ref(|s| println!("{:#?}", s))
40    }
41
42    /// System output -> with `:?`'s `println!`.
43    ///
44    /// Consumes `self`, `println!` with `:?`, returns `self`.
45    fn sout(self) -> Self where Self: Debug {
46        self.also_ref(|s| println!("{:?}", s))
47    }
48
49    /// Consumes `self`, `println!` as it is, returns `self`.
50    fn echo(self) -> Self where Self: Display {
51        self.also_ref(|s| println!("{}", s))
52    }
53}
54
55impl<T> StdAnyExt for T {}