1use core::fmt;
2use littlefs_rust_core::{
3 LFS_ERR_CORRUPT, LFS_ERR_EXIST, LFS_ERR_INVAL, LFS_ERR_IO, LFS_ERR_ISDIR, LFS_ERR_NAMETOOLONG,
4 LFS_ERR_NOATTR, LFS_ERR_NOENT, LFS_ERR_NOMEM, LFS_ERR_NOSPC, LFS_ERR_NOTDIR, LFS_ERR_NOTEMPTY,
5};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Error {
10 Io,
11 Corrupt,
12 NoEntry,
13 Exists,
14 NotDir,
15 IsDir,
16 NotEmpty,
17 Invalid,
18 NoSpace,
19 NoMemory,
20 NoAttribute,
21 NameTooLong,
22}
23
24impl fmt::Display for Error {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 Error::Io => write!(f, "I/O error"),
28 Error::Corrupt => write!(f, "filesystem corrupt"),
29 Error::NoEntry => write!(f, "no such file or directory"),
30 Error::Exists => write!(f, "file or directory already exists"),
31 Error::NotDir => write!(f, "not a directory"),
32 Error::IsDir => write!(f, "is a directory"),
33 Error::NotEmpty => write!(f, "directory not empty"),
34 Error::Invalid => write!(f, "invalid parameter"),
35 Error::NoSpace => write!(f, "no space left on device"),
36 Error::NoMemory => write!(f, "out of memory"),
37 Error::NoAttribute => write!(f, "no such attribute"),
38 Error::NameTooLong => write!(f, "name too long"),
39 }
40 }
41}
42
43#[cfg(feature = "std")]
44impl std::error::Error for Error {}
45
46impl From<i32> for Error {
47 fn from(code: i32) -> Self {
48 match code {
49 c if c == LFS_ERR_IO => Error::Io,
50 c if c == LFS_ERR_CORRUPT => Error::Corrupt,
51 c if c == LFS_ERR_NOENT => Error::NoEntry,
52 c if c == LFS_ERR_EXIST => Error::Exists,
53 c if c == LFS_ERR_NOTDIR => Error::NotDir,
54 c if c == LFS_ERR_ISDIR => Error::IsDir,
55 c if c == LFS_ERR_NOTEMPTY => Error::NotEmpty,
56 c if c == LFS_ERR_INVAL => Error::Invalid,
57 c if c == LFS_ERR_NOSPC => Error::NoSpace,
58 c if c == LFS_ERR_NOMEM => Error::NoMemory,
59 c if c == LFS_ERR_NOATTR => Error::NoAttribute,
60 c if c == LFS_ERR_NAMETOOLONG => Error::NameTooLong,
61 _ => panic!("unknown LFS error code: {}", code),
62 }
63 }
64}
65
66pub(crate) fn from_lfs_result(code: i32) -> Result<(), Error> {
67 if code == 0 {
68 Ok(())
69 } else {
70 Err(Error::from(code))
71 }
72}
73
74pub(crate) fn from_lfs_size(code: i32) -> Result<u32, Error> {
75 if code >= 0 {
76 Ok(code as u32)
77 } else {
78 Err(Error::from(code))
79 }
80}