futures_codec2/
framed_write.rs1use crate::{Encoder, FramedImpl, WriteFrame};
2
3use futures_core::stream::Stream;
4use futures_io::AsyncWrite;
5use futures_sink::Sink;
6use pin_project_lite::pin_project;
7use std::fmt;
8use std::io;
9use std::pin::Pin;
10use std::task::{Context, Poll};
11
12pin_project! {
13 pub struct FramedWrite<T, E> {
17 #[pin]
18 inner: FramedImpl<T, E, WriteFrame>,
19 }
20}
21
22impl<T, E> FramedWrite<T, E>
23where
24 T: AsyncWrite,
25{
26 pub fn new(inner: T, encoder: E) -> FramedWrite<T, E> {
28 FramedWrite {
29 inner: FramedImpl {
30 inner,
31 codec: encoder,
32 state: WriteFrame::default(),
33 },
34 }
35 }
36}
37
38impl<T, E> FramedWrite<T, E> {
39 pub fn get_ref(&self) -> &T {
46 &self.inner.inner
47 }
48
49 pub fn get_mut(&mut self) -> &mut T {
56 &mut self.inner.inner
57 }
58
59 pub fn into_inner(self) -> T {
65 self.inner.inner
66 }
67
68 pub fn encoder(&self) -> &E {
70 &self.inner.codec
71 }
72
73 pub fn encoder_mut(&mut self) -> &mut E {
75 &mut self.inner.codec
76 }
77}
78
79impl<T, I, E> Sink<I> for FramedWrite<T, E>
81where
82 T: AsyncWrite,
83 E: Encoder<I>,
84 E::Error: From<io::Error>,
85{
86 type Error = E::Error;
87
88 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
89 self.project().inner.poll_ready(cx)
90 }
91
92 fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
93 self.project().inner.start_send(item)
94 }
95
96 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
97 self.project().inner.poll_flush(cx)
98 }
99
100 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
101 self.project().inner.poll_close(cx)
102 }
103}
104
105impl<T, D> Stream for FramedWrite<T, D>
107where
108 T: Stream,
109{
110 type Item = T::Item;
111
112 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
113 self.project().inner.project().inner.poll_next(cx)
114 }
115}
116
117impl<T, U> fmt::Debug for FramedWrite<T, U>
118where
119 T: fmt::Debug,
120 U: fmt::Debug,
121{
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.debug_struct("FramedWrite")
124 .field("inner", &self.get_ref())
125 .field("encoder", &self.encoder())
126 .field("buffer", &self.inner.state.buffer)
127 .finish()
128 }
129}