c-ares 13.0.0

A Rust wrapper for the c-ares library, for asynchronous DNS requests.
Documentation
use core::ffi::c_int;
use std::fmt;
use std::ptr;

use itertools::Itertools;

use crate::error::{Error, Result};
use crate::host::{HostAliasResultsIter, HostResults};
use crate::record::QueryRecord;
use crate::types::QueryType;

/// The result of a successful PTR lookup.
#[derive(Debug)]
pub struct PTRResults {
    hostent: HostResults,
}

impl PTRResults {
    /// Obtain a `PTRResults` from the response to a PTR lookup.
    pub fn parse_from(data: &[u8]) -> Result<PTRResults> {
        let mut hostent: *mut c_types::hostent = ptr::null_mut();
        let dummy_ip = [0, 0, 0, 0];
        let parse_status = unsafe {
            #[allow(clippy::useless_conversion)]
            c_ares_sys::ares_parse_ptr_reply(
                data.as_ptr(),
                data.len() as c_int,
                dummy_ip.as_ptr().cast(),
                dummy_ip.len() as c_int,
                c_types::AF_INET.into(),
                &raw mut hostent,
            )
        };
        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
            let result = PTRResults::new(hostent);
            Ok(result)
        } else {
            Err(Error::from(parse_status))
        }
    }

    fn new(hostent: *mut c_types::hostent) -> Self {
        PTRResults {
            hostent: HostResults::new(hostent),
        }
    }

    /// Returns the hostname from this `PTRResults`.
    pub fn hostname(&self) -> &str {
        self.hostent.hostname()
    }

    /// Returns an iterator over the host aliases in this `PTRResults`.
    pub fn aliases(&self) -> HostAliasResultsIter<'_> {
        self.hostent.aliases()
    }
}

impl fmt::Display for PTRResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Hostname: {}, ", self.hostname())?;
        let aliases = self.aliases().format(", ");
        write!(fmt, "Aliases: [{aliases}]")
    }
}

impl QueryRecord for PTRResults {
    const QUERY_TYPE: QueryType = QueryType::PTR;
    fn parse(data: &[u8]) -> Result<Self> {
        Self::parse_from(data)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_invalid_data() {
        let result = PTRResults::parse_from(&[]);
        assert!(result.is_err());
    }

    #[test]
    fn is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<PTRResults>();
    }

    #[test]
    fn is_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<PTRResults>();
    }
}