const_unwrap/lib.rs
1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! `const-unwrap` provides functions which can be used to unwrap [`Result`]s in
6//! a const context.
7
8#![no_std]
9
10/// Unwraps a [`Result`]'s [`Ok`] variant, or panics.
11///
12/// `const_unwrap_result` is a `const fn`, and may be called in a const context.
13/// Note that, if called from a non-const context, `const_unwrap_result` will
14/// execute at runtime, not at compile time.
15pub const fn const_unwrap_result<T: Copy, E: Copy + core::fmt::Debug>(opt: Result<T, E>) -> T {
16 // Require `E: Debug` because `Result::unwrap` does, and we don't want to
17 // allow code to use `const_unwrap_result` which can't later be transitioned
18 // to `Result::unwrap` once it's const-stable.
19 //
20 // We can't include the error itself in the panic message because
21 // const-panicking only supports string literals, and does not support
22 // format string arguments. There does not appear to be a tracking issue for
23 // this, but the following links may be relevant:
24 // - https://doc.rust-lang.org/beta/unstable-book/library-features/const-format-args.html
25 // - https://doc.rust-lang.org/std/macro.const_format_args.html
26 match opt {
27 Ok(x) => x,
28 Err(_) => panic!("const_unwrap_result called on err `Err` value"),
29 }
30}
31
32const _UNWRAP_OK: usize = const_unwrap_result(Result::<_, bool>::Ok(0));
33
34// The following don't compile. Remove `#[cfg(ignore)]` and compile to verify.
35#[cfg(ignore)]
36mod dont_compile {
37 const _UNWRAP_ERR: usize = const_unwrap_result!(Err(0));
38}