mini_c_ares/
uri.rs

1use std::ffi::CStr;
2use std::fmt;
3use std::marker::PhantomData;
4use std::os::raw::{c_char, c_int, c_uchar, c_void};
5use std::ptr;
6use std::slice;
7
8use itertools::Itertools;
9
10use crate::error::{Error, Result};
11use crate::panic;
12
13/// The result of a successful URI lookup.
14#[derive(Debug)]
15pub struct URIResults {
16    uri_reply: *mut c_ares_sys::ares_uri_reply,
17    phantom: PhantomData<c_ares_sys::ares_uri_reply>,
18}
19
20/// The contents of a single URI record.
21#[derive(Clone, Copy)]
22pub struct URIResult<'a> {
23    // A single result - reference into a `URIResults`.
24    uri_reply: &'a c_ares_sys::ares_uri_reply,
25}
26
27impl URIResults {
28    /// Obtain a `URIResults` from the response to a URI lookup.
29    pub fn parse_from(data: &[u8]) -> Result<URIResults> {
30        let mut uri_reply: *mut c_ares_sys::ares_uri_reply = ptr::null_mut();
31        let parse_status = unsafe {
32            c_ares_sys::ares_parse_uri_reply(data.as_ptr(), data.len() as c_int, &mut uri_reply)
33        };
34        if parse_status == c_ares_sys::ARES_SUCCESS {
35            let uri_result = URIResults::new(uri_reply);
36            Ok(uri_result)
37        } else {
38            Err(Error::from(parse_status))
39        }
40    }
41
42    fn new(uri_reply: *mut c_ares_sys::ares_uri_reply) -> Self {
43        URIResults {
44            uri_reply,
45            phantom: PhantomData,
46        }
47    }
48
49    /// Returns an iterator over the `URIResult` values in this `URIResults`.
50    pub fn iter(&self) -> URIResultsIter {
51        URIResultsIter {
52            next: unsafe { self.uri_reply.as_ref() },
53        }
54    }
55}
56
57impl fmt::Display for URIResults {
58    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
59        let results = self.iter().format("}, {");
60        write!(fmt, "[{{{results}}}]")
61    }
62}
63
64/// Iterator of `URIResult`s.
65#[derive(Clone, Copy)]
66pub struct URIResultsIter<'a> {
67    next: Option<&'a c_ares_sys::ares_uri_reply>,
68}
69
70impl<'a> Iterator for URIResultsIter<'a> {
71    type Item = URIResult<'a>;
72    fn next(&mut self) -> Option<Self::Item> {
73        let opt_reply = self.next;
74        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
75        opt_reply.map(|reply| URIResult { uri_reply: reply })
76    }
77}
78
79impl<'a> IntoIterator for &'a URIResults {
80    type Item = URIResult<'a>;
81    type IntoIter = URIResultsIter<'a>;
82
83    fn into_iter(self) -> Self::IntoIter {
84        self.iter()
85    }
86}
87
88impl Drop for URIResults {
89    fn drop(&mut self) {
90        unsafe { c_ares_sys::ares_free_data(self.uri_reply as *mut c_void) }
91    }
92}
93
94unsafe impl Send for URIResults {}
95unsafe impl Sync for URIResults {}
96unsafe impl<'a> Send for URIResult<'a> {}
97unsafe impl<'a> Sync for URIResult<'a> {}
98unsafe impl<'a> Send for URIResultsIter<'a> {}
99unsafe impl<'a> Sync for URIResultsIter<'a> {}
100
101impl<'a> URIResult<'a> {
102    /// Returns the weight in this `URIResult`.
103    pub fn weight(self) -> u16 {
104        self.uri_reply.weight
105    }
106
107    /// Returns the priority in this `URIResult`.
108    pub fn priority(self) -> u16 {
109        self.uri_reply.priority
110    }
111
112    /// Returns the uri in this `URIResult`.
113    ///
114    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
115    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
116    /// fallible conversion, a lossy conversion, or something else altogether.
117    pub fn uri(self) -> &'a CStr {
118        unsafe { CStr::from_ptr(self.uri_reply.uri as *const c_char) }
119    }
120
121    /// Returns the time-to-live in this `URIResult`.
122    pub fn ttl(self) -> i32 {
123        #[allow(clippy::unnecessary_cast)]
124        let ttl = self.uri_reply.ttl as i32;
125        ttl
126    }
127}
128
129impl<'a> fmt::Display for URIResult<'a> {
130    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
131        write!(
132            fmt,
133            "URI: {}, ",
134            self.uri().to_str().unwrap_or("<not utf8>")
135        )?;
136        write!(fmt, "Priority: {}, ", self.priority())?;
137        write!(fmt, "Weight: {}, ", self.weight())?;
138        write!(fmt, "TTL: {}", self.ttl())
139    }
140}
141
142pub(crate) unsafe extern "C" fn query_uri_callback<F>(
143    arg: *mut c_void,
144    status: c_int,
145    _timeouts: c_int,
146    abuf: *mut c_uchar,
147    alen: c_int,
148) where
149    F: FnOnce(Result<URIResults>) + Send + 'static,
150{
151    ares_callback!(arg as *mut F, status, abuf, alen, URIResults::parse_from);
152}