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.
10 /// Similar to [`Option`] and [`Result`], this enum can be used with the `?` operator
11 /// to return immediately if the [`Break`] variant is present or otherwise continue normally
12 /// with the value inside the [`Continue`] variant.
16 /// Early-exiting from [`Iterator::try_for_each`]:
18 /// use std::ops::ControlFlow;
20 /// let r = (2..100).try_for_each(|x| {
22 /// return ControlFlow::Break(x)
25 /// ControlFlow::Continue(())
27 /// assert_eq!(r, ControlFlow::Break(13));
30 /// A basic tree traversal:
32 /// use std::ops::ControlFlow;
34 /// pub struct TreeNode<T> {
36 /// left: Option<Box<TreeNode<T>>>,
37 /// right: Option<Box<TreeNode<T>>>,
40 /// impl<T> TreeNode<T> {
41 /// pub fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
42 /// if let Some(left) = &self.left {
43 /// left.traverse_inorder(f)?;
46 /// if let Some(right) = &self.right {
47 /// right.traverse_inorder(f)?;
49 /// ControlFlow::Continue(())
51 /// fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
52 /// Some(Box::new(Self { value, left: None, right: None }))
56 /// let node = TreeNode {
58 /// left: TreeNode::leaf(1),
59 /// right: Some(Box::new(TreeNode {
61 /// left: TreeNode::leaf(5),
62 /// right: TreeNode::leaf(2),
67 /// let res = node.traverse_inorder(&mut |val| {
69 /// ControlFlow::Break(*val)
72 /// ControlFlow::Continue(())
75 /// assert_eq!(res, ControlFlow::Break(-1));
76 /// assert_eq!(sum, 6);
79 /// [`Break`]: ControlFlow::Break
80 /// [`Continue`]: ControlFlow::Continue
81 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
82 #[derive(Debug, Clone, Copy, PartialEq)]
83 pub enum ControlFlow<B, C = ()> {
84 /// Move on to the next phase of the operation as normal.
85 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
88 /// Exit the operation without running subsequent phases.
89 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
92 // Yes, the order of the variants doesn't match the type parameters.
93 // They're in this order so that `ControlFlow<A, B>` <-> `Result<B, A>`
94 // is a no-op conversion in the `Try` implementation.
97 #[unstable(feature = "try_trait_v2", issue = "84277")]
98 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
99 impl<B, C> const ops::Try for ControlFlow<B, C> {
101 type Residual = ControlFlow<B, convert::Infallible>;
104 fn from_output(output: Self::Output) -> Self {
105 ControlFlow::Continue(output)
109 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
111 ControlFlow::Continue(c) => ControlFlow::Continue(c),
112 ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)),
117 #[unstable(feature = "try_trait_v2", issue = "84277")]
118 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
119 impl<B, C> const ops::FromResidual for ControlFlow<B, C> {
121 fn from_residual(residual: ControlFlow<B, convert::Infallible>) -> Self {
123 ControlFlow::Break(b) => ControlFlow::Break(b),
128 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
129 #[rustc_const_unstable(feature = "const_try", issue = "74935")]
130 impl<B, C> const ops::Residual<C> for ControlFlow<B, convert::Infallible> {
131 type TryType = ControlFlow<B, C>;
134 impl<B, C> ControlFlow<B, C> {
135 /// Returns `true` if this is a `Break` variant.
140 /// use std::ops::ControlFlow;
142 /// assert!(ControlFlow::<i32, String>::Break(3).is_break());
143 /// assert!(!ControlFlow::<String, i32>::Continue(3).is_break());
146 #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
147 pub fn is_break(&self) -> bool {
148 matches!(*self, ControlFlow::Break(_))
151 /// Returns `true` if this is a `Continue` variant.
156 /// use std::ops::ControlFlow;
158 /// assert!(!ControlFlow::<i32, String>::Break(3).is_continue());
159 /// assert!(ControlFlow::<String, i32>::Continue(3).is_continue());
162 #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
163 pub fn is_continue(&self) -> bool {
164 matches!(*self, ControlFlow::Continue(_))
167 /// Converts the `ControlFlow` into an `Option` which is `Some` if the
168 /// `ControlFlow` was `Break` and `None` otherwise.
173 /// #![feature(control_flow_enum)]
174 /// use std::ops::ControlFlow;
176 /// assert_eq!(ControlFlow::<i32, String>::Break(3).break_value(), Some(3));
177 /// assert_eq!(ControlFlow::<String, i32>::Continue(3).break_value(), None);
180 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
181 pub fn break_value(self) -> Option<B> {
183 ControlFlow::Continue(..) => None,
184 ControlFlow::Break(x) => Some(x),
188 /// Maps `ControlFlow<B, C>` to `ControlFlow<T, C>` by applying a function
189 /// to the break value in case it exists.
191 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
192 pub fn map_break<T, F>(self, f: F) -> ControlFlow<T, C>
197 ControlFlow::Continue(x) => ControlFlow::Continue(x),
198 ControlFlow::Break(x) => ControlFlow::Break(f(x)),
202 /// Converts the `ControlFlow` into an `Option` which is `Some` if the
203 /// `ControlFlow` was `Continue` and `None` otherwise.
208 /// #![feature(control_flow_enum)]
209 /// use std::ops::ControlFlow;
211 /// assert_eq!(ControlFlow::<i32, String>::Break(3).continue_value(), None);
212 /// assert_eq!(ControlFlow::<String, i32>::Continue(3).continue_value(), Some(3));
215 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
216 pub fn continue_value(self) -> Option<C> {
218 ControlFlow::Continue(x) => Some(x),
219 ControlFlow::Break(..) => None,
223 /// Maps `ControlFlow<B, C>` to `ControlFlow<B, T>` by applying a function
224 /// to the continue value in case it exists.
226 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
227 pub fn map_continue<T, F>(self, f: F) -> ControlFlow<B, T>
232 ControlFlow::Continue(x) => ControlFlow::Continue(f(x)),
233 ControlFlow::Break(x) => ControlFlow::Break(x),
238 /// These are used only as part of implementing the iterator adapters.
239 /// They have mediocre names and non-obvious semantics, so aren't
240 /// currently on a path to potential stabilization.
241 impl<R: ops::Try> ControlFlow<R, R::Output> {
242 /// Create a `ControlFlow` from any type implementing `Try`.
244 pub(crate) fn from_try(r: R) -> Self {
246 ControlFlow::Continue(v) => ControlFlow::Continue(v),
247 ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)),
251 /// Convert a `ControlFlow` into any type implementing `Try`;
253 pub(crate) fn into_try(self) -> R {
255 ControlFlow::Continue(v) => R::from_output(v),
256 ControlFlow::Break(v) => v,
261 impl<B> ControlFlow<B, ()> {
262 /// It's frequently the case that there's no value needed with `Continue`,
263 /// so this provides a way to avoid typing `(())`, if you prefer it.
268 /// #![feature(control_flow_enum)]
269 /// use std::ops::ControlFlow;
271 /// let mut partial_sum = 0;
272 /// let last_used = (1..10).chain(20..25).try_for_each(|x| {
273 /// partial_sum += x;
274 /// if partial_sum > 100 { ControlFlow::Break(x) }
275 /// else { ControlFlow::CONTINUE }
277 /// assert_eq!(last_used.break_value(), Some(22));
279 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
280 pub const CONTINUE: Self = ControlFlow::Continue(());
283 impl<C> ControlFlow<(), C> {
284 /// APIs like `try_for_each` don't need values with `Break`,
285 /// so this provides a way to avoid typing `(())`, if you prefer it.
290 /// #![feature(control_flow_enum)]
291 /// use std::ops::ControlFlow;
293 /// let mut partial_sum = 0;
294 /// (1..10).chain(20..25).try_for_each(|x| {
295 /// if partial_sum > 100 { ControlFlow::BREAK }
296 /// else { partial_sum += x; ControlFlow::CONTINUE }
298 /// assert_eq!(partial_sum, 108);
300 #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
301 pub const BREAK: Self = ControlFlow::Break(());