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, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
38 /// if let Some(left) = &self.left {
39 /// left.traverse_inorder(f)?;
42 /// if let Some(right) = &self.right {
43 /// right.traverse_inorder(f)?;
45 /// ControlFlow::Continue(())
47 /// fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
48 /// Some(Box::new(Self { value, left: None, right: None }))
52 /// let node = TreeNode {
54 /// left: TreeNode::leaf(1),
55 /// right: Some(Box::new(TreeNode {
57 /// left: TreeNode::leaf(5),
58 /// right: TreeNode::leaf(2),
63 /// let res = node.traverse_inorder(&mut |val| {
65 /// ControlFlow::Break(*val)
68 /// ControlFlow::Continue(())
71 /// assert_eq!(res, ControlFlow::Break(-1));
72 /// assert_eq!(sum, 6);
74 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
75 #[derive(Debug, Clone, Copy, PartialEq)]
76 pub enum ControlFlow<B, C = ()> {
77 /// Move on to the next phase of the operation as normal.
78 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
81 /// Exit the operation without running subsequent phases.
82 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
85 // Yes, the order of the variants doesn't match the type parameters.
86 // They're in this order so that `ControlFlow<A, B>` <-> `Result<B, A>`
87 // is a no-op conversion in the `Try` implementation.
90 #[unstable(feature = "try_trait_v2", issue = "84277")]
91 impl<B, C> ops::Try for ControlFlow<B, C> {
93 type Residual = ControlFlow<B, convert::Infallible>;
96 fn from_output(output: Self::Output) -> Self {
97 ControlFlow::Continue(output)
101 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
103 ControlFlow::Continue(c) => ControlFlow::Continue(c),
104 ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)),
109 #[unstable(feature = "try_trait_v2", issue = "84277")]
110 impl<B, C> ops::FromResidual for ControlFlow<B, C> {
112 fn from_residual(residual: ControlFlow<B, convert::Infallible>) -> Self {
114 ControlFlow::Break(b) => ControlFlow::Break(b),
119 impl<B, C> ControlFlow<B, C> {
120 /// Returns `true` if this is a `Break` variant.
125 /// #![feature(control_flow_enum)]
126 /// use std::ops::ControlFlow;
128 /// assert!(ControlFlow::<i32, String>::Break(3).is_break());
129 /// assert!(!ControlFlow::<String, i32>::Continue(3).is_break());
132 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
133 pub fn is_break(&self) -> bool {
134 matches!(*self, ControlFlow::Break(_))
137 /// Returns `true` if this is a `Continue` variant.
142 /// #![feature(control_flow_enum)]
143 /// use std::ops::ControlFlow;
145 /// assert!(!ControlFlow::<i32, String>::Break(3).is_continue());
146 /// assert!(ControlFlow::<String, i32>::Continue(3).is_continue());
149 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
150 pub fn is_continue(&self) -> bool {
151 matches!(*self, ControlFlow::Continue(_))
154 /// Converts the `ControlFlow` into an `Option` which is `Some` if the
155 /// `ControlFlow` was `Break` and `None` otherwise.
160 /// #![feature(control_flow_enum)]
161 /// use std::ops::ControlFlow;
163 /// assert_eq!(ControlFlow::<i32, String>::Break(3).break_value(), Some(3));
164 /// assert_eq!(ControlFlow::<String, i32>::Continue(3).break_value(), None);
167 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
168 pub fn break_value(self) -> Option<B> {
170 ControlFlow::Continue(..) => None,
171 ControlFlow::Break(x) => Some(x),
175 /// Maps `ControlFlow<B, C>` to `ControlFlow<T, C>` by applying a function
176 /// to the break value in case it exists.
178 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
179 pub fn map_break<T, F>(self, f: F) -> ControlFlow<T, C>
184 ControlFlow::Continue(x) => ControlFlow::Continue(x),
185 ControlFlow::Break(x) => ControlFlow::Break(f(x)),
190 /// These are used only as part of implementing the iterator adapters.
191 /// They have mediocre names and non-obvious semantics, so aren't
192 /// currently on a path to potential stabilization.
193 impl<R: ops::Try> ControlFlow<R, R::Output> {
194 /// Create a `ControlFlow` from any type implementing `Try`.
196 pub(crate) fn from_try(r: R) -> Self {
198 ControlFlow::Continue(v) => ControlFlow::Continue(v),
199 ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)),
203 /// Convert a `ControlFlow` into any type implementing `Try`;
205 pub(crate) fn into_try(self) -> R {
207 ControlFlow::Continue(v) => R::from_output(v),
208 ControlFlow::Break(v) => v,
213 impl<B> ControlFlow<B, ()> {
214 /// It's frequently the case that there's no value needed with `Continue`,
215 /// so this provides a way to avoid typing `(())`, if you prefer it.
220 /// #![feature(control_flow_enum)]
221 /// use std::ops::ControlFlow;
223 /// let mut partial_sum = 0;
224 /// let last_used = (1..10).chain(20..25).try_for_each(|x| {
225 /// partial_sum += x;
226 /// if partial_sum > 100 { ControlFlow::Break(x) }
227 /// else { ControlFlow::CONTINUE }
229 /// assert_eq!(last_used.break_value(), Some(22));
231 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
232 pub const CONTINUE: Self = ControlFlow::Continue(());
235 impl<C> ControlFlow<(), C> {
236 /// APIs like `try_for_each` don't need values with `Break`,
237 /// so this provides a way to avoid typing `(())`, if you prefer it.
242 /// #![feature(control_flow_enum)]
243 /// use std::ops::ControlFlow;
245 /// let mut partial_sum = 0;
246 /// (1..10).chain(20..25).try_for_each(|x| {
247 /// if partial_sum > 100 { ControlFlow::BREAK }
248 /// else { partial_sum += x; ControlFlow::CONTINUE }
250 /// assert_eq!(partial_sum, 108);
252 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
253 pub const BREAK: Self = ControlFlow::Break(());