scope_functions/
lib.rs

1//! This crate provides Kotlin-inspired scope functions for use in almost any situation.
2
3mod apply;
4mod run;
5
6pub use apply::Apply;
7pub use run::Run;
8
9/// Calls the specified `closure` and returns its result.
10#[inline(always)]
11pub fn run<T>(closure: impl FnOnce() -> T) -> T {
12    closure()
13}
14
15/// Calls the specified `closure` and returns a `Result`.
16#[inline(always)]
17pub fn try_run<T, E>(closure: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
18    closure()
19}
20
21/// Calls the specified `closure` with the given `receiver` and returns its result.
22#[inline(always)]
23pub fn with<R, T>(receiver: &R, closure: impl FnOnce(&R) -> T) -> T {
24    closure(receiver)
25}
26
27/// Calls the specified `closure` with the given mutable `receiver` and returns its result.
28#[inline(always)]
29pub fn with_mut<R, T>(receiver: &mut R, closure: impl FnOnce(&mut R) -> T) -> T {
30    closure(receiver)
31}
32
33/// Calls the specified `closure` with the given `receiver` and returns a `Result`.
34#[inline(always)]
35pub fn try_with<R, T, E>(receiver: &R, closure: impl FnOnce(&R) -> Result<T, E>) -> Result<T, E> {
36    closure(receiver)
37}
38
39/// Calls the specified `closure` with the given mutable `receiver` and returns a `Result`.
40#[inline(always)]
41pub fn try_with_mut<R, T, E>(receiver: &mut R, closure: impl FnOnce(&mut R) -> Result<T, E>) -> Result<T, E> {
42    closure(receiver)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn run_works() {
51        let x = 21;
52        let y = run(|| x + 21);
53
54        assert_eq!(y, 42);
55    }
56
57    #[test]
58    fn try_run_works() {
59        let x: Result<i32, ()> = try_run(|| Ok(42));
60        assert_eq!(x, Ok(42));
61
62        let y: Result<(), &str> = try_run(|| Err("error"));
63        assert_eq!(y, Err("error"));
64    }
65
66    #[test]
67    fn with_works() {
68        let x = with(&14, |x| x + 28);
69
70        assert_eq!(x, 42);
71    }
72
73    #[test]
74    fn with_mut_works() {
75        let x = with_mut(&mut 28, |x| {
76            *x += 14;
77            *x
78        });
79
80        assert_eq!(x, 42);
81    }
82
83    #[test]
84    fn try_with_works() {
85        let x: Result<i32, ()> = try_with(&42, |x| Ok(*x));
86        assert_eq!(x, Ok(42));
87
88        let y: Result<(), &str> = try_with(&0, |_| Err("error"));
89        assert_eq!(y, Err("error"));
90    }
91
92    #[test]
93    fn try_with_mut_works() {
94        let x: Result<i32, ()> = try_with_mut(&mut 28, |x| {
95            *x += 14;
96            Ok(*x)
97        });
98        assert_eq!(x, Ok(42));
99
100        let y: Result<(), &str> = try_with_mut(&mut 0, |_| Err("error"));
101        assert_eq!(y, Err("error"));
102    }
103}