use std::error::Error as ErrorTrait;
use std::fmt::{Display, Error as FmtError, Formatter};
use super::cw_return_values;
#[derive(Debug)]
pub struct LibCwError {}
impl Display for LibCwError
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError>
{
write!(f, "LibCwError")
}
}
impl ErrorTrait for LibCwError
{
}
pub type LibCwResult = Result<(), LibCwError>;
impl Into<LibCwResult> for cw_return_values
{
fn into(self) -> Result<(), LibCwError>
{
if 0 == self.0 {
Err(LibCwError {})
} else {
Ok(())
}
}
}
#[cfg(test)]
mod tests
{
use std::ffi::CString;
use std::thread::{JoinHandle, spawn};
use super::*;
use super::super::unixcw_libcw_demo_1;
#[test]
fn test_lib_cw_error()
{
let lib_cw_error = LibCwError {};
println!("lib_cw_error = {}.", lib_cw_error);
println!("lib_cw_error = {:?}.", lib_cw_error);
}
#[test]
fn test_lib_cw_result()
{
let lib_cw_result_ok: LibCwResult = cw_return_values(1).into();
let lib_cw_result_err: LibCwResult = cw_return_values(0).into();
assert!(lib_cw_result_ok.is_ok());
assert!(lib_cw_result_err.is_err());
}
#[test]
fn test_lib_cw_demo_1_parallel()
{
let thread_num = 2;
let mut threads = Vec::<JoinHandle<LibCwResult>>::new();
for i in 0..thread_num {
let thread_id = i;
threads.push(
spawn(move || {
println!("thread {thread_id} started.");
let msg_cstr = CString::new(format!("thread {thread_id}")
.into_bytes())
.unwrap();
let ret = unsafe {
unixcw_libcw_demo_1(msg_cstr.as_ptr()).into()
};
println!("thread {thread_id} finished.");
ret
})
);
}
let mut threads_into_iter = threads.into_iter();
while let Some(join_handle) = threads_into_iter.next() {
join_handle.join()
.expect("test thread MUST terminate successfully")
.expect("libcw demo 1 MUST succeed");
}
}
}