use thiserror::Error;
#[derive(Debug, Error)]
pub enum QuantumError {
#[error("Invalid qubit index {index}: must be < {max}")]
InvalidQubit { index: usize, max: usize },
#[error("Invalid measurement target: qubit {0}")]
InvalidMeasurement(usize),
#[error("Quantum state is not normalized (norm = {0:.6})")]
NotNormalized(f64),
#[error("Failed to allocate quantum state with {0} qubits")]
AllocationFailed(usize),
#[error("Operation not supported: {0}")]
UnsupportedOperation(String),
#[error("Control qubit {0} cannot equal target qubit")]
SameControlTarget(usize),
#[error("FFI error: {0}")]
Ffi(String),
#[error("Entropy error: {0}")]
Entropy(String),
#[error("Algorithm error: {0}")]
Algorithm(String),
#[error("Null pointer returned from C library")]
NullPointer,
}
pub type Result<T> = std::result::Result<T, QuantumError>;
#[allow(dead_code)]
pub(crate) fn check_result(code: i32, context: &str) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(QuantumError::Ffi(format!("{}: error code {}", context, code)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_display() {
let err = QuantumError::InvalidQubit { index: 5, max: 4 };
assert!(err.to_string().contains("5"));
assert!(err.to_string().contains("4"));
}
#[test]
fn test_check_result() {
assert!(check_result(0, "test").is_ok());
assert!(check_result(-1, "test").is_err());
}
}