1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
use core::ops::Deref;
/// Constant representing a successful operation.
pub const OK: Success = Success { ok: true };
/// Constant representing a failed operation.
pub const FAIL: Success = Success { ok: false };
/// Structure representing the success state of an operation.
#[must_use]
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Success {
/// Boolean indicating whether the operation was successful.
pub ok: bool,
}
/// Structure representing the failure state of an operation.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Failure {
/// Boolean indicating whether the operation failed.
pub fail: bool,
}
impl Deref for Success {
type Target = Failure;
/// Returns a reference to the corresponding `Failure` instance based on the success state.
fn deref(&self) -> &Self::Target {
if self.ok {
&Failure { fail: false }
} else {
&Failure { fail: true }
}
}
}
/// Checks if the given `Success` result indicates a successful operation.
///
/// # Arguments
///
/// * `result` - A `Success` struct representing the result of an operation.
///
/// # Returns
///
/// * `true` if the operation was successful.
/// * `false` if the operation failed.
pub fn is_success(result: Success) -> bool {
result.ok
}
/// Checks if the given `Success` result indicates a failure operation.
///
/// # Arguments
///
/// * `result` - A `Success` struct representing the result of an operation.
///
/// # Returns
///
/// * `true` if the operation failed.
/// * `false` if the operation was successful.
pub fn is_failure(result: Success) -> bool {
!result.ok
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_success() {
assert!(is_success(OK));
assert!(!is_success(FAIL));
}
#[test]
fn test_deref() {
let success = OK;
let failure = FAIL;
assert!(!success.deref().fail);
assert!(failure.deref().fail);
}
}