os/vfs/
error.rs

1//! VFS 错误类型
2//!
3//! 定义了与 POSIX 兼容的文件系统错误码,可通过 [`FsError::to_errno()`] 转换为系统调用错误码。
4
5/// VFS 错误类型
6///
7/// 各错误码对应标准 POSIX errno 值。
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum FsError {
10    // 文件/目录相关
11    NotFound,          // -ENOENT(2): 文件不存在
12    AlreadyExists,     // -EEXIST(17): 文件已存在
13    NotDirectory,      // -ENOTDIR(20): 不是目录
14    IsDirectory,       // -EISDIR(21): 是目录
15    DirectoryNotEmpty, // -ENOTEMPTY(39): 目录非空
16
17    // 权限相关
18    PermissionDenied, // -EACCES(13): 权限被拒绝
19
20    // 文件描述符相关
21    BadFileDescriptor, // -EBADF(9): 无效的文件描述符
22    TooManyOpenFiles,  // -EMFILE(24): 打开的文件过多
23
24    // 参数相关
25    InvalidArgument, // -EINVAL(22): 无效参数
26    NameTooLong,     // -ENAMETOOLONG(36): 文件名过长
27
28    // 文件系统相关
29    ReadOnlyFs, // -EROFS(30): 只读文件系统
30    NoSpace,    // -ENOSPC(28): 设备空间不足
31    IoError,    // -EIO(5): I/O 错误
32    NoDevice,   // -ENODEV(19): 设备不存在
33
34    // 管道相关 (新增)
35    BrokenPipe, // -EPIPE(32): 管道破裂 (读端已关闭)
36    WouldBlock, // -EAGAIN(11): 非阻塞操作将阻塞
37
38    // 网络相关
39    NotConnected, // -ENOTCONN(107): 套接字未连接
40
41    // 其他
42    NotSupported, // -ENOTSUP(95): 操作不支持
43    TooManyLinks, // -EMLINK(31): 硬链接过多
44}
45
46impl FsError {
47    /// 转换为系统调用错误码(负数)
48    pub fn to_errno(&self) -> isize {
49        match self {
50            FsError::NotFound => -2,
51            FsError::IoError => -5,
52            FsError::BadFileDescriptor => -9,
53            FsError::WouldBlock => -11,
54            FsError::PermissionDenied => -13,
55            FsError::AlreadyExists => -17,
56            FsError::NoDevice => -19,
57            FsError::NotDirectory => -20,
58            FsError::IsDirectory => -21,
59            FsError::InvalidArgument => -22,
60            FsError::TooManyOpenFiles => -24,
61            FsError::NoSpace => -28,
62            FsError::ReadOnlyFs => -30,
63            FsError::TooManyLinks => -31,
64            FsError::BrokenPipe => -32,
65            FsError::NameTooLong => -36,
66            FsError::DirectoryNotEmpty => -39,
67            FsError::NotSupported => -95,
68            FsError::NotConnected => -107,
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use crate::{kassert, test_case};
76
77    use super::*;
78
79    test_case!(test_error_codes, {
80        kassert!(FsError::NotFound.to_errno() == -2);
81        kassert!(FsError::PermissionDenied.to_errno() == -13);
82        kassert!(FsError::AlreadyExists.to_errno() == -17);
83    });
84}