core/
bool.rs

1//! impl bool {}
2
3impl bool {
4    /// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html),
5    /// or `None` otherwise.
6    ///
7    /// Arguments passed to `then_some` are eagerly evaluated; if you are
8    /// passing the result of a function call, it is recommended to use
9    /// [`then`], which is lazily evaluated.
10    ///
11    /// [`then`]: bool::then
12    ///
13    /// # Examples
14    ///
15    /// ```
16    /// assert_eq!(false.then_some(0), None);
17    /// assert_eq!(true.then_some(0), Some(0));
18    /// ```
19    ///
20    /// ```
21    /// let mut a = 0;
22    /// let mut function_with_side_effects = || { a += 1; };
23    ///
24    /// true.then_some(function_with_side_effects());
25    /// false.then_some(function_with_side_effects());
26    ///
27    /// // `a` is incremented twice because the value passed to `then_some` is
28    /// // evaluated eagerly.
29    /// assert_eq!(a, 2);
30    /// ```
31    #[stable(feature = "bool_to_option", since = "1.62.0")]
32    #[inline]
33    pub fn then_some<T>(self, t: T) -> Option<T> {
34        if self { Some(t) } else { None }
35    }
36
37    /// Returns `Some(f())` if the `bool` is [`true`](../std/keyword.true.html),
38    /// or `None` otherwise.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// assert_eq!(false.then(|| 0), None);
44    /// assert_eq!(true.then(|| 0), Some(0));
45    /// ```
46    ///
47    /// ```
48    /// let mut a = 0;
49    ///
50    /// true.then(|| { a += 1; });
51    /// false.then(|| { a += 1; });
52    ///
53    /// // `a` is incremented once because the closure is evaluated lazily by
54    /// // `then`.
55    /// assert_eq!(a, 1);
56    /// ```
57    #[doc(alias = "then_with")]
58    #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
59    #[cfg_attr(not(test), rustc_diagnostic_item = "bool_then")]
60    #[inline]
61    pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
62        if self { Some(f()) } else { None }
63    }
64
65    /// Returns either `true_val` or `false_val` depending on the value of
66    /// `self`, with a hint to the compiler that `self` is unlikely
67    /// to be correctly predicted by a CPU’s branch predictor.
68    ///
69    /// This method is functionally equivalent to
70    /// ```ignore (this is just for illustrative purposes)
71    /// fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
72    ///     if b { true_val } else { false_val }
73    /// }
74    /// ```
75    /// but might generate different assembly. In particular, on platforms with
76    /// a conditional move or select instruction (like `cmov` on x86 or `csel`
77    /// on ARM) the optimizer might use these instructions to avoid branches,
78    /// which can benefit performance if the branch predictor is struggling
79    /// with predicting `condition`, such as in an implementation of  binary
80    /// search.
81    ///
82    /// Note however that this lowering is not guaranteed (on any platform) and
83    /// should not be relied upon when trying to write constant-time code. Also
84    /// be aware that this lowering might *decrease* performance if `condition`
85    /// is well-predictable. It is advisable to perform benchmarks to tell if
86    /// this function is useful.
87    ///
88    /// # Examples
89    ///
90    /// Distribute values evenly between two buckets:
91    /// ```
92    /// #![feature(select_unpredictable)]
93    ///
94    /// use std::hash::BuildHasher;
95    ///
96    /// fn append<H: BuildHasher>(hasher: &H, v: i32, bucket_one: &mut Vec<i32>, bucket_two: &mut Vec<i32>) {
97    ///     let hash = hasher.hash_one(&v);
98    ///     let bucket = (hash % 2 == 0).select_unpredictable(bucket_one, bucket_two);
99    ///     bucket.push(v);
100    /// }
101    /// # let hasher = std::collections::hash_map::RandomState::new();
102    /// # let mut bucket_one = Vec::new();
103    /// # let mut bucket_two = Vec::new();
104    /// # append(&hasher, 42, &mut bucket_one, &mut bucket_two);
105    /// # assert_eq!(bucket_one.len() + bucket_two.len(), 1);
106    /// ```
107    #[inline(always)]
108    #[unstable(feature = "select_unpredictable", issue = "133962")]
109    pub fn select_unpredictable<T>(self, true_val: T, false_val: T) -> T {
110        crate::intrinsics::select_unpredictable(self, true_val, false_val)
111    }
112}