conditional_assignment/lib.rs
1#![doc = include_str!("../README.md")]
2
3pub trait Pick<O>: private::Sealed {
4 fn pick(self, when_true: O, when_false: O) -> O;
5 fn pick_lazy<P, N>(self, when_true: P, when_false: N) -> O
6 where
7 P: FnOnce() -> O,
8 N: FnOnce() -> O;
9}
10
11// Prevent this trait from being implemented outside of this crate.
12// https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed
13mod private {
14 pub trait Sealed {}
15 impl Sealed for bool {}
16}
17
18impl<O> Pick<O> for bool {
19 ///
20 ///
21 /// Example:
22 /// ```
23 /// use conditional_assignment::Pick;
24 /// let condition = 0 < 1;
25 /// let outcome = if condition {
26 /// "true"
27 /// } else {
28 /// "false"
29 /// };
30 /// ```
31 #[inline]
32 fn pick(self: bool, when_true: O, when_false: O) -> O {
33 if self {
34 when_true
35 } else {
36 when_false
37 }
38 }
39
40 ///
41 ///
42 /// Example:
43 /// ```
44 /// use conditional_assignment::Pick;
45 /// let condition = 0 < 1;
46 /// let outcome = condition.pick_lazy(
47 /// || {
48 /// assert!(condition);
49 /// "true"
50 /// },
51 /// || {
52 /// assert!(!condition);
53 /// "false"
54 /// },
55 /// );
56 /// ```
57 #[inline]
58 fn pick_lazy<P, N>(self: bool, when_true: P, when_false: N) -> O
59 where
60 P: FnOnce() -> O,
61 N: FnOnce() -> O,
62 {
63 if self {
64 when_true()
65 } else {
66 when_false()
67 }
68 }
69}