qubit_common/lang/argument/error.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # Argument Validation Errors
10//!
11//! Defines error types related to argument validation.
12//!
13//! # Author
14//!
15//! Haixing Hu
16
17use std::fmt;
18
19/// Argument validation error
20///
21/// Returned when an argument does not satisfy validation conditions.
22///
23/// # Features
24///
25/// - Contains detailed error messages
26/// - Implements standard error traits
27/// - Supports conversion from strings
28///
29/// # Examples
30///
31/// ```rust
32/// use qubit_common::lang::argument::ArgumentError;
33///
34/// let error = ArgumentError::new("Invalid argument");
35/// assert_eq!(error.message(), "Invalid argument");
36/// ```
37///
38/// # Author
39///
40/// Haixing Hu
41///
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ArgumentError {
44 message: String,
45}
46
47impl ArgumentError {
48 /// Create a new argument error
49 ///
50 /// # Parameters
51 ///
52 /// * `message` - Error message
53 ///
54 /// # Examples
55 ///
56 /// ```rust
57 /// use qubit_common::lang::argument::ArgumentError;
58 ///
59 /// let error = ArgumentError::new("Value cannot be negative");
60 /// ```
61 #[inline]
62 pub fn new(message: impl Into<String>) -> Self {
63 Self {
64 message: message.into(),
65 }
66 }
67
68 /// Get the error message
69 ///
70 /// # Returns
71 ///
72 /// Returns a reference to the error message
73 #[inline]
74 pub fn message(&self) -> &str {
75 &self.message
76 }
77}
78
79impl fmt::Display for ArgumentError {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "{}", self.message)
82 }
83}
84
85impl std::error::Error for ArgumentError {}
86
87impl From<String> for ArgumentError {
88 #[inline]
89 fn from(message: String) -> Self {
90 Self::new(message)
91 }
92}
93
94impl From<&str> for ArgumentError {
95 #[inline]
96 fn from(message: &str) -> Self {
97 Self::new(message)
98 }
99}
100
101/// Argument validation result type
102///
103/// Unified result type for all argument validation operations.
104///
105/// # Examples
106///
107/// ```rust
108/// use qubit_common::lang::argument::{ArgumentResult, ArgumentError};
109///
110/// fn validate_positive(value: i32) -> ArgumentResult<i32> {
111/// if value > 0 {
112/// Ok(value)
113/// } else {
114/// Err(ArgumentError::new("Value must be positive"))
115/// }
116/// }
117/// ```
118///
119/// # Author
120///
121/// Haixing Hu
122///
123pub type ArgumentResult<T> = Result<T, ArgumentError>;