1use std::fmt;
4
5use crate::TransportError;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Reason {
10 WrongCode,
12 Refused,
14 Busy,
16 Failed,
18 Declined,
20 HoldsSpace,
22}
23
24impl Reason {
25 pub(crate) const fn number(self) -> u8 {
26 match self {
27 Self::WrongCode => 1,
28 Self::Refused => 2,
29 Self::Busy => 3,
30 Self::Failed => 4,
31 Self::Declined => 5,
32 Self::HoldsSpace => 6,
33 }
34 }
35
36 pub(crate) const fn of_number(number: u8) -> Option<Self> {
37 match number {
38 1 => Some(Self::WrongCode),
39 2 => Some(Self::Refused),
40 3 => Some(Self::Busy),
41 4 => Some(Self::Failed),
42 5 => Some(Self::Declined),
43 6 => Some(Self::HoldsSpace),
44 _ => None,
45 }
46 }
47}
48
49impl fmt::Display for Reason {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.write_str(match self {
52 Self::WrongCode => "the pairing code did not match",
53 Self::Refused => {
54 "it does not sync with this device, which it never paired with or revoked"
55 }
56 Self::Busy => "it is syncing with another replica",
57 Self::Failed => "something went wrong on its side",
58 Self::Declined => "the invitation was declined",
59 Self::HoldsSpace => "the library that was invited holds the space already",
60 })
61 }
62}
63
64#[derive(Debug, thiserror::Error)]
66#[non_exhaustive]
67pub enum SyncError {
68 #[error("the connection failed: {0}")]
70 Connection(#[from] TransportError),
71 #[error("the other device broke the protocol: {0}")]
73 Protocol(String),
74 #[error("the other device ended the connection: {0}")]
76 Ended(Reason),
77 #[error("the pairing code did not match")]
80 WrongCode,
81 #[error("the other device is no replica of this library")]
83 NotAReplica,
84 #[error("the invitation was declined")]
86 Declined,
87 #[error("this library holds the space already")]
89 HoldsSpace,
90 #[error(transparent)]
92 Holder(Box<dyn std::error::Error + Send + Sync>),
93}
94
95impl SyncError {
96 pub(crate) fn protocol(what: impl Into<String>) -> Self {
97 Self::Protocol(what.into())
98 }
99
100 pub(crate) fn holder(error: impl std::error::Error + Send + Sync + 'static) -> Self {
101 Self::Holder(Box::new(error))
102 }
103
104 pub(crate) fn either_side(self) -> Self {
106 match self {
107 Self::Ended(Reason::WrongCode) => Self::WrongCode,
108 error => error,
109 }
110 }
111
112 pub(crate) const fn reason(&self) -> Option<Reason> {
115 match self {
116 Self::Ended(_) | Self::Connection(_) => None,
117 Self::NotAReplica => Some(Reason::Refused),
118 Self::WrongCode => Some(Reason::WrongCode),
119 Self::Declined => Some(Reason::Declined),
120 Self::HoldsSpace => Some(Reason::HoldsSpace),
121 Self::Protocol(_) | Self::Holder(_) => Some(Reason::Failed),
122 }
123 }
124}