use crate::error::{DaosError, Result};
use daos::daos_handle_t;
#[derive(Debug, Clone, Copy)]
pub struct DaosHandle {
inner: daos_handle_t,
}
impl DaosHandle {
#[inline]
pub unsafe fn from_raw(raw: daos_handle_t) -> Self {
Self { inner: raw }
}
#[inline]
pub fn as_raw(&self) -> daos_handle_t {
self.inner
}
#[inline]
pub fn cookie(&self) -> u64 {
self.inner.cookie
}
}
pub const DAOS_HANDLE_NULL: daos_handle_t = daos_handle_t { cookie: 0 };
#[inline]
pub fn is_valid_handle(handle: daos_handle_t) -> bool {
handle.cookie != 0
}
#[inline]
pub fn validate_handle(handle: daos_handle_t) -> Result<()> {
if is_valid_handle(handle) {
Ok(())
} else {
Err(DaosError::InvalidArg)
}
}
#[inline]
pub fn try_from_handle(handle: daos_handle_t) -> Result<DaosHandle> {
validate_handle(handle)?;
Ok(unsafe { DaosHandle::from_raw(handle) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_null_handle_is_invalid() {
let null_handle = DAOS_HANDLE_NULL;
assert!(!is_valid_handle(null_handle));
}
#[test]
fn test_valid_handle_is_valid() {
let valid_handle = daos_handle_t { cookie: 12345 };
assert!(is_valid_handle(valid_handle));
}
#[test]
fn test_validate_null_handle_returns_error() {
let result = validate_handle(DAOS_HANDLE_NULL);
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), DaosError::InvalidArg));
}
#[test]
fn test_validate_valid_handle_ok() {
let valid_handle = daos_handle_t { cookie: 12345 };
let result = validate_handle(valid_handle);
assert!(result.is_ok());
}
#[test]
fn test_try_from_handle_success() {
let handle = daos_handle_t { cookie: 999 };
let result = try_from_handle(handle);
assert!(result.is_ok());
let wrapper = result.unwrap();
assert_eq!(wrapper.cookie(), 999);
}
#[test]
fn test_try_from_handle_failure() {
let result = try_from_handle(DAOS_HANDLE_NULL);
assert!(result.is_err());
}
}