libq/
error.rs

1//! Error handling for lib-Q
2//!
3//! This module defines the error types used throughout the library.
4
5use core::fmt;
6
7/// The error type for lib-Q operations
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum Error {
10    /// Invalid key size
11    InvalidKeySize { expected: usize, actual: usize },
12
13    /// Invalid signature size
14    InvalidSignatureSize { expected: usize, actual: usize },
15
16    /// Invalid nonce size
17    InvalidNonceSize { expected: usize, actual: usize },
18
19    /// Invalid message size
20    InvalidMessageSize { max: usize, actual: usize },
21
22    /// Invalid ciphertext size
23    InvalidCiphertextSize { expected: usize, actual: usize },
24
25    /// Invalid plaintext size
26    InvalidPlaintextSize { expected: usize, actual: usize },
27
28    /// Invalid hash size
29    InvalidHashSize { expected: usize, actual: usize },
30
31    /// Invalid algorithm
32    InvalidAlgorithm { algorithm: String },
33
34    /// Invalid security level
35    InvalidSecurityLevel {
36        level: u32,
37        supported: &'static [u32],
38    },
39
40    /// Verification failed
41    VerificationFailed { operation: String },
42
43    /// Encryption failed
44    EncryptionFailed { operation: String },
45
46    /// Decryption failed
47    DecryptionFailed { operation: String },
48
49    /// Key generation failed
50    KeyGenerationFailed { operation: String },
51
52    /// Random number generation failed
53    RandomGenerationFailed { operation: String },
54
55    /// Memory allocation failed
56    MemoryAllocationFailed { operation: String },
57
58    /// Internal error
59    InternalError { operation: String, details: String },
60
61    /// Not implemented
62    NotImplemented { feature: String },
63
64    /// Unsupported operation
65    UnsupportedOperation { operation: String },
66
67    /// Invalid state
68    InvalidState { state: String },
69}
70
71impl fmt::Display for Error {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Error::InvalidKeySize { expected, actual } => {
75                write!(f, "Invalid key size: expected {expected}, got {actual}")
76            }
77            Error::InvalidSignatureSize { expected, actual } => {
78                write!(
79                    f,
80                    "Invalid signature size: expected {expected}, got {actual}"
81                )
82            }
83            Error::InvalidNonceSize { expected, actual } => {
84                write!(f, "Invalid nonce size: expected {expected}, got {actual}")
85            }
86            Error::InvalidMessageSize { max, actual } => {
87                write!(f, "Invalid message size: maximum {max}, got {actual}")
88            }
89            Error::InvalidCiphertextSize { expected, actual } => {
90                write!(
91                    f,
92                    "Invalid ciphertext size: expected {expected}, got {actual}"
93                )
94            }
95            Error::InvalidPlaintextSize { expected, actual } => {
96                write!(
97                    f,
98                    "Invalid plaintext size: expected {expected}, got {actual}"
99                )
100            }
101            Error::InvalidHashSize { expected, actual } => {
102                write!(f, "Invalid hash size: expected {expected}, got {actual}")
103            }
104            Error::InvalidAlgorithm { algorithm } => {
105                write!(f, "Invalid algorithm: {algorithm}")
106            }
107            Error::InvalidSecurityLevel { level, supported } => {
108                write!(
109                    f,
110                    "Invalid security level: {level} (supported: {supported:?})"
111                )
112            }
113            Error::VerificationFailed { operation } => {
114                write!(f, "Verification failed: {operation}")
115            }
116            Error::EncryptionFailed { operation } => {
117                write!(f, "Encryption failed: {operation}")
118            }
119            Error::DecryptionFailed { operation } => {
120                write!(f, "Decryption failed: {operation}")
121            }
122            Error::KeyGenerationFailed { operation } => {
123                write!(f, "Key generation failed: {operation}")
124            }
125            Error::RandomGenerationFailed { operation } => {
126                write!(f, "Random generation failed: {operation}")
127            }
128            Error::MemoryAllocationFailed { operation } => {
129                write!(f, "Memory allocation failed: {operation}")
130            }
131            Error::InternalError { operation, details } => {
132                write!(f, "Internal error in {operation}: {details}")
133            }
134            Error::NotImplemented { feature } => {
135                write!(f, "Feature not implemented: {feature}")
136            }
137            Error::UnsupportedOperation { operation } => {
138                write!(f, "Unsupported operation: {operation}")
139            }
140            Error::InvalidState { state } => {
141                write!(f, "Invalid state: {state}")
142            }
143        }
144    }
145}
146
147#[cfg(feature = "std")]
148impl std::error::Error for Error {}
149
150/// Result type for lib-Q operations
151pub type Result<T> = core::result::Result<T, Error>;
152
153/// Security levels supported by lib-Q
154pub const SECURITY_LEVELS: &[u32] = &[1, 3, 4, 5];
155
156/// Check if a security level is supported
157pub fn is_supported_security_level(level: u32) -> bool {
158    SECURITY_LEVELS.contains(&level)
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn test_error_display() {
167        let error = Error::InvalidKeySize {
168            expected: 32,
169            actual: 16,
170        };
171        assert_eq!(error.to_string(), "Invalid key size: expected 32, got 16");
172    }
173
174    #[test]
175    fn test_security_levels() {
176        assert!(is_supported_security_level(1));
177        assert!(is_supported_security_level(3));
178        assert!(is_supported_security_level(4));
179        assert!(is_supported_security_level(5));
180        assert!(!is_supported_security_level(2));
181        assert!(!is_supported_security_level(6));
182    }
183}