ranged_mmap/file/
error.rs

1//! Error types for ranged-mmap
2//! 
3//! ranged-mmap 的错误类型
4
5use std::fmt;
6use std::io;
7
8/// Error type for ranged-mmap operations
9/// 
10/// ranged-mmap 操作的错误类型
11#[derive(Debug)]
12pub enum Error {
13    /// I/O error
14    /// 
15    /// I/O 错误
16    Io(io::Error),
17    
18    /// Empty file cannot be mapped
19    /// 
20    /// 空文件无法映射
21    EmptyFile,
22    
23    /// Buffer too small for range
24    /// 
25    /// 缓冲区太小
26    BufferTooSmall {
27        buffer_len: usize,
28        range_len: u64,
29    },
30
31}
32
33impl fmt::Display for Error {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Error::Io(err) => write!(f, "I/O error: {}", err),
37            Error::EmptyFile => write!(f, "Cannot map empty file / 无法映射空文件"),
38            Error::BufferTooSmall { buffer_len, range_len } => {
39                write!(
40                    f,
41                    "Buffer length {} is smaller than range length {} / 缓冲区长度 {} 小于范围长度 {}",
42                    buffer_len, range_len, buffer_len, range_len
43                )
44            }
45        }
46    }
47}
48
49impl std::error::Error for Error {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Error::Io(err) => Some(err),
53            _ => None,
54        }
55    }
56}
57
58/// Convert from io::Error to Error
59/// 
60/// 从 io::Error 转换到 Error
61impl From<io::Error> for Error {
62    fn from(err: io::Error) -> Self {
63        Error::Io(err)
64    }
65}
66
67/// Convert from Error to io::Error for compatibility
68/// 
69/// 从 Error 转换到 io::Error 以保持兼容性
70impl From<Error> for io::Error {
71    fn from(err: Error) -> Self {
72        match err {
73            Error::Io(io_err) => io_err,
74            Error::EmptyFile => io::Error::new(io::ErrorKind::InvalidInput, err.to_string()),
75            Error::BufferTooSmall { .. } => io::Error::new(io::ErrorKind::InvalidInput, err.to_string())
76        }
77    }
78}
79
80/// Result type alias using our custom Error type
81/// 
82/// 使用自定义 Error 类型的 Result 类型别名
83pub type Result<T> = std::result::Result<T, Error>;
84