Skip to main content

core/ops/
control_flow.rs

1use crate::marker::Destruct;
2use crate::{convert, ops};
3
4/// Used to tell an operation whether it should exit early or go on as usual.
5///
6/// This is used when exposing things (like graph traversals or visitors) where
7/// you want the user to be able to choose whether to exit early.
8/// Having the enum makes it clearer -- no more wondering "wait, what did `false`
9/// mean again?" -- and allows including a value.
10///
11/// Similar to [`Option`] and [`Result`], this enum can be used with the `?` operator
12/// to return immediately if the [`Break`] variant is present or otherwise continue normally
13/// with the value inside the [`Continue`] variant.
14///
15/// # Examples
16///
17/// Early-exiting from [`Iterator::try_for_each`]:
18/// ```
19/// use std::ops::ControlFlow;
20///
21/// let r = (2..100).try_for_each(|x| {
22///     if 403 % x == 0 {
23///         return ControlFlow::Break(x)
24///     }
25///
26///     ControlFlow::Continue(())
27/// });
28/// assert_eq!(r, ControlFlow::Break(13));
29/// ```
30///
31/// A basic tree traversal:
32/// ```
33/// use std::ops::ControlFlow;
34///
35/// pub struct TreeNode<T> {
36///     value: T,
37///     left: Option<Box<TreeNode<T>>>,
38///     right: Option<Box<TreeNode<T>>>,
39/// }
40///
41/// impl<T> TreeNode<T> {
42///     pub fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
43///         if let Some(left) = &self.left {
44///             left.traverse_inorder(f)?;
45///         }
46///         f(&self.value)?;
47///         if let Some(right) = &self.right {
48///             right.traverse_inorder(f)?;
49///         }
50///         ControlFlow::Continue(())
51///     }
52///     fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
53///         Some(Box::new(Self { value, left: None, right: None }))
54///     }
55/// }
56///
57/// let node = TreeNode {
58///     value: 0,
59///     left: TreeNode::leaf(1),
60///     right: Some(Box::new(TreeNode {
61///         value: -1,
62///         left: TreeNode::leaf(5),
63///         right: TreeNode::leaf(2),
64///     }))
65/// };
66/// let mut sum = 0;
67///
68/// let res = node.traverse_inorder(&mut |val| {
69///     if *val < 0 {
70///         ControlFlow::Break(*val)
71///     } else {
72///         sum += *val;
73///         ControlFlow::Continue(())
74///     }
75/// });
76/// assert_eq!(res, ControlFlow::Break(-1));
77/// assert_eq!(sum, 6);
78/// ```
79///
80/// [`Break`]: ControlFlow::Break
81/// [`Continue`]: ControlFlow::Continue
82#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
83#[rustc_diagnostic_item = "ControlFlow"]
84#[must_use]
85// ControlFlow should not implement PartialOrd or Ord, per RFC 3058:
86// https://rust-lang.github.io/rfcs/3058-try-trait-v2.html#traits-for-controlflow
87#[derive(Copy, Debug, Hash)]
88#[derive_const(Clone, PartialEq, Eq)]
89pub enum ControlFlow<B, C = ()> {
90    /// Move on to the next phase of the operation as normal.
91    #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
92    #[lang = "Continue"]
93    Continue(C),
94    /// Exit the operation without running subsequent phases.
95    #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
96    #[lang = "Break"]
97    Break(B),
98    // Yes, the order of the variants doesn't match the type parameters.
99    // They're in this order so that `ControlFlow<A, B>` <-> `Result<B, A>`
100    // is a no-op conversion in the `Try` implementation.
101}
102
103#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
104#[rustc_const_unstable(feature = "const_try", issue = "74935")]
105impl<B, C> const ops::Try for ControlFlow<B, C> {
106    type Output = C;
107    type Residual = ControlFlow<B, convert::Infallible>;
108
109    #[inline]
110    fn from_output(output: Self::Output) -> Self {
111        ControlFlow::Continue(output)
112    }
113
114    #[inline]
115    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
116        match self {
117            ControlFlow::Continue(c) => ControlFlow::Continue(c),
118            ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)),
119        }
120    }
121}
122
123#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
124#[rustc_const_unstable(feature = "const_try", issue = "74935")]
125// Note: manually specifying the residual type instead of using the default to work around
126// https://github.com/rust-lang/rust/issues/99940
127impl<B, C> const ops::FromResidual<ControlFlow<B, convert::Infallible>> for ControlFlow<B, C> {
128    #[inline]
129    fn from_residual(residual: ControlFlow<B, convert::Infallible>) -> Self {
130        match residual {
131            ControlFlow::Break(b) => ControlFlow::Break(b),
132        }
133    }
134}
135
136#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
137impl<B, C> ops::Residual<C> for ControlFlow<B, convert::Infallible> {
138    type TryType = ControlFlow<B, C>;
139}
140
141impl<B, C> ControlFlow<B, C> {
142    /// Returns `true` if this is a `Break` variant.
143    ///
144    /// # Examples
145    ///
146    /// ```
147    /// use std::ops::ControlFlow;
148    ///
149    /// assert!(ControlFlow::<&str, i32>::Break("Stop right there!").is_break());
150    /// assert!(!ControlFlow::<&str, i32>::Continue(3).is_break());
151    /// ```
152    #[inline]
153    #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
154    #[rustc_const_stable(feature = "min_const_control_flow", since = "CURRENT_RUSTC_VERSION")]
155    pub const fn is_break(&self) -> bool {
156        matches!(*self, ControlFlow::Break(_))
157    }
158
159    /// Returns `true` if this is a `Continue` variant.
160    ///
161    /// # Examples
162    ///
163    /// ```
164    /// use std::ops::ControlFlow;
165    ///
166    /// assert!(!ControlFlow::<&str, i32>::Break("Stop right there!").is_continue());
167    /// assert!(ControlFlow::<&str, i32>::Continue(3).is_continue());
168    /// ```
169    #[inline]
170    #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
171    #[rustc_const_stable(feature = "min_const_control_flow", since = "CURRENT_RUSTC_VERSION")]
172    pub const fn is_continue(&self) -> bool {
173        matches!(*self, ControlFlow::Continue(_))
174    }
175
176    /// Converts the `ControlFlow` into an `Option` which is `Some` if the
177    /// `ControlFlow` was `Break` and `None` otherwise.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use std::ops::ControlFlow;
183    ///
184    /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_value(), Some("Stop right there!"));
185    /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_value(), None);
186    /// ```
187    #[inline]
188    #[stable(feature = "control_flow_enum", since = "1.83.0")]
189    #[rustc_const_unstable(feature = "const_control_flow", issue = "148739")]
190    pub const fn break_value(self) -> Option<B>
191    where
192        Self: [const] Destruct,
193    {
194        match self {
195            ControlFlow::Continue(..) => None,
196            ControlFlow::Break(x) => Some(x),
197        }
198    }
199
200    /// Converts the `ControlFlow` into a `Result` which is `Ok` if the
201    /// `ControlFlow` was `Break` and `Err` if otherwise.
202    ///
203    /// # Examples
204    ///
205    /// ```
206    /// use std::ops::ControlFlow;
207    ///
208    /// struct TreeNode<T> {
209    ///     value: T,
210    ///     left: Option<Box<TreeNode<T>>>,
211    ///     right: Option<Box<TreeNode<T>>>,
212    /// }
213    ///
214    /// impl<T> TreeNode<T> {
215    ///     fn find<'a>(&'a self, mut predicate: impl FnMut(&T) -> bool) -> Result<&'a T, ()> {
216    ///         let mut f = |t: &'a T| -> ControlFlow<&'a T> {
217    ///             if predicate(t) {
218    ///                 ControlFlow::Break(t)
219    ///             } else {
220    ///                 ControlFlow::Continue(())
221    ///             }
222    ///         };
223    ///
224    ///         self.traverse_inorder(&mut f).break_ok()
225    ///     }
226    ///
227    ///     fn traverse_inorder<'a, B>(
228    ///         &'a self,
229    ///         f: &mut impl FnMut(&'a T) -> ControlFlow<B>,
230    ///     ) -> ControlFlow<B> {
231    ///         if let Some(left) = &self.left {
232    ///             left.traverse_inorder(f)?;
233    ///         }
234    ///         f(&self.value)?;
235    ///         if let Some(right) = &self.right {
236    ///             right.traverse_inorder(f)?;
237    ///         }
238    ///         ControlFlow::Continue(())
239    ///     }
240    ///
241    ///     fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
242    ///         Some(Box::new(Self {
243    ///             value,
244    ///             left: None,
245    ///             right: None,
246    ///         }))
247    ///     }
248    /// }
249    ///
250    /// let node = TreeNode {
251    ///     value: 0,
252    ///     left: TreeNode::leaf(1),
253    ///     right: Some(Box::new(TreeNode {
254    ///         value: -1,
255    ///         left: TreeNode::leaf(5),
256    ///         right: TreeNode::leaf(2),
257    ///     })),
258    /// };
259    ///
260    /// let res = node.find(|val: &i32| *val > 3);
261    /// assert_eq!(res, Ok(&5));
262    /// ```
263    #[inline]
264    #[stable(feature = "control_flow_ok", since = "CURRENT_RUSTC_VERSION")]
265    #[rustc_const_stable(feature = "control_flow_ok", since = "CURRENT_RUSTC_VERSION")]
266    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
267    pub const fn break_ok(self) -> Result<B, C> {
268        match self {
269            ControlFlow::Continue(c) => Err(c),
270            ControlFlow::Break(b) => Ok(b),
271        }
272    }
273
274    /// Maps `ControlFlow<B, C>` to `ControlFlow<T, C>` by applying a function
275    /// to the break value in case it exists.
276    #[inline]
277    #[stable(feature = "control_flow_enum", since = "1.83.0")]
278    #[rustc_const_unstable(feature = "const_control_flow", issue = "148739")]
279    pub const fn map_break<T, F>(self, f: F) -> ControlFlow<T, C>
280    where
281        F: [const] FnOnce(B) -> T + [const] Destruct,
282    {
283        match self {
284            ControlFlow::Continue(x) => ControlFlow::Continue(x),
285            ControlFlow::Break(x) => ControlFlow::Break(f(x)),
286        }
287    }
288
289    /// Converts the `ControlFlow` into an `Option` which is `Some` if the
290    /// `ControlFlow` was `Continue` and `None` otherwise.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use std::ops::ControlFlow;
296    ///
297    /// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_value(), None);
298    /// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_value(), Some(3));
299    /// ```
300    #[inline]
301    #[stable(feature = "control_flow_enum", since = "1.83.0")]
302    #[rustc_const_unstable(feature = "const_control_flow", issue = "148739")]
303    pub const fn continue_value(self) -> Option<C>
304    where
305        Self: [const] Destruct,
306    {
307        match self {
308            ControlFlow::Continue(x) => Some(x),
309            ControlFlow::Break(..) => None,
310        }
311    }
312
313    /// Converts the `ControlFlow` into a `Result` which is `Ok` if the
314    /// `ControlFlow` was `Continue` and `Err` if otherwise.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use std::ops::ControlFlow;
320    ///
321    /// struct TreeNode<T> {
322    ///     value: T,
323    ///     left: Option<Box<TreeNode<T>>>,
324    ///     right: Option<Box<TreeNode<T>>>,
325    /// }
326    ///
327    /// impl<T> TreeNode<T> {
328    ///     fn validate<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> Result<(), B> {
329    ///         self.traverse_inorder(f).continue_ok()
330    ///     }
331    ///
332    ///     fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
333    ///         if let Some(left) = &self.left {
334    ///             left.traverse_inorder(f)?;
335    ///         }
336    ///         f(&self.value)?;
337    ///         if let Some(right) = &self.right {
338    ///             right.traverse_inorder(f)?;
339    ///         }
340    ///         ControlFlow::Continue(())
341    ///     }
342    ///
343    ///     fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
344    ///         Some(Box::new(Self {
345    ///             value,
346    ///             left: None,
347    ///             right: None,
348    ///         }))
349    ///     }
350    /// }
351    ///
352    /// let node = TreeNode {
353    ///     value: 0,
354    ///     left: TreeNode::leaf(1),
355    ///     right: Some(Box::new(TreeNode {
356    ///         value: -1,
357    ///         left: TreeNode::leaf(5),
358    ///         right: TreeNode::leaf(2),
359    ///     })),
360    /// };
361    ///
362    /// let res = node.validate(&mut |val| {
363    ///     if *val < 0 {
364    ///         return ControlFlow::Break("negative value detected");
365    ///     }
366    ///
367    ///     if *val > 4 {
368    ///         return ControlFlow::Break("too big value detected");
369    ///     }
370    ///
371    ///     ControlFlow::Continue(())
372    /// });
373    /// assert_eq!(res, Err("too big value detected"));
374    /// ```
375    #[inline]
376    #[stable(feature = "control_flow_ok", since = "CURRENT_RUSTC_VERSION")]
377    #[rustc_const_stable(feature = "control_flow_ok", since = "CURRENT_RUSTC_VERSION")]
378    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
379    pub const fn continue_ok(self) -> Result<C, B> {
380        match self {
381            ControlFlow::Continue(c) => Ok(c),
382            ControlFlow::Break(b) => Err(b),
383        }
384    }
385
386    /// Maps `ControlFlow<B, C>` to `ControlFlow<B, T>` by applying a function
387    /// to the continue value in case it exists.
388    #[inline]
389    #[stable(feature = "control_flow_enum", since = "1.83.0")]
390    #[rustc_const_unstable(feature = "const_control_flow", issue = "148739")]
391    pub const fn map_continue<T, F>(self, f: F) -> ControlFlow<B, T>
392    where
393        F: [const] FnOnce(C) -> T + [const] Destruct,
394    {
395        match self {
396            ControlFlow::Continue(x) => ControlFlow::Continue(f(x)),
397            ControlFlow::Break(x) => ControlFlow::Break(x),
398        }
399    }
400}
401
402impl<T> ControlFlow<T, T> {
403    /// Extracts the value `T` that is wrapped by `ControlFlow<T, T>`.
404    ///
405    /// # Examples
406    ///
407    /// ```
408    /// #![feature(control_flow_into_value)]
409    /// use std::ops::ControlFlow;
410    ///
411    /// assert_eq!(ControlFlow::<i32, i32>::Break(1024).into_value(), 1024);
412    /// assert_eq!(ControlFlow::<i32, i32>::Continue(512).into_value(), 512);
413    /// ```
414    #[unstable(feature = "control_flow_into_value", issue = "137461")]
415    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
416    pub const fn into_value(self) -> T {
417        match self {
418            ControlFlow::Continue(x) | ControlFlow::Break(x) => x,
419        }
420    }
421}
422
423// These are used only as part of implementing the iterator adapters.
424// They have mediocre names and non-obvious semantics, so aren't
425// currently on a path to potential stabilization.
426impl<R: ops::Try> ControlFlow<R, R::Output> {
427    /// Creates a `ControlFlow` from any type implementing `Try`.
428    #[inline]
429    pub(crate) fn from_try(r: R) -> Self {
430        match R::branch(r) {
431            ControlFlow::Continue(v) => ControlFlow::Continue(v),
432            ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)),
433        }
434    }
435
436    /// Converts a `ControlFlow` into any type implementing `Try`.
437    #[inline]
438    pub(crate) fn into_try(self) -> R {
439        match self {
440            ControlFlow::Continue(v) => R::from_output(v),
441            ControlFlow::Break(v) => v,
442        }
443    }
444}