Skip to main content

ntex_io/
types.rs

1//! Values exposed through transport and filter queries.
2use std::{any, fmt, marker::PhantomData, net::SocketAddr};
3
4#[derive(Copy, Clone, PartialEq, Eq)]
5/// Peer socket address returned by [`IoRef::query`](crate::IoRef::query).
6pub struct PeerAddr(pub SocketAddr);
7
8impl PeerAddr {
9    /// Returns the contained socket address.
10    pub fn into_inner(self) -> SocketAddr {
11        self.0
12    }
13}
14
15impl From<SocketAddr> for PeerAddr {
16    fn from(addr: SocketAddr) -> Self {
17        Self(addr)
18    }
19}
20
21impl fmt::Debug for PeerAddr {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        self.0.fmt(f)
24    }
25}
26
27#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
28/// HTTP protocol selected for an I/O stream.
29pub enum HttpProtocol {
30    /// HTTP/1.x.
31    Http1,
32    /// HTTP/2.
33    Http2,
34    /// The protocol has not been identified or is not HTTP.
35    Unknown,
36}
37
38/// Typed result of an [`IoRef::query`](crate::IoRef::query).
39///
40/// Query providers store values as `dyn Any`; this wrapper performs the
41/// requested downcast without exposing the erased representation.
42pub struct QueryItem<T> {
43    item: Option<Box<dyn any::Any>>,
44    _t: PhantomData<T>,
45}
46
47impl<T: any::Any> QueryItem<T> {
48    pub(crate) fn new(item: Option<Box<dyn any::Any>>) -> Self {
49        Self {
50            item,
51            _t: PhantomData,
52        }
53    }
54
55    /// Copies the queried value out of this item.
56    ///
57    /// Returns `None` if no provider returned a value of type `T`.
58    pub fn get(&self) -> Option<T>
59    where
60        T: Copy,
61    {
62        self.item.as_ref().and_then(|v| v.downcast_ref().copied())
63    }
64
65    /// Moves the queried value out of this item.
66    ///
67    /// Returns `None` if no provider returned a value of type `T`.
68    pub fn into_inner(self) -> Option<T> {
69        self.item.and_then(|v| v.downcast().ok()).map(|v| *v)
70    }
71
72    /// Borrows the queried value.
73    ///
74    /// Returns `None` if no provider returned a value of type `T`.
75    pub fn as_ref(&self) -> Option<&T> {
76        if let Some(ref item) = self.item {
77            item.downcast_ref()
78        } else {
79            None
80        }
81    }
82}
83
84impl<T: any::Any + fmt::Debug> fmt::Debug for QueryItem<T> {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        if let Some(v) = self.as_ref() {
87            f.debug_tuple("QueryItem").field(v).finish()
88        } else {
89            f.debug_tuple("QueryItem").field(&None::<T>).finish()
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    /// STATEMENT: `PeerAddr` preserves and formats its socket address.
99    ///
100    /// HOW:
101    /// - Convert a loopback address, compare the wrapper and debug output, then extract the address.
102    #[test]
103    fn peer_addr() {
104        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
105        let peer = PeerAddr::from(addr);
106        assert_eq!(peer, PeerAddr(addr));
107        assert_eq!(format!("{peer:?}"), "127.0.0.1:8080");
108        assert_eq!(peer.into_inner(), addr);
109    }
110
111    /// STATEMENT: `QueryItem` exposes only values matching its requested type.
112    ///
113    /// HOW:
114    /// - Construct matching, mismatched, and absent values and check owned and borrowed access.
115    /// - Verify debug formatting for the matching and absent cases.
116    #[test]
117    fn query_item() {
118        let item = QueryItem::<u32>::new(Some(Box::new(10u32)));
119        assert_eq!(item.get(), Some(10));
120        assert_eq!(item.as_ref(), Some(&10));
121        assert_eq!(format!("{item:?}"), "QueryItem(10)");
122
123        // a value of another type is not returned
124        let item = QueryItem::<u32>::new(Some(Box::new("str")));
125        assert_eq!(item.get(), None);
126        assert_eq!(item.as_ref(), None);
127
128        let item = QueryItem::<u32>::new(None);
129        assert_eq!(item.get(), None);
130        assert_eq!(item.as_ref(), None);
131        assert_eq!(format!("{item:?}"), "QueryItem(None)");
132    }
133}