c_ares/
txt.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::os::raw::{c_int, c_uchar, c_void};
4use std::ptr;
5use std::slice;
6use std::str;
7
8use itertools::Itertools;
9
10use crate::error::{Error, Result};
11use crate::panic;
12
13/// The result of a successful TXT lookup.
14#[derive(Debug)]
15pub struct TXTResults {
16    txt_reply: *mut c_ares_sys::ares_txt_ext,
17    phantom: PhantomData<c_ares_sys::ares_txt_ext>,
18}
19
20/// The contents of a single TXT record.
21#[derive(Clone, Copy)]
22pub struct TXTResult<'a> {
23    txt_reply: &'a c_ares_sys::ares_txt_ext,
24}
25
26impl TXTResults {
27    /// Obtain a `TXTResults` from the response to a TXT lookup.
28    pub fn parse_from(data: &[u8]) -> Result<TXTResults> {
29        let mut txt_reply: *mut c_ares_sys::ares_txt_ext = ptr::null_mut();
30        let parse_status = unsafe {
31            c_ares_sys::ares_parse_txt_reply_ext(data.as_ptr(), data.len() as c_int, &mut txt_reply)
32        };
33        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
34            let result = TXTResults::new(txt_reply);
35            Ok(result)
36        } else {
37            Err(Error::from(parse_status))
38        }
39    }
40
41    fn new(txt_reply: *mut c_ares_sys::ares_txt_ext) -> Self {
42        TXTResults {
43            txt_reply,
44            phantom: PhantomData,
45        }
46    }
47
48    /// Returns an iterator over the `TXTResult` values in this `TXTResults`.
49    pub fn iter(&self) -> TXTResultsIter {
50        TXTResultsIter {
51            next: unsafe { self.txt_reply.as_ref() },
52        }
53    }
54}
55
56impl fmt::Display for TXTResults {
57    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
58        let results = self.iter().format("}, {");
59        write!(fmt, "[{{{results}}}]")
60    }
61}
62
63/// Iterator of `TXTResult`s.
64#[derive(Clone, Copy)]
65pub struct TXTResultsIter<'a> {
66    next: Option<&'a c_ares_sys::ares_txt_ext>,
67}
68
69impl<'a> Iterator for TXTResultsIter<'a> {
70    type Item = TXTResult<'a>;
71    fn next(&mut self) -> Option<Self::Item> {
72        let opt_reply = self.next;
73        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
74        opt_reply.map(|reply| TXTResult { txt_reply: reply })
75    }
76}
77
78impl<'a> IntoIterator for &'a TXTResults {
79    type Item = TXTResult<'a>;
80    type IntoIter = TXTResultsIter<'a>;
81
82    fn into_iter(self) -> Self::IntoIter {
83        self.iter()
84    }
85}
86
87impl Drop for TXTResults {
88    fn drop(&mut self) {
89        unsafe { c_ares_sys::ares_free_data(self.txt_reply.cast()) }
90    }
91}
92
93unsafe impl Send for TXTResult<'_> {}
94unsafe impl Sync for TXTResult<'_> {}
95unsafe impl Send for TXTResults {}
96unsafe impl Sync for TXTResults {}
97unsafe impl Send for TXTResultsIter<'_> {}
98unsafe impl Sync for TXTResultsIter<'_> {}
99
100impl<'a> TXTResult<'a> {
101    /// Is this the start of a text record, or the continuation of a previous record?
102    pub fn record_start(self) -> bool {
103        self.txt_reply.record_start != 0
104    }
105
106    /// Returns the text in this `TXTResult`.
107    ///
108    /// Although text is usual here, any binary data is legal - which is why we return `&[u8]`.
109    pub fn text(self) -> &'a [u8] {
110        unsafe { slice::from_raw_parts(self.txt_reply.txt, self.txt_reply.length) }
111    }
112}
113
114impl fmt::Display for TXTResult<'_> {
115    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
116        let text = str::from_utf8(self.text()).unwrap_or("<binary>");
117        write!(fmt, "Record start: {}, Text: {}", self.record_start(), text)
118    }
119}
120
121pub(crate) unsafe extern "C" fn query_txt_callback<F>(
122    arg: *mut c_void,
123    status: c_int,
124    _timeouts: c_int,
125    abuf: *mut c_uchar,
126    alen: c_int,
127) where
128    F: FnOnce(Result<TXTResults>) + Send + 'static,
129{
130    ares_callback!(arg.cast::<F>(), status, abuf, alen, TXTResults::parse_from);
131}