Skip to main content

qubit_argument/argument/
argument_error.rs

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