use std::sync::Arc;
use super::{avahi_util, poll::ManagedAvahiSimplePoll};
use crate::ffi::c_str;
use crate::Result;
use avahi_sys::{
avahi_client_free, avahi_client_get_host_name, avahi_client_new, avahi_simple_poll_get,
AvahiClient, AvahiClientCallback, AvahiClientFlags,
};
use libc::{c_int, c_void};
#[derive(Debug)]
pub struct ManagedAvahiClient {
pub(crate) inner: *mut AvahiClient,
_poll: Arc<ManagedAvahiSimplePoll>,
}
impl ManagedAvahiClient {
pub fn new(
ManagedAvahiClientParams {
poll,
flags,
callback,
userdata,
}: ManagedAvahiClientParams,
) -> Result<Self> {
let mut err: c_int = 0;
let inner = unsafe {
avahi_client_new(
avahi_simple_poll_get(poll.inner()),
flags,
callback,
userdata,
&mut err,
)
};
if inner.is_null() {
return Err("could not initialize AvahiClient".into());
}
match err {
0 => Ok(Self { inner, _poll: poll }),
_ => Err(format!(
"could not initialize AvahiClient: {}",
avahi_util::get_error(err)
)
.into()),
}
}
pub fn host_name<'a>(&self) -> Result<&'a str> {
unsafe { get_host_name(self.inner) }
}
}
impl Drop for ManagedAvahiClient {
fn drop(&mut self) {
unsafe { avahi_client_free(self.inner) };
}
}
unsafe impl Send for ManagedAvahiClient {}
unsafe impl Sync for ManagedAvahiClient {}
#[derive(Builder, BuilderDelegate)]
pub struct ManagedAvahiClientParams {
poll: Arc<ManagedAvahiSimplePoll>,
flags: AvahiClientFlags,
callback: AvahiClientCallback,
userdata: *mut c_void,
}
pub(super) unsafe fn get_host_name<'a>(client: *mut AvahiClient) -> Result<&'a str> {
assert_not_null!(client);
let host_name = avahi_client_get_host_name(client);
if !host_name.is_null() {
Ok(c_str::raw_to_str(host_name))
} else {
Err("could not get host name from AvahiClient".into())
}
}