Skip to main content

ntex_io/
seal.rs

1use std::{any::Any, any::TypeId, fmt, io, ops, task::Context, task::Poll};
2
3use crate::{Filter, FilterCtx, Io};
4
5/// Type-erased filter chain used by [`IoBoxed`].
6pub struct Sealed(pub(crate) Box<dyn Filter>);
7
8impl fmt::Debug for Sealed {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        f.debug_struct("Sealed").finish()
11    }
12}
13
14impl Filter for Sealed {
15    #[inline]
16    fn query(&self, id: TypeId) -> Option<Box<dyn Any>> {
17        self.0.query(id)
18    }
19
20    #[inline]
21    fn process_read_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
22        self.0.process_read_buf(ctx)
23    }
24
25    #[inline]
26    fn process_write_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
27        self.0.process_write_buf(ctx)
28    }
29
30    #[inline]
31    fn shutdown(&self, ctx: &mut FilterCtx<'_>) -> io::Result<Poll<()>> {
32        self.0.shutdown(ctx)
33    }
34
35    #[inline]
36    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
37        self.0.poll_ready(cx)
38    }
39}
40
41#[derive(Debug)]
42/// An [`Io`] object whose filter-chain type has been erased.
43pub struct IoBoxed(pub(crate) Io<Sealed>);
44
45impl IoBoxed {
46    #[inline]
47    #[must_use]
48    /// Transfers the live I/O state into a new object.
49    ///
50    /// This does not clone the connection. The current object is replaced with
51    /// a stopped placeholder and should no longer be used for I/O.
52    pub fn take(&mut self) -> Self {
53        // SAFETY: `&mut self` rules out borrows of the inner `Io`
54        IoBoxed(unsafe { self.0.take() })
55    }
56}
57
58impl<F: Filter> From<Io<F>> for IoBoxed {
59    fn from(io: Io<F>) -> Self {
60        io.boxed()
61    }
62}
63
64impl ops::Deref for IoBoxed {
65    type Target = Io<Sealed>;
66
67    #[inline]
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}
72
73impl From<IoBoxed> for Io<Sealed> {
74    fn from(value: IoBoxed) -> Self {
75        value.0
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use std::any::TypeId;
82
83    use ntex_bytes::Bytes;
84    use ntex_codec::BytesCodec;
85
86    use super::*;
87    use crate::{FilterBuf, FilterLayer, filter::NullFilter, testing::IoTest};
88
89    #[derive(Debug)]
90    struct Tagged;
91
92    impl FilterLayer for Tagged {
93        fn query(&self, id: TypeId) -> Option<Box<dyn Any>> {
94            (id == TypeId::of::<&'static str>()).then(|| Box::new("tagged") as Box<dyn Any>)
95        }
96
97        fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
98            buf.with_read_buffers(|src, dst| {
99                if let Some(src) = src.take() {
100                    dst.extend_from_slice(&src);
101                }
102            });
103            Ok(())
104        }
105
106        fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
107            buf.with_write_buffers(ntex_bytes::BytePages::move_to);
108            Ok(())
109        }
110    }
111
112    /// Filter chain wrapper built from the forwarding macros.
113    struct Wrapper<F> {
114        inner: F,
115    }
116
117    impl<F: Filter> Filter for Wrapper<F> {
118        crate::forward_ready!(inner);
119        crate::forward_query!(inner);
120        crate::forward_shutdown!(inner);
121
122        fn process_read_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
123            self.inner.process_read_buf(ctx)
124        }
125
126        fn process_write_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
127            self.inner.process_write_buf(ctx)
128        }
129    }
130
131    /// STATEMENT: Sealed and macro-forwarding filter wrappers preserve queries, data flow, and shutdown.
132    ///
133    /// HOW:
134    /// - Box a tagged filter chain, seal it, and wrap it with forwarding macros.
135    /// - Check matching and absent queries, exchange bytes in both directions, and verify shutdown.
136    #[ntex::test]
137    async fn sealed_chain_delegates_to_inner_filter() {
138        assert_eq!(format!("{:?}", Sealed(Box::new(NullFilter))), "Sealed");
139
140        let (client, server) = IoTest::create();
141        client.remote_buffer_cap(1024);
142
143        let io = Io::from(server).add_filter(Tagged).boxed();
144        let io: Io<Sealed> = io.into();
145        let io = io.map_filter(|inner| Wrapper { inner });
146        assert_eq!(io.query::<&'static str>().get(), Some("tagged"));
147        assert!(io.query::<u32>().get().is_none());
148
149        client.write("hello");
150        let item = io.recv(&BytesCodec).await.unwrap().unwrap();
151        assert_eq!(item, Bytes::from_static(b"hello"));
152
153        io.send(Bytes::from_static(b"world"), &BytesCodec)
154            .await
155            .unwrap();
156        assert_eq!(client.read().await.unwrap(), Bytes::from_static(b"world"));
157
158        io.shutdown().await.unwrap();
159        assert!(io.is_closed());
160    }
161}