use libc::{c_int, c_void, setsockopt, socklen_t, timespec};
use std::{io, ptr};
use std::mem::size_of;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[inline]
pub fn set_socket_option<T>(fd: c_int, level: c_int, name: c_int, val: &T) -> io::Result<()> {
let rv = unsafe {
let val_ptr: *const T = val as *const T;
setsockopt(fd,
level,
name,
val_ptr as *const c_void,
size_of::<T>() as socklen_t)
};
if rv != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn set_socket_option_mult<T>(fd: c_int,
level: c_int,
name: c_int,
values: &[T])
-> io::Result<()> {
let rv = if values.is_empty() {
unsafe { setsockopt(fd, level, name, ptr::null(), 0) }
} else {
unsafe {
let val_ptr = &values[0] as *const T;
setsockopt(fd,
level,
name,
val_ptr as *const c_void,
(size_of::<T>() * values.len()) as socklen_t)
}
};
if rv != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[inline]
pub fn duration_from_timeval(ts: timespec) -> Duration {
Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
}
#[inline]
pub fn system_time_from_timespec(ts: timespec) -> SystemTime {
UNIX_EPOCH + duration_from_timeval(ts)
}