Skip to content

Commit 95d8b51

Browse files
committed
implement continue_ok and break_ok for ControlFlow
1 parent 3c877f6 commit 95d8b51

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

library/core/src/ops/control_flow.rs

+44
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,28 @@ impl<B, C> ControlFlow<B, C> {
167167
matches!(*self, ControlFlow::Continue(_))
168168
}
169169

170+
/// Converts the `ControlFlow` into an `Result` which is `Ok` if the
171+
/// `ControlFlow` was `Break` and `Err` if otherwise.
172+
///
173+
/// # Examples
174+
///
175+
/// ```
176+
/// #![feature(control_flow_ok)]
177+
///
178+
/// use std::ops::ControlFlow;
179+
///
180+
/// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!"));
181+
/// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3));
182+
/// ```
183+
#[inline]
184+
#[unstable(feature = "control_flow_ok", issue = "140266")]
185+
pub fn break_ok(self) -> Result<B, C> {
186+
match self {
187+
ControlFlow::Continue(c) => Err(c),
188+
ControlFlow::Break(b) => Ok(b),
189+
}
190+
}
191+
170192
/// Converts the `ControlFlow` into an `Option` which is `Some` if the
171193
/// `ControlFlow` was `Break` and `None` otherwise.
172194
///
@@ -198,6 +220,28 @@ impl<B, C> ControlFlow<B, C> {
198220
}
199221
}
200222

223+
/// Converts the `ControlFlow` into an `Result` which is `Ok` if the
224+
/// `ControlFlow` was `Continue` and `Err` if otherwise.
225+
///
226+
/// # Examples
227+
///
228+
/// ```
229+
/// #![feature(control_flow_ok)]
230+
///
231+
/// use std::ops::ControlFlow;
232+
///
233+
/// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!"));
234+
/// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3));
235+
/// ```
236+
#[inline]
237+
#[unstable(feature = "control_flow_ok", issue = "140266")]
238+
pub fn continue_ok(self) -> Result<C, B> {
239+
match self {
240+
ControlFlow::Continue(c) => Ok(c),
241+
ControlFlow::Break(b) => Err(b),
242+
}
243+
}
244+
201245
/// Converts the `ControlFlow` into an `Option` which is `Some` if the
202246
/// `ControlFlow` was `Continue` and `None` otherwise.
203247
///

0 commit comments

Comments
 (0)