]> git.lizzy.rs Git - rust.git/blob - library/core/src/ops/control_flow.rs
Merge commit '2b2190cb5667cdd276a24ef8b9f3692209c54a89' into clippyup
[rust.git] / library / core / src / ops / control_flow.rs
1 use crate::{convert, ops};
2
3 /// Used to tell an operation whether it should exit early or go on as usual.
4 ///
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.
9 ///
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.
13 ///
14 /// # Examples
15 ///
16 /// Early-exiting from [`Iterator::try_for_each`]:
17 /// ```
18 /// use std::ops::ControlFlow;
19 ///
20 /// let r = (2..100).try_for_each(|x| {
21 ///     if 403 % x == 0 {
22 ///         return ControlFlow::Break(x)
23 ///     }
24 ///
25 ///     ControlFlow::Continue(())
26 /// });
27 /// assert_eq!(r, ControlFlow::Break(13));
28 /// ```
29 ///
30 /// A basic tree traversal:
31 /// ```
32 /// use std::ops::ControlFlow;
33 ///
34 /// pub struct TreeNode<T> {
35 ///     value: T,
36 ///     left: Option<Box<TreeNode<T>>>,
37 ///     right: Option<Box<TreeNode<T>>>,
38 /// }
39 ///
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)?;
44 ///         }
45 ///         f(&self.value)?;
46 ///         if let Some(right) = &self.right {
47 ///             right.traverse_inorder(f)?;
48 ///         }
49 ///         ControlFlow::Continue(())
50 ///     }
51 ///     fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
52 ///         Some(Box::new(Self { value, left: None, right: None }))
53 ///     }
54 /// }
55 ///
56 /// let node = TreeNode {
57 ///     value: 0,
58 ///     left: TreeNode::leaf(1),
59 ///     right: Some(Box::new(TreeNode {
60 ///         value: -1,
61 ///         left: TreeNode::leaf(5),
62 ///         right: TreeNode::leaf(2),
63 ///     }))
64 /// };
65 /// let mut sum = 0;
66 ///
67 /// let res = node.traverse_inorder(&mut |val| {
68 ///     if *val < 0 {
69 ///         ControlFlow::Break(*val)
70 ///     } else {
71 ///         sum += *val;
72 ///         ControlFlow::Continue(())
73 ///     }
74 /// });
75 /// assert_eq!(res, ControlFlow::Break(-1));
76 /// assert_eq!(sum, 6);
77 /// ```
78 ///
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")]
86     #[lang = "Continue"]
87     Continue(C),
88     /// Exit the operation without running subsequent phases.
89     #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
90     #[lang = "Break"]
91     Break(B),
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.
95 }
96
97 #[unstable(feature = "try_trait_v2", issue = "84277")]
98 impl<B, C> ops::Try for ControlFlow<B, C> {
99     type Output = C;
100     type Residual = ControlFlow<B, convert::Infallible>;
101
102     #[inline]
103     fn from_output(output: Self::Output) -> Self {
104         ControlFlow::Continue(output)
105     }
106
107     #[inline]
108     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
109         match self {
110             ControlFlow::Continue(c) => ControlFlow::Continue(c),
111             ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)),
112         }
113     }
114 }
115
116 #[unstable(feature = "try_trait_v2", issue = "84277")]
117 impl<B, C> ops::FromResidual for ControlFlow<B, C> {
118     #[inline]
119     fn from_residual(residual: ControlFlow<B, convert::Infallible>) -> Self {
120         match residual {
121             ControlFlow::Break(b) => ControlFlow::Break(b),
122         }
123     }
124 }
125
126 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
127 impl<B, C> ops::Residual<C> for ControlFlow<B, convert::Infallible> {
128     type TryType = ControlFlow<B, C>;
129 }
130
131 impl<B, C> ControlFlow<B, C> {
132     /// Returns `true` if this is a `Break` variant.
133     ///
134     /// # Examples
135     ///
136     /// ```
137     /// use std::ops::ControlFlow;
138     ///
139     /// assert!(ControlFlow::<i32, String>::Break(3).is_break());
140     /// assert!(!ControlFlow::<String, i32>::Continue(3).is_break());
141     /// ```
142     #[inline]
143     #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
144     pub fn is_break(&self) -> bool {
145         matches!(*self, ControlFlow::Break(_))
146     }
147
148     /// Returns `true` if this is a `Continue` variant.
149     ///
150     /// # Examples
151     ///
152     /// ```
153     /// use std::ops::ControlFlow;
154     ///
155     /// assert!(!ControlFlow::<i32, String>::Break(3).is_continue());
156     /// assert!(ControlFlow::<String, i32>::Continue(3).is_continue());
157     /// ```
158     #[inline]
159     #[stable(feature = "control_flow_enum_is", since = "1.59.0")]
160     pub fn is_continue(&self) -> bool {
161         matches!(*self, ControlFlow::Continue(_))
162     }
163
164     /// Converts the `ControlFlow` into an `Option` which is `Some` if the
165     /// `ControlFlow` was `Break` and `None` otherwise.
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// #![feature(control_flow_enum)]
171     /// use std::ops::ControlFlow;
172     ///
173     /// assert_eq!(ControlFlow::<i32, String>::Break(3).break_value(), Some(3));
174     /// assert_eq!(ControlFlow::<String, i32>::Continue(3).break_value(), None);
175     /// ```
176     #[inline]
177     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
178     pub fn break_value(self) -> Option<B> {
179         match self {
180             ControlFlow::Continue(..) => None,
181             ControlFlow::Break(x) => Some(x),
182         }
183     }
184
185     /// Maps `ControlFlow<B, C>` to `ControlFlow<T, C>` by applying a function
186     /// to the break value in case it exists.
187     #[inline]
188     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
189     pub fn map_break<T, F>(self, f: F) -> ControlFlow<T, C>
190     where
191         F: FnOnce(B) -> T,
192     {
193         match self {
194             ControlFlow::Continue(x) => ControlFlow::Continue(x),
195             ControlFlow::Break(x) => ControlFlow::Break(f(x)),
196         }
197     }
198
199     /// Converts the `ControlFlow` into an `Option` which is `Some` if the
200     /// `ControlFlow` was `Continue` and `None` otherwise.
201     ///
202     /// # Examples
203     ///
204     /// ```
205     /// #![feature(control_flow_enum)]
206     /// use std::ops::ControlFlow;
207     ///
208     /// assert_eq!(ControlFlow::<i32, String>::Break(3).continue_value(), None);
209     /// assert_eq!(ControlFlow::<String, i32>::Continue(3).continue_value(), Some(3));
210     /// ```
211     #[inline]
212     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
213     pub fn continue_value(self) -> Option<C> {
214         match self {
215             ControlFlow::Continue(x) => Some(x),
216             ControlFlow::Break(..) => None,
217         }
218     }
219
220     /// Maps `ControlFlow<B, C>` to `ControlFlow<B, T>` by applying a function
221     /// to the continue value in case it exists.
222     #[inline]
223     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
224     pub fn map_continue<T, F>(self, f: F) -> ControlFlow<B, T>
225     where
226         F: FnOnce(C) -> T,
227     {
228         match self {
229             ControlFlow::Continue(x) => ControlFlow::Continue(f(x)),
230             ControlFlow::Break(x) => ControlFlow::Break(x),
231         }
232     }
233 }
234
235 /// These are used only as part of implementing the iterator adapters.
236 /// They have mediocre names and non-obvious semantics, so aren't
237 /// currently on a path to potential stabilization.
238 impl<R: ops::Try> ControlFlow<R, R::Output> {
239     /// Create a `ControlFlow` from any type implementing `Try`.
240     #[inline]
241     pub(crate) fn from_try(r: R) -> Self {
242         match R::branch(r) {
243             ControlFlow::Continue(v) => ControlFlow::Continue(v),
244             ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)),
245         }
246     }
247
248     /// Convert a `ControlFlow` into any type implementing `Try`;
249     #[inline]
250     pub(crate) fn into_try(self) -> R {
251         match self {
252             ControlFlow::Continue(v) => R::from_output(v),
253             ControlFlow::Break(v) => v,
254         }
255     }
256 }
257
258 impl<B> ControlFlow<B, ()> {
259     /// It's frequently the case that there's no value needed with `Continue`,
260     /// so this provides a way to avoid typing `(())`, if you prefer it.
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// #![feature(control_flow_enum)]
266     /// use std::ops::ControlFlow;
267     ///
268     /// let mut partial_sum = 0;
269     /// let last_used = (1..10).chain(20..25).try_for_each(|x| {
270     ///     partial_sum += x;
271     ///     if partial_sum > 100 { ControlFlow::Break(x) }
272     ///     else { ControlFlow::CONTINUE }
273     /// });
274     /// assert_eq!(last_used.break_value(), Some(22));
275     /// ```
276     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
277     pub const CONTINUE: Self = ControlFlow::Continue(());
278 }
279
280 impl<C> ControlFlow<(), C> {
281     /// APIs like `try_for_each` don't need values with `Break`,
282     /// so this provides a way to avoid typing `(())`, if you prefer it.
283     ///
284     /// # Examples
285     ///
286     /// ```
287     /// #![feature(control_flow_enum)]
288     /// use std::ops::ControlFlow;
289     ///
290     /// let mut partial_sum = 0;
291     /// (1..10).chain(20..25).try_for_each(|x| {
292     ///     if partial_sum > 100 { ControlFlow::BREAK }
293     ///     else { partial_sum += x; ControlFlow::CONTINUE }
294     /// });
295     /// assert_eq!(partial_sum, 108);
296     /// ```
297     #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")]
298     pub const BREAK: Self = ControlFlow::Break(());
299 }