1use core::fmt;
4
5#[derive(Debug)]
10#[non_exhaustive]
11pub enum Error {
12 InvalidConfig {
14 field: &'static str,
16 reason: &'static str,
18 },
19 DeviceNotFound,
21 UnsupportedTuner,
23 PllUnlocked,
25 ConfigurationUnknown,
27 DeviceClosed,
29 Busy,
31 Unsupported,
33 StreamClosed {
35 reason: &'static str,
37 },
38 Usb(nusb::Error),
40 Transfer(nusb::transfer::TransferError),
42 Operation {
44 operation: &'static str,
46 source: Box<Error>,
48 },
49 Protocol {
51 operation: &'static str,
53 reason: &'static str,
55 },
56}
57
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60#[non_exhaustive]
61pub enum ErrorKind {
62 InvalidConfig,
64 NotFound,
66 DeviceClosed,
68 DeviceDisconnected,
70 Busy,
72 Unsupported,
74 Usb,
76 StreamClosed,
78 Other,
80}
81
82impl Error {
83 pub(crate) const fn invalid_config(field: &'static str, reason: &'static str) -> Self {
85 Self::InvalidConfig { field, reason }
86 }
87
88 pub(crate) const fn stream_closed(reason: &'static str) -> Self {
90 Self::StreamClosed { reason }
91 }
92
93 pub(crate) const fn protocol(operation: &'static str, reason: &'static str) -> Self {
95 Self::Protocol { operation, reason }
96 }
97
98 pub(crate) fn at(self, operation: &'static str) -> Self {
100 Self::Operation {
101 operation,
102 source: Box::new(self),
103 }
104 }
105
106 pub fn kind(&self) -> ErrorKind {
108 match self {
109 Self::InvalidConfig { .. } => ErrorKind::InvalidConfig,
110 Self::DeviceNotFound => ErrorKind::NotFound,
111 Self::UnsupportedTuner => ErrorKind::Unsupported,
112 Self::PllUnlocked | Self::ConfigurationUnknown => ErrorKind::Other,
113 Self::DeviceClosed => ErrorKind::DeviceClosed,
114 Self::Busy => ErrorKind::Busy,
115 Self::Unsupported => ErrorKind::Unsupported,
116 Self::StreamClosed { .. } => ErrorKind::StreamClosed,
117 Self::Usb(err) => match err.kind() {
118 nusb::ErrorKind::Disconnected => ErrorKind::DeviceDisconnected,
119 nusb::ErrorKind::Busy => ErrorKind::Busy,
120 nusb::ErrorKind::NotFound => ErrorKind::NotFound,
121 nusb::ErrorKind::Unsupported => ErrorKind::Unsupported,
122 _ => ErrorKind::Usb,
123 },
124 Self::Transfer(nusb::transfer::TransferError::Disconnected) => {
125 ErrorKind::DeviceDisconnected
126 }
127 Self::Transfer(_) => ErrorKind::Usb,
128 Self::Operation { source, .. } => source.kind(),
129 Self::Protocol { .. } => ErrorKind::Other,
130 }
131 }
132}
133
134impl fmt::Display for Error {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 match self {
137 Self::InvalidConfig { field, reason } => {
138 write!(f, "invalid configuration for {field}: {reason}")
139 }
140 Self::DeviceNotFound => f.write_str("no matching RTL-SDR device found"),
141 Self::UnsupportedTuner => f.write_str("unsupported tuner (R820T/R828D required)"),
142 Self::PllUnlocked => f.write_str("tuner PLL did not lock"),
143 Self::ConfigurationUnknown => {
144 f.write_str("configuration is unknown; reapply a complete configuration or reopen")
145 }
146 Self::DeviceClosed => f.write_str("RTL-SDR device is closed"),
147 Self::Busy => f.write_str("RTL-SDR device or USB resource is busy"),
148 Self::Unsupported => f.write_str("operation is unsupported"),
149 Self::StreamClosed { reason } => write!(f, "stream closed: {reason}"),
150 Self::Usb(err) => write!(f, "USB error: {err}"),
151 Self::Transfer(err) => write!(f, "USB transfer error: {err}"),
152 Self::Operation { operation, source } => write!(f, "{operation}: {source}"),
153 Self::Protocol { operation, reason } => write!(f, "{operation}: {reason}"),
154 }
155 }
156}
157
158impl std::error::Error for Error {
159 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
160 match self {
161 Self::Usb(err) => Some(err),
162 Self::Transfer(err) => Some(err),
163 Self::Operation { source, .. } => Some(source),
164 _ => None,
165 }
166 }
167}
168
169impl From<nusb::Error> for Error {
170 fn from(value: nusb::Error) -> Self {
171 Self::Usb(value)
172 }
173}
174
175impl From<nusb::transfer::TransferError> for Error {
176 fn from(value: nusb::transfer::TransferError) -> Self {
177 Self::Transfer(value)
178 }
179}
180
181pub type Result<T> = core::result::Result<T, Error>;
183
184#[cfg(test)]
185mod tests {
186 use std::error::Error as _;
187
188 use super::{Error, ErrorKind};
189
190 #[test]
191 fn transfer_errors_preserve_their_source_and_are_not_configuration_errors() {
192 let err = Error::from(nusb::transfer::TransferError::InvalidArgument);
193
194 assert!(matches!(
195 &err,
196 Error::Transfer(nusb::transfer::TransferError::InvalidArgument)
197 ));
198 assert_eq!(err.kind(), ErrorKind::Usb);
199 assert!(err.source().is_some());
200 }
201
202 #[test]
203 fn transfer_disconnects_have_their_own_error_category() {
204 let err = Error::from(nusb::transfer::TransferError::Disconnected);
205
206 assert_eq!(err.kind(), ErrorKind::DeviceDisconnected);
207 assert!(err.source().is_some());
208 }
209
210 #[test]
211 fn configuration_errors_expose_the_field_and_reason() {
212 let err = Error::invalid_config("frequency_hz", "must be nonzero");
213
214 assert!(matches!(
215 &err,
216 Error::InvalidConfig {
217 field: "frequency_hz",
218 reason: "must be nonzero"
219 }
220 ));
221 assert_eq!(err.kind(), ErrorKind::InvalidConfig);
222 }
223
224 #[test]
225 fn operation_context_preserves_source_category() {
226 let err =
227 Error::from(nusb::transfer::TransferError::Fault).at("applying receiver configuration");
228
229 assert_eq!(err.kind(), ErrorKind::Usb);
230 assert!(
231 err.to_string()
232 .starts_with("applying receiver configuration: USB transfer error:")
233 );
234 assert!(err.source().is_some());
235 }
236
237 #[test]
238 fn operation_context_preserves_disconnect_category() {
239 let err =
240 Error::from(nusb::transfer::TransferError::Disconnected).at("reading receiver samples");
241
242 assert_eq!(err.kind(), ErrorKind::DeviceDisconnected);
243 assert!(err.source().is_some());
244 }
245
246 #[test]
247 fn closed_device_has_its_own_error_category() {
248 assert_eq!(Error::DeviceClosed.kind(), ErrorKind::DeviceClosed);
249 assert_eq!(Error::DeviceClosed.to_string(), "RTL-SDR device is closed");
250 }
251}