Skip to main content

omgkit_core/
error.rs

1//! 核心层错误类型。
2//!
3//! L0 只关心结构性错误(下标越界、自环、规模溢出)。化学语义错误
4//! (价键异常、芳香性感知失败)属于 L2,由 `omgkit-chem` 自行定义。
5
6use core::fmt;
7
8/// 核心层错误。
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12    /// 原子下标越界
13    AtomIndexOutOfRange {
14        /// 越界的下标
15        index: u32,
16        /// 实际原子数
17        num_atoms: u32,
18    },
19    /// 试图添加自环。分子图中不存在自环。
20    SelfLoop {
21        /// 两端相同的那个原子
22        atom: u32,
23    },
24    /// 分子下标越界
25    MolIndexOutOfRange {
26        /// 越界的下标
27        index: u32,
28        /// 实际分子数
29        num_mols: u32,
30    },
31    /// 键下标越界
32    BondIndexOutOfRange {
33        /// 越界的下标
34        index: u32,
35        /// 实际键数
36        num_bonds: u32,
37    },
38    /// 批规模超出 `u32` 索引上限
39    BatchTooLarge {
40        /// 溢出的是哪一类实体("atoms" / "bonds" / "molecules")
41        what: &'static str,
42        /// 实际数量
43        count: usize,
44    },
45}
46
47impl fmt::Display for Error {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::AtomIndexOutOfRange { index, num_atoms } => {
51                write!(f, "原子下标 {index} 越界(共 {num_atoms} 个原子)")
52            }
53            Self::SelfLoop { atom } => {
54                write!(f, "原子 {atom} 上出现自环;分子图中不允许自环")
55            }
56            Self::BondIndexOutOfRange { index, num_bonds } => {
57                write!(f, "键下标 {index} 越界(共 {num_bonds} 条键)")
58            }
59            Self::MolIndexOutOfRange { index, num_mols } => {
60                write!(f, "分子下标 {index} 越界(共 {num_mols} 个分子)")
61            }
62            Self::BatchTooLarge { what, count } => {
63                write!(f, "批中 {what} 数量 {count} 超出 u32 索引上限")
64            }
65        }
66    }
67}
68
69impl std::error::Error for Error {}
70
71/// 核心层的 `Result` 别名。
72pub type Result<T> = core::result::Result<T, Error>;