Skip to main content

no_break/
lib.rs

1/*
2 * SPDX-FileCopyrightText: 2024 Sebastiano Vigna
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
5 */
6
7#![doc = include_str!("../README.md")]
8
9use core::ops::ControlFlow;
10
11/// A [`ControlFlow::Break`] type that can never happen.
12///
13/// This enum has the same purpose of [`std::convert::Infallible`], but it is
14/// specific to control flows. It should be ultimately replaced by the
15/// [`!`] type if it becomes stable.
16pub enum Unbreakable {}
17
18/// A trait to extract continuation values from [control flows](ControlFlow)
19/// that never break.
20///
21/// See the [crate documentation](crate) for more information.
22pub trait NoBreak {
23    /// The type of the value in the [`Continue`](ControlFlow::Continue)
24    /// variant of the control flow.
25    type Continue;
26    /// Returns the continue value of the control flow.
27    fn continue_value_no_break(self) -> Self::Continue;
28}
29
30impl<C> NoBreak for ControlFlow<Unbreakable, C> {
31    type Continue = C;
32    /// Force a typesafe, compile-time check that the control flow will never
33    /// break, and extracts the value from the only possible variant.
34    #[inline(always)]
35    fn continue_value_no_break(self) -> C {
36        match self {
37            ControlFlow::Continue(value) => value,
38        }
39    }
40}