libp2p_core/upgrade/error.rs
1// Copyright 2018 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use multistream_select::NegotiationError;
22use std::fmt;
23
24/// Error that can happen when upgrading a connection or substream to use a protocol.
25#[derive(Debug)]
26pub enum UpgradeError<E> {
27 /// Error during the negotiation process.
28 Select(NegotiationError),
29 /// Error during the post-negotiation handshake.
30 Apply(E),
31}
32
33impl<E> UpgradeError<E> {
34 pub fn map_err<F, T>(self, f: F) -> UpgradeError<T>
35 where
36 F: FnOnce(E) -> T
37 {
38 match self {
39 UpgradeError::Select(e) => UpgradeError::Select(e),
40 UpgradeError::Apply(e) => UpgradeError::Apply(f(e)),
41 }
42 }
43
44 pub fn into_err<T>(self) -> UpgradeError<T>
45 where
46 T: From<E>
47 {
48 self.map_err(Into::into)
49 }
50}
51
52impl<E> fmt::Display for UpgradeError<E>
53where
54 E: fmt::Display
55{
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match self {
58 UpgradeError::Select(e) => write!(f, "select error: {}", e),
59 UpgradeError::Apply(e) => write!(f, "upgrade apply error: {}", e),
60 }
61 }
62}
63
64impl<E> std::error::Error for UpgradeError<E>
65where
66 E: std::error::Error + 'static
67{
68 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69 match self {
70 UpgradeError::Select(e) => Some(e),
71 UpgradeError::Apply(e) => Some(e),
72 }
73 }
74}
75
76impl<E> From<NegotiationError> for UpgradeError<E> {
77 fn from(e: NegotiationError) -> Self {
78 UpgradeError::Select(e)
79 }
80}
81