bpwallet/util.rs
1// Modern, minimalistic & standard-compliant cold wallet library.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2020-2024 by
6// Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
7//
8// Copyright (C) 2020-2024 LNP/BP Standards Association. All rights reserved.
9// Copyright (C) 2020-2024 Dr Maxim Orlovsky. All rights reserved.
10//
11// Licensed under the Apache License, Version 2.0 (the "License");
12// you may not use this file except in compliance with the License.
13// You may obtain a copy of the License at
14//
15// http://www.apache.org/licenses/LICENSE-2.0
16//
17// Unless required by applicable law or agreed to in writing, software
18// distributed under the License is distributed on an "AS IS" BASIS,
19// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20// See the License for the specific language governing permissions and
21// limitations under the License.
22
23// TODO: Move to amplify library
24
25#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
26pub struct MayError<T, E> {
27 pub ok: T,
28 pub err: Option<E>,
29}
30
31impl<T, E> MayError<T, E> {
32 pub fn ok(result: T) -> Self {
33 MayError {
34 ok: result,
35 err: None,
36 }
37 }
38
39 pub fn err(ok: T, err: E) -> Self { MayError { ok, err: Some(err) } }
40
41 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MayError<U, E> {
42 let ok = f(self.ok);
43 MayError { ok, err: self.err }
44 }
45
46 pub fn split(self) -> (T, Option<E>) { (self.ok, self.err) }
47
48 pub fn into_ok(self) -> T { self.ok }
49
50 pub fn into_err(self) -> Option<E> { self.err }
51
52 pub fn unwrap_err(self) -> E { self.err.unwrap() }
53
54 pub fn into_result(self) -> Result<T, E> {
55 match self.err {
56 Some(err) => Err(err),
57 None => Ok(self.ok),
58 }
59 }
60}