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
use libmtp_sys as ffi;
use std::string::FromUtf8Error;
use thiserror::Error as ErrorTrait;
#[derive(Debug, Clone, Copy)]
pub enum MtpErrorKind {
General,
PtpLayer,
UsbLayer,
MemoryAllocation,
NoDeviceAttached,
StorageFull,
Connecting,
Cancelled,
}
impl MtpErrorKind {
pub(crate) fn from_error_number(error_code: ffi::LIBMTP_error_number_t) -> Option<Self> {
match error_code {
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_NONE => None,
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_GENERAL => Some(Self::General),
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_PTP_LAYER => Some(Self::PtpLayer),
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_USB_LAYER => Some(Self::UsbLayer),
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_MEMORY_ALLOCATION => {
Some(Self::MemoryAllocation)
}
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_NO_DEVICE_ATTACHED => {
Some(Self::NoDeviceAttached)
}
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_STORAGE_FULL => Some(Self::StorageFull),
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_CONNECTING => Some(Self::Connecting),
ffi::LIBMTP_error_number_t_LIBMTP_ERROR_CANCELLED => Some(Self::Cancelled),
_ => None,
}
}
}
#[derive(Debug, Clone, ErrorTrait)]
pub enum Error {
#[error("Unknown error (possibly a libmtp undocumented error)")]
Unknown,
#[error("Internal libmtp ({kind:?}): {text}")]
MtpError { kind: MtpErrorKind, text: String },
#[error("Utf8 error ({source})")]
Utf8Error { source: FromUtf8Error },
}
impl Default for Error {
fn default() -> Self {
Error::Unknown
}
}
impl Error {
pub(crate) unsafe fn from_latest_error(mut list: *const ffi::LIBMTP_error_t) -> Option<Self> {
if list.is_null() {
None
} else {
while !(*list).next.is_null() {
list = (*list).next;
}
let error_t = &*list;
let kind = MtpErrorKind::from_error_number(error_t.errornumber)?;
let u8vec = cstr_to_u8vec!(error_t.error_text);
let text = String::from_utf8_lossy(&u8vec).into_owned();
Some(Error::MtpError { kind, text })
}
}
}
impl From<FromUtf8Error> for Error {
fn from(source: FromUtf8Error) -> Self {
Error::Utf8Error { source }
}
}