bp3d_util/result.rs
1// Copyright (c) 2025, BlockProject 3D
2//
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without modification,
6// are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of BlockProject 3D nor the names of its contributors
14// may be used to endorse or promote products derived from this software
15// without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29//! Result utilities.
30
31use crate::extension;
32use std::error::Error;
33
34extension! {
35 /// Result extensions designed to simplify console based tools.
36 pub extension ResultExt<T, E>: Result<T, E> {
37 /// Expects a given result to unwrap without issues, in case the result is an error,
38 /// this function exits the program.
39 ///
40 /// # Arguments
41 ///
42 /// * `msg`: a failure context message.
43 /// * `code`: the exit code to exit the program with in case of error.
44 ///
45 /// returns: T the value if no errors have occurred.
46 fn expect_exit(self, msg: &str, code: i32) -> T;
47 }
48}
49
50impl<T, E: Error> ResultExt<T, E> for Result<T, E> {
51 fn expect_exit(self, msg: &str, code: i32) -> T {
52 match self {
53 Ok(v) => v,
54 Err(e) => {
55 eprintln!("{}: {}", msg, e);
56 std::process::exit(code);
57 }
58 }
59 }
60}
61
62/// Generates a match block which returns errors to circumvent rust borrow checker defects.
63#[macro_export]
64macro_rules! try_res {
65 ($value: expr => |$e: ident| $err: expr) => {
66 match $value {
67 Ok(v) => v,
68 Err($e) => return Err($err),
69 }
70 };
71}
72
73/// Generates a match block which returns errors to circumvent rust borrow checker defects.
74#[macro_export]
75macro_rules! try_opt {
76 ($value: expr => $err: expr) => {
77 match $value {
78 Some(v) => v,
79 None => return Err($err),
80 }
81 };
82}