Skip to main content

memguard_rs/
error.rs

1//! Error types for the memguard-rs crate.
2
3/// Errors that can occur during memory operations.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Error {
6    /// Failed to lock memory (e.g., `mlock` or `VirtualLock` returned an error).
7    ///
8    /// Common causes:
9    /// - `RLIMIT_MEMLOCK` is too low (Unix)
10    /// - The process lacks `CAP_IPC_LOCK` (Linux)
11    /// - The address space is too fragmented (Windows)
12    LockFailed,
13
14    /// Failed to unlock memory (e.g., `munlock` or `VirtualUnlock` returned an error).
15    ///
16    /// This is rare and usually indicates the memory was already unlocked
17    /// or the address/size does not match a previous lock call.
18    UnlockFailed,
19
20    /// Failed to allocate memory for a secret.
21    AllocationFailed,
22}
23
24/// A specialized [`Result`] type for memguard-rs operations.
25pub type Result<T> = core::result::Result<T, Error>;
26
27#[cfg(feature = "std")]
28impl std::fmt::Display for Error {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        let msg = match self {
31            Error::LockFailed => "failed to lock memory",
32            Error::UnlockFailed => "failed to unlock memory",
33            Error::AllocationFailed => "failed to allocate memory",
34        };
35        f.write_str(msg)
36    }
37}
38
39#[cfg(feature = "std")]
40impl std::error::Error for Error {}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn error_equality() {
48        assert_eq!(Error::LockFailed, Error::LockFailed);
49        assert_ne!(Error::LockFailed, Error::UnlockFailed);
50    }
51
52    #[test]
53    fn error_copy() {
54        let err = Error::LockFailed;
55        let copied = err;
56        assert_eq!(err, copied);
57    }
58
59    #[cfg(feature = "std")]
60    #[test]
61    fn error_display() {
62        assert_eq!(format!("{}", Error::LockFailed), "failed to lock memory");
63        assert_eq!(
64            format!("{}", Error::UnlockFailed),
65            "failed to unlock memory"
66        );
67        assert_eq!(
68            format!("{}", Error::AllocationFailed),
69            "failed to allocate memory"
70        );
71    }
72}