1 use crate::{convert, ops};
3 /// Used to tell an operation whether it should exit early or go on as usual.
5 /// This is used when exposing things (like graph traversals or visitors) where
6 /// you want the user to be able to choose whether to exit early.
7 /// Having the enum makes it clearer -- no more wondering "wait, what did `false`
8 /// mean again?" -- and allows including a value.
12 /// Early-exiting from [`Iterator::try_for_each`]:
14 /// use std::ops::ControlFlow;
16 /// let r = (2..100).try_for_each(|x| {
18 /// return ControlFlow::Break(x)
21 /// ControlFlow::Continue(())
23 /// assert_eq!(r, ControlFlow::Break(13));
26 /// A basic tree traversal:
28 /// use std::ops::ControlFlow;
30 /// pub struct TreeNode<T> {
32 /// left: Option<Box<TreeNode<T>>>,
33 /// right: Option<Box<TreeNode<T>>>,
36 /// impl<T> TreeNode<T> {
37 /// pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
38 /// if let Some(left) = &self.left {
39 /// left.traverse_inorder(&mut f)?;
42 /// if let Some(right) = &self.right {
43 /// right.traverse_inorder(&mut f)?;
45 /// ControlFlow::Continue(())
49 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
50 #[derive(Debug, Clone, Copy, PartialEq)]
51 pub enum ControlFlow<B, C = ()> {
52 /// Move on to the next phase of the operation as normal.
53 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
56 /// Exit the operation without running subsequent phases.
57 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
60 // Yes, the order of the variants doesn't match the type parameters.
61 // They're in this order so that `ControlFlow<A, B>` <-> `Result<B, A>`
62 // is a no-op conversion in the `Try` implementation.
65 #[unstable(feature = "try_trait_v2", issue = "84277")]
66 impl<B, C> ops::Try for ControlFlow<B, C> {
68 type Residual = ControlFlow<B, convert::Infallible>;
71 fn from_output(output: Self::Output) -> Self {
72 ControlFlow::Continue(output)
76 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
78 ControlFlow::Continue(c) => ControlFlow::Continue(c),
79 ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)),
84 #[unstable(feature = "try_trait_v2", issue = "84277")]
85 impl<B, C> ops::FromResidual for ControlFlow<B, C> {
87 fn from_residual(residual: ControlFlow<B, convert::Infallible>) -> Self {
89 ControlFlow::Break(b) => ControlFlow::Break(b),
94 impl<B, C> ControlFlow<B, C> {
95 /// Returns `true` if this is a `Break` variant.
100 /// #![feature(control_flow_enum)]
101 /// use std::ops::ControlFlow;
103 /// assert!(ControlFlow::<i32, String>::Break(3).is_break());
104 /// assert!(!ControlFlow::<String, i32>::Continue(3).is_break());
107 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
108 pub fn is_break(&self) -> bool {
109 matches!(*self, ControlFlow::Break(_))
112 /// Returns `true` if this is a `Continue` variant.
117 /// #![feature(control_flow_enum)]
118 /// use std::ops::ControlFlow;
120 /// assert!(!ControlFlow::<i32, String>::Break(3).is_continue());
121 /// assert!(ControlFlow::<String, i32>::Continue(3).is_continue());
124 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
125 pub fn is_continue(&self) -> bool {
126 matches!(*self, ControlFlow::Continue(_))
129 /// Converts the `ControlFlow` into an `Option` which is `Some` if the
130 /// `ControlFlow` was `Break` and `None` otherwise.
135 /// #![feature(control_flow_enum)]
136 /// use std::ops::ControlFlow;
138 /// assert_eq!(ControlFlow::<i32, String>::Break(3).break_value(), Some(3));
139 /// assert_eq!(ControlFlow::<String, i32>::Continue(3).break_value(), None);
142 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
143 pub fn break_value(self) -> Option<B> {
145 ControlFlow::Continue(..) => None,
146 ControlFlow::Break(x) => Some(x),
150 /// Maps `ControlFlow<B, C>` to `ControlFlow<T, C>` by applying a function
151 /// to the break value in case it exists.
153 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
154 pub fn map_break<T, F>(self, f: F) -> ControlFlow<T, C>
159 ControlFlow::Continue(x) => ControlFlow::Continue(x),
160 ControlFlow::Break(x) => ControlFlow::Break(f(x)),
165 /// These are used only as part of implementing the iterator adapters.
166 /// They have mediocre names and non-obvious semantics, so aren't
167 /// currently on a path to potential stabilization.
168 impl<R: ops::Try> ControlFlow<R, R::Output> {
169 /// Create a `ControlFlow` from any type implementing `Try`.
171 pub(crate) fn from_try(r: R) -> Self {
173 ControlFlow::Continue(v) => ControlFlow::Continue(v),
174 ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)),
178 /// Convert a `ControlFlow` into any type implementing `Try`;
180 pub(crate) fn into_try(self) -> R {
182 ControlFlow::Continue(v) => R::from_output(v),
183 ControlFlow::Break(v) => v,
188 impl<B> ControlFlow<B, ()> {
189 /// It's frequently the case that there's no value needed with `Continue`,
190 /// so this provides a way to avoid typing `(())`, if you prefer it.
195 /// #![feature(control_flow_enum)]
196 /// use std::ops::ControlFlow;
198 /// let mut partial_sum = 0;
199 /// let last_used = (1..10).chain(20..25).try_for_each(|x| {
200 /// partial_sum += x;
201 /// if partial_sum > 100 { ControlFlow::Break(x) }
202 /// else { ControlFlow::CONTINUE }
204 /// assert_eq!(last_used.break_value(), Some(22));
206 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
207 pub const CONTINUE: Self = ControlFlow::Continue(());
210 impl<C> ControlFlow<(), C> {
211 /// APIs like `try_for_each` don't need values with `Break`,
212 /// so this provides a way to avoid typing `(())`, if you prefer it.
217 /// #![feature(control_flow_enum)]
218 /// use std::ops::ControlFlow;
220 /// let mut partial_sum = 0;
221 /// (1..10).chain(20..25).try_for_each(|x| {
222 /// if partial_sum > 100 { ControlFlow::BREAK }
223 /// else { partial_sum += x; ControlFlow::CONTINUE }
225 /// assert_eq!(partial_sum, 108);
227 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
228 pub const BREAK: Self = ControlFlow::Break(());