Skip to main content

core/
bool.rs

1//! impl bool {}
2
3use crate::intrinsics;
4use crate::marker::Destruct;
5use crate::ub_checks::assert_unsafe_precondition;
6
7impl bool {
8    /// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html),
9    /// or `None` otherwise.
10    ///
11    /// Arguments passed to `then_some` are eagerly evaluated; if you are
12    /// passing the result of a function call, it is recommended to use
13    /// [`then`], which is lazily evaluated.
14    ///
15    /// [`then`]: bool::then
16    ///
17    /// # Examples
18    ///
19    /// ```
20    /// assert_eq!(false.then_some(0), None);
21    /// assert_eq!(true.then_some(0), Some(0));
22    /// ```
23    ///
24    /// ```
25    /// let mut a = 0;
26    /// let mut function_with_side_effects = || { a += 1; };
27    ///
28    /// true.then_some(function_with_side_effects());
29    /// false.then_some(function_with_side_effects());
30    ///
31    /// // `a` is incremented twice because the value passed to `then_some` is
32    /// // evaluated eagerly.
33    /// assert_eq!(a, 2);
34    /// ```
35    #[stable(feature = "bool_to_option", since = "1.62.0")]
36    #[rustc_const_unstable(feature = "const_bool", issue = "151531")]
37    #[inline]
38    pub const fn then_some<T: [const] Destruct>(self, t: T) -> Option<T> {
39        if self { Some(t) } else { None }
40    }
41
42    /// Returns `Some(f())` if the `bool` is [`true`](../std/keyword.true.html),
43    /// or `None` otherwise.
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// assert_eq!(false.then(|| 0), None);
49    /// assert_eq!(true.then(|| 0), Some(0));
50    /// ```
51    ///
52    /// ```
53    /// let mut a = 0;
54    ///
55    /// true.then(|| { a += 1; });
56    /// false.then(|| { a += 1; });
57    ///
58    /// // `a` is incremented once because the closure is evaluated lazily by
59    /// // `then`.
60    /// assert_eq!(a, 1);
61    /// ```
62    #[doc(alias = "then_with")]
63    #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
64    #[rustc_diagnostic_item = "bool_then"]
65    #[rustc_const_unstable(feature = "const_bool", issue = "151531")]
66    #[inline]
67    pub const fn then<T, F: [const] FnOnce() -> T + [const] Destruct>(self, f: F) -> Option<T> {
68        if self { Some(f()) } else { None }
69    }
70
71    /// Returns `Ok(())` if the `bool` is [`true`](../std/keyword.true.html),
72    /// or `Err(err)` otherwise.
73    ///
74    /// Arguments passed to `ok_or` are eagerly evaluated; if you are
75    /// passing the result of a function call, it is recommended to use
76    /// [`ok_or_else`], which is lazily evaluated.
77    ///
78    /// [`ok_or_else`]: bool::ok_or_else
79    ///
80    /// # Examples
81    ///
82    /// ```
83    /// assert_eq!(false.ok_or(0), Err(0));
84    /// assert_eq!(true.ok_or(0), Ok(()));
85    /// ```
86    ///
87    /// ```
88    /// let mut a = 0;
89    /// let mut function_with_side_effects = || { a += 1; };
90    ///
91    /// assert!(true.ok_or(function_with_side_effects()).is_ok());
92    /// assert!(false.ok_or(function_with_side_effects()).is_err());
93    ///
94    /// // `a` is incremented twice because the value passed to `ok_or` is
95    /// // evaluated eagerly.
96    /// assert_eq!(a, 2);
97    /// ```
98    #[stable(feature = "bool_to_result", since = "1.98.0")]
99    #[rustc_const_unstable(feature = "const_bool", issue = "151531")]
100    #[inline]
101    pub const fn ok_or<E: [const] Destruct>(self, err: E) -> Result<(), E> {
102        if self { Ok(()) } else { Err(err) }
103    }
104
105    /// Returns `Ok(())` if the `bool` is [`true`](../std/keyword.true.html),
106    /// or `Err(f())` otherwise.
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// assert_eq!(false.ok_or_else(|| 0), Err(0));
112    /// assert_eq!(true.ok_or_else(|| 0), Ok(()));
113    /// ```
114    ///
115    /// ```
116    /// let mut a = 0;
117    ///
118    /// assert!(true.ok_or_else(|| { a += 1; }).is_ok());
119    /// assert!(false.ok_or_else(|| { a += 1; }).is_err());
120    ///
121    /// // `a` is incremented once because the closure is evaluated lazily by
122    /// // `ok_or_else`.
123    /// assert_eq!(a, 1);
124    /// ```
125    #[stable(feature = "bool_to_result", since = "1.98.0")]
126    #[rustc_const_unstable(feature = "const_bool", issue = "151531")]
127    #[inline]
128    pub const fn ok_or_else<E, F: [const] FnOnce() -> E + [const] Destruct>(
129        self,
130        f: F,
131    ) -> Result<(), E> {
132        if self { Ok(()) } else { Err(f()) }
133    }
134
135    /// Toggles `self` in-place.
136    ///
137    /// - If `self` is [`true`], sets `self` to [`false`].
138    /// - If `self` is [`false`], sets `self` to [`true`].
139    ///
140    /// Equivalent to `value = !value`.
141    ///
142    /// # Examples
143    ///
144    /// ```
145    /// let mut boolean = false;
146    ///
147    /// boolean.toggle();
148    /// assert_eq!(boolean, true);
149    ///
150    /// boolean.toggle();
151    /// assert_eq!(boolean, false);
152    /// ```
153    ///
154    /// [`true`]: ../std/keyword.true.html
155    /// [`false`]: ../std/keyword.false.html
156    #[stable(feature = "bool_toggle", since = "1.100.0")]
157    #[rustc_const_stable(feature = "bool_toggle", since = "1.100.0")]
158    #[inline]
159    pub const fn toggle(&mut self) {
160        *self = !*self;
161    }
162
163    /// Disjoint, bitwise or. Computes `self | rhs`, assuming at most one, true value.
164    ///
165    /// Practically, this requires that `self | rhs` and `self ^ rhs` both yield the
166    /// same result, allowing for any of the two to be emitted in codegen -- depending
167    /// on whichever is cheapest.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// #![feature(disjoint_bitor)]
173    ///
174    /// assert_eq!(
175    ///     // SAFETY: Only one, true value is passed.
176    ///     unsafe { false.unchecked_disjoint_bitor(true) },
177    ///     true,
178    /// );
179    ///
180    /// assert_eq!(
181    ///     // SAFETY: No true values are passed.
182    ///     unsafe { false.unchecked_disjoint_bitor(false) },
183    ///     false,
184    /// );
185    /// ```
186    ///
187    /// # Safety
188    ///
189    /// This results in undefined behaviour if both `self` and `rhs` are true.
190    #[unstable(feature = "disjoint_bitor", issue = "135758")]
191    #[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
192    #[must_use = "this returns the result of the operation, \
193                      without modifying the original"]
194    #[inline]
195    pub const unsafe fn unchecked_disjoint_bitor(self, rhs: Self) -> Self {
196        assert_unsafe_precondition!(
197            check_language_ub,
198            "bool::unchecked_disjoint_bitor cannot bitor two truths",
199            (
200                lhs: bool = self,
201                rhs: bool = rhs,
202            ) => !(lhs & rhs),
203        );
204
205        // SAFETY: Same precondition.
206        unsafe { intrinsics::disjoint_bitor(self, rhs) }
207    }
208}