Skip to content

implement continue_ok and break_ok for ControlFlow #140267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions library/core/src/ops/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,28 @@ impl<B, C> ControlFlow<B, C> {
matches!(*self, ControlFlow::Continue(_))
}

/// Converts the `ControlFlow` into an `Result` which is `Ok` if the
/// `ControlFlow` was `Break` and `Err` if otherwise.
///
/// # Examples
///
/// ```
/// #![feature(control_flow_ok)]
///
/// use std::ops::ControlFlow;
///
/// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").break_ok(), Ok("Stop right there!"));
/// assert_eq!(ControlFlow::<&str, i32>::Continue(3).break_ok(), Err(3));
/// ```
#[inline]
#[unstable(feature = "control_flow_ok", issue = "140266")]
pub fn break_ok(self) -> Result<B, C> {
match self {
ControlFlow::Continue(c) => Err(c),
ControlFlow::Break(b) => Ok(b),
}
}

/// Converts the `ControlFlow` into an `Option` which is `Some` if the
/// `ControlFlow` was `Break` and `None` otherwise.
///
Expand Down Expand Up @@ -198,6 +220,28 @@ impl<B, C> ControlFlow<B, C> {
}
}

/// Converts the `ControlFlow` into an `Result` which is `Ok` if the
/// `ControlFlow` was `Continue` and `Err` if otherwise.
///
/// # Examples
///
/// ```
/// #![feature(control_flow_ok)]
///
/// use std::ops::ControlFlow;
///
/// assert_eq!(ControlFlow::<&str, i32>::Break("Stop right there!").continue_ok(), Err("Stop right there!"));
/// assert_eq!(ControlFlow::<&str, i32>::Continue(3).continue_ok(), Ok(3));
/// ```
#[inline]
#[unstable(feature = "control_flow_ok", issue = "140266")]
pub fn continue_ok(self) -> Result<C, B> {
match self {
ControlFlow::Continue(c) => Ok(c),
ControlFlow::Break(b) => Err(b),
}
}

/// Converts the `ControlFlow` into an `Option` which is `Some` if the
/// `ControlFlow` was `Continue` and `None` otherwise.
///
Expand Down
Loading