snarkvm_console_network_environment/helpers/or_halt.rs
1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::Environment;
17
18/// A trait to unwrap a `Result` or `Halt`.
19pub trait OrHalt<T> {
20 /// Returns the result if it is successful, otherwise halt.
21 fn or_halt<E: Environment>(self) -> T;
22
23 /// Returns the result if it is successful, otherwise halts with the message.
24 fn or_halt_with<E: Environment>(self, msg: &str) -> T;
25}
26
27impl<T, Error: core::fmt::Display> OrHalt<T> for Result<T, Error> {
28 /// Returns the result if it is successful, otherwise halt.
29 fn or_halt<E: Environment>(self) -> T {
30 match self {
31 Ok(result) => result,
32 Err(error) => E::halt(error.to_string()),
33 }
34 }
35
36 /// Returns the result if it is successful, otherwise halts with the message.
37 fn or_halt_with<E: Environment>(self, msg: &str) -> T {
38 match self {
39 Ok(result) => result,
40 Err(error) => E::halt(format!("{msg}: {error}")),
41 }
42 }
43}