1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use std::fmt;

type BoxedError = Box<dyn std::error::Error + Send + Sync>;

/// List of specific errors that may occur when using this library.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    /// A USB transport error occurred.
    ///
    /// This variant is used for all errors reported by the operating system when performing a USB
    /// operation. It may indicate that the USB device was unplugged, that another application or an
    /// operating system driver is currently using it, or that the current user does not have
    /// permission to access it.
    Usb,

    /// No (matching) J-Link device was found.
    ///
    /// This error occurs when calling [`JayLink::open_by_serial`] while no J-Link device is connected
    /// (or no device matching the serial number is connected).
    ///
    /// [`JayLink::open_by_serial`]: struct.JayLink.html#method.open_by_serial
    DeviceNotFound,

    /// Automatic device connection failed because multiple devices were found.
    ///
    /// This error occurs when calling [`JayLink::open_by_serial`] without a serial number while
    /// multiple J-Link devices are connected. This library will refuse to "guess" a device and
    /// requires specifying a serial number in this case. The [`scan_usb`] function can also be used
    /// to find a specific device to connect to.
    ///
    /// [`JayLink::open_by_serial`]: struct.JayLink.html#method.open_by_serial
    /// [`scan_usb`]: fn.scan_usb.html
    MultipleDevicesFound,

    /// A operation was attempted that is not supported by the probe.
    ///
    /// Some operations are not supported by all firmware/hardware versions, and are instead
    /// advertised as optional *capability* bits. This error occurs when the capability bit for an
    /// operation isn't set when that operation is attempted.
    ///
    /// Capabilities can be read by calling [`JayLink::read_capabilities`], which returns a
    /// [`Capabilities`] bitflags struct.
    ///
    /// [`JayLink::read_capabilities`]: struct.JayLink.html#method.read_capabilities
    /// [`Capabilities`]: struct.Capabilities.html
    MissingCapability,

    /// An unspecified error occurred.
    Other,

    #[doc(hidden)]
    __NonExhaustive(crate::private::Private),
}

pub(crate) trait Cause {
    const KIND: ErrorKind;
}

/// The error type used by this library.
///
/// Errors can be introspected by the user by calling [`Error::kind`] and inspecting the returned
/// [`ErrorKind`].
///
/// [`Error::kind`]: #method.kind
/// [`ErrorKind`]: enum.ErrorKind.html
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    inner: BoxedError,
    while_: Option<&'static str>,
}

impl Error {
    pub(crate) fn new(kind: ErrorKind, inner: impl Into<BoxedError>) -> Self {
        Self {
            kind,
            inner: inner.into(),
            while_: None,
        }
    }

    pub(crate) fn with_while(
        kind: ErrorKind,
        inner: impl Into<BoxedError>,
        while_: &'static str,
    ) -> Self {
        Self {
            kind,
            inner: inner.into(),
            while_: Some(while_),
        }
    }

    fn fmt_while(&self) -> String {
        if let Some(while_) = self.while_ {
            format!(" while {}", while_)
        } else {
            String::new()
        }
    }

    /// Returns the [`ErrorKind`] describing this error.
    ///
    /// [`ErrorKind`]: enum.ErrorKind.html
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Prefix foreign errors with further explanation where they're coming from
        match self.kind {
            ErrorKind::Usb => write!(f, "USB error{}: {}", self.fmt_while(), self.inner),
            _ => {
                if let Some(while_) = self.while_ {
                    write!(f, "error{}: {}", while_, self.inner)
                } else {
                    self.inner.fmt(f)
                }
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.inner.source()
    }
}

pub(crate) trait ResultExt<T, E> {
    fn jaylink_err(self) -> Result<T, Error>
    where
        E: Cause + Into<BoxedError>;

    fn jaylink_err_while(self, while_: &'static str) -> Result<T, Error>
    where
        E: Cause + Into<BoxedError>;
}

impl<T, E> ResultExt<T, E> for Result<T, E> {
    fn jaylink_err(self) -> Result<T, Error>
    where
        E: Cause + Into<BoxedError>,
    {
        self.map_err(|e| Error::new(E::KIND, e))
    }

    fn jaylink_err_while(self, while_: &'static str) -> Result<T, Error>
    where
        E: Cause + Into<BoxedError>,
    {
        self.map_err(|e| Error::with_while(E::KIND, e, while_))
    }
}

macro_rules! error_mapping {
    (
        $(
            $errty:ty => $kind:ident,
        )+
    ) => {
        $(
            impl Cause for $errty {
                const KIND: ErrorKind = ErrorKind::$kind;
            }
        )+
    };
}

error_mapping! {
    rusb::Error => Usb,
    String => Other,
}