adaq_talib/error.rs
1//! 错误类型定义 / Error type definitions.
2//!
3//! `TaError` 语义映射 TA-Lib 的 `TA_RetCode`(见 TA-Lib `ta_defs.h`)。
4//! `TaError` is the semantic mapping of TA-Lib's `TA_RetCode` (see TA-Lib `ta_defs.h`).
5
6use std::fmt;
7
8/// 本库公开错误类型,对应 TA-Lib `TA_RetCode` 的语义。
9///
10/// Public error type, corresponding to the semantics of TA-Lib `TA_RetCode`.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum TaError {
13 /// 非法参数(对应 `TA_BAD_PARAM`)。例如时间周期 <= 0。
14 /// Invalid parameter (maps to `TA_BAD_PARAM`), e.g. time period <= 0.
15 BadParam(String),
16
17 /// 参数越界(对应 `TA_OUT_OF_RANGE`)。
18 /// Parameter out of range (maps to `TA_OUT_OF_RANGE`).
19 OutOfRange(String),
20
21 /// 库未初始化(对应 `TA_LIB_NOT_INITIALIZED`)。
22 /// Library not initialized (maps to `TA_LIB_NOT_INITIALIZED`).
23 LibNotInitialized,
24
25 /// 内存分配失败(对应 `TA_ALLOC_ERR`)。
26 /// Memory allocation failure (maps to `TA_ALLOC_ERR`).
27 OutOfMemory,
28
29 /// 内部错误(对应 `TA_INTERNAL_ERROR`)。
30 /// Internal error (maps to `TA_INTERNAL_ERROR`).
31 InternalError(String),
32}
33
34impl fmt::Display for TaError {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 match self {
37 TaError::BadParam(s) => write!(f, "Bad parameter: {s}"),
38 TaError::OutOfRange(s) => write!(f, "Out of range: {s}"),
39 TaError::LibNotInitialized => write!(f, "Library not initialized"),
40 TaError::OutOfMemory => write!(f, "Out of memory"),
41 TaError::InternalError(s) => write!(f, "Internal error: {s}"),
42 }
43 }
44}
45
46impl std::error::Error for TaError {}
47
48/// 将周期参数转换为 `Result`,非法则返回 [`TaError::BadParam`]。
49///
50/// Convert a period parameter into a `Result`; returns [`TaError::BadParam`] when invalid.
51#[inline]
52pub(crate) fn check_period(period: usize) -> Result<usize, TaError> {
53 if period == 0 {
54 return Err(TaError::BadParam("time period must be >= 1".into()));
55 }
56 Ok(period)
57}