platform_data/flow.rs
1use std::ops::ControlFlow;
2
3/// Represents the control flow of an operation, similar to `ControlFlow`.
4///
5/// This is a simplified enum that can be used with iterators and callbacks
6/// to indicate whether to continue or break early.
7#[repr(usize)]
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Flow {
10 Continue,
11 Break,
12}
13
14impl Flow {
15 /// Returns `true` if this is `Flow::Continue`.
16 #[must_use]
17 pub const fn is_continue(&self) -> bool {
18 matches!(self, Self::Continue)
19 }
20
21 /// Returns `true` if this is `Flow::Break`.
22 #[must_use]
23 pub const fn is_break(&self) -> bool {
24 matches!(self, Self::Break)
25 }
26
27 /// Converts this `Flow` into a `ControlFlow` that can be used with `try_for_each`.
28 ///
29 /// ```
30 /// use platform_data::Flow;
31 /// use std::ops::ControlFlow;
32 ///
33 /// let mut count = 0;
34 /// let result = (0..10).try_for_each(|i| {
35 /// count += 1;
36 /// if i == 5 { Flow::Break.into_control_flow() } else { Flow::Continue.into_control_flow() }
37 /// });
38 /// assert_eq!(count, 6);
39 /// ```
40 pub const fn into_control_flow(self) -> ControlFlow<()> {
41 match self {
42 Self::Continue => ControlFlow::Continue(()),
43 Self::Break => ControlFlow::Break(()),
44 }
45 }
46}
47
48impl<C, B> From<ControlFlow<C, B>> for Flow {
49 fn from(flow: ControlFlow<C, B>) -> Self {
50 match flow {
51 ControlFlow::Continue(_) => Self::Continue,
52 ControlFlow::Break(_) => Self::Break,
53 }
54 }
55}
56
57impl From<Flow> for ControlFlow<()> {
58 fn from(flow: Flow) -> Self {
59 match flow {
60 Flow::Continue => Self::Continue(()),
61 Flow::Break => Self::Break(()),
62 }
63 }
64}