Skip to main content

http_type/stream/
impl.rs

1use super::*;
2
3/// Implementation of `From` trait for converting `usize` address into `&Stream`.
4impl From<usize> for &'static Stream {
5    /// Converts a memory address into a reference to `Stream`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - The memory address of the `Stream` instance.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static Stream` - A reference to the `Stream` at the given address.
14    ///
15    /// # Safety
16    ///
17    /// - The address is guaranteed to be a valid `Stream` instance
18    ///   that was previously converted from a reference and is managed by the runtime.
19    #[inline(always)]
20    fn from(address: usize) -> &'static Stream {
21        unsafe { &*(address as *const Stream) }
22    }
23}
24
25/// Implementation of `From` trait for converting `usize` address into `&mut Stream`.
26impl<'a> From<usize> for &'a mut Stream {
27    /// Converts a memory address into a mutable reference to `Stream`.
28    ///
29    /// # Arguments
30    ///
31    /// - `usize` - The memory address of the `Stream` instance.
32    ///
33    /// # Returns
34    ///
35    /// - `&'a mut Stream` - A mutable reference to the `Stream` at the given address.
36    ///
37    /// # Safety
38    ///
39    /// - The address is guaranteed to be a valid `Stream` instance
40    ///   that was previously converted from a reference and is managed by the runtime.
41    #[inline(always)]
42    fn from(address: usize) -> &'a mut Stream {
43        unsafe { &mut *(address as *mut Stream) }
44    }
45}
46
47/// Implementation of `From` trait for converting `&Stream` into `usize` address.
48impl From<&Stream> for usize {
49    /// Converts a reference to `Stream` into its memory address.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Stream` - The reference to the `Stream` instance.
54    ///
55    /// # Returns
56    ///
57    /// - `usize` - The memory address of the `Stream` instance.
58    #[inline(always)]
59    fn from(stream: &Stream) -> Self {
60        stream as *const Stream as usize
61    }
62}
63
64/// Implementation of `From` trait for converting `&mut Stream` into `usize` address.
65impl From<&mut Stream> for usize {
66    /// Converts a mutable reference to `Stream` into its memory address.
67    ///
68    /// # Arguments
69    ///
70    /// - `&mut Stream` - The mutable reference to the `Stream` instance.
71    ///
72    /// # Returns
73    ///
74    /// - `usize` - The memory address of the `Stream` instance.
75    #[inline(always)]
76    fn from(stream: &mut Stream) -> Self {
77        stream as *mut Stream as usize
78    }
79}
80
81/// Implementation of `AsRef` trait for `Stream`.
82impl AsRef<Stream> for Stream {
83    /// Converts `&Stream` to `&Stream` via memory address conversion.
84    ///
85    /// # Returns
86    ///
87    /// - `&Self` - A reference to the `Stream` instance.
88    #[inline(always)]
89    fn as_ref(&self) -> &Self {
90        let address: usize = self.into();
91        address.into()
92    }
93}
94
95/// Implementation of `AsMut` trait for `Stream`.
96impl AsMut<Stream> for Stream {
97    /// Converts `&mut Stream` to `&mut Stream` via memory address conversion.
98    ///
99    /// # Returns
100    ///
101    /// - `&mut Self` - A mutable reference to the `Stream` instance.
102    #[inline(always)]
103    fn as_mut(&mut self) -> &mut Self {
104        let address: usize = self.into();
105        address.into()
106    }
107}
108
109/// Implementation of `Lifetime` trait for `Stream`.
110impl Lifetime for Stream {
111    /// Converts a reference to the stream into a `'static` reference.
112    ///
113    /// # Returns
114    ///
115    /// - `&'static Self` - A reference to the stream with a `'static` lifetime.
116    ///
117    /// # Safety
118    ///
119    /// - The address is guaranteed to be a valid `Self` instance
120    ///   that was previously converted from a reference and is managed by the runtime.
121    #[inline(always)]
122    unsafe fn leak(&self) -> &'static Self {
123        let address: usize = self.into();
124        address.into()
125    }
126
127    /// Converts a reference to the stream into a `'static` mutable reference.
128    ///
129    /// # Returns
130    ///
131    /// - `&'static mut Self` - A mutable reference to the stream with a `'static` lifetime.
132    ///
133    /// # Safety
134    ///
135    /// - The address is guaranteed to be a valid `Self` instance
136    ///   that was previously converted from a reference and is managed by the runtime.
137    #[inline(always)]
138    unsafe fn leak_mut(&self) -> &'static mut Self {
139        let address: usize = self.into();
140        address.into()
141    }
142}
143
144/// Implementation of `Transport` trait for the plain TCP socket.
145///
146/// The socket is the reference transport: it already carries a socket
147/// identity, so its addresses are reported directly.
148impl Transport for TcpStream {
149    /// Reports the address of the remote end of the socket.
150    ///
151    /// # Returns
152    ///
153    /// - `Result<SocketAddr, io::Error>` - The peer address of the socket.
154    fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
155        TcpStream::peer_addr(self)
156    }
157
158    /// Reports the address of the local end of the socket.
159    ///
160    /// # Returns
161    ///
162    /// - `Result<SocketAddr, io::Error>` - The local address of the socket.
163    fn local_addr(&self) -> Result<SocketAddr, io::Error> {
164        TcpStream::local_addr(self)
165    }
166}
167
168/// Implements [`Drop`] for [`PooledReader`].
169impl Drop for PooledReader<'_> {
170    /// Releases the buffer back to the pool for reuse by later requests.
171    fn drop(&mut self) {
172        let buffer: Vec<u8> = mem::take(self.get_mut_buffer());
173        return_read_buffer(buffer);
174    }
175}
176
177/// Implements non-blocking buffered reads for `PooledReader`.
178///
179/// Buffered bytes are served first; once drained, reads are delegated
180/// directly to the underlying stream.
181impl AsyncRead for PooledReader<'_> {
182    /// Polls to read data into the provided buffer.
183    ///
184    /// # Arguments
185    ///
186    /// - `Pin<&mut Self>` - The pinned reader.
187    /// - `&mut Context<'_>` - The task context.
188    /// - `&mut ReadBuf<'_>` - The destination buffer.
189    ///
190    /// # Returns
191    ///
192    /// - `Poll<io::Result<()>>` - Ready when data was read or an error occurred.
193    fn poll_read(
194        self: Pin<&mut Self>,
195        cx: &mut Context<'_>,
196        buf: &mut ReadBuf<'_>,
197    ) -> Poll<io::Result<()>> {
198        let this: &mut Self = self.get_mut();
199        if this.get_start() < this.get_end() {
200            let available: usize = this.get_end() - this.get_start();
201            let amount: usize = available.min(buf.remaining());
202            let end: usize = this.get_start() + amount;
203            buf.put_slice(&this.get_buffer()[this.get_start()..end]);
204            this.set_start(end);
205            return Poll::Ready(Ok(()));
206        }
207        return_read_buffer(mem::take(this.get_mut_buffer()));
208        Pin::new(&mut **this.get_mut_stream()).poll_read(cx, buf)
209    }
210}
211
212/// Implements buffered-read support for `PooledReader`.
213///
214/// The internal buffer is refilled from the stream only when fully
215/// consumed, so a single socket read serves multiple line parses.
216impl AsyncBufRead for PooledReader<'_> {
217    /// Polls to fill the internal buffer and returns the available data.
218    ///
219    /// # Arguments
220    ///
221    /// - `Pin<&mut Self>` - The pinned reader.
222    /// - `&mut Context<'_>` - The task context.
223    ///
224    /// # Returns
225    ///
226    /// - `Poll<io::Result<&[u8]>>` - Ready with the unconsumed bytes, or an error.
227    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
228        let this: &mut Self = self.get_mut();
229        let PooledReader {
230            stream,
231            buffer,
232            capacity,
233            start,
234            end,
235        } = this;
236        if *start >= *end {
237            *start = 0;
238            *end = 0;
239            if buffer.is_empty() {
240                *buffer = take_read_buffer(*capacity);
241            }
242            let mut read_buf: ReadBuf<'_> = ReadBuf::new(buffer);
243            match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
244                Poll::Ready(Ok(())) => {
245                    *end = read_buf.filled().len();
246                }
247                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
248                Poll::Pending => {
249                    return_read_buffer(mem::take(buffer));
250                    return Poll::Pending;
251                }
252            }
253        }
254        Poll::Ready(Ok(&buffer[*start..*end]))
255    }
256
257    /// Marks the given number of bytes as consumed.
258    ///
259    /// # Arguments
260    ///
261    /// - `Pin<&mut Self>` - The pinned reader.
262    /// - `usize` - The number of bytes to consume.
263    fn consume(self: Pin<&mut Self>, amount: usize) {
264        let this: &mut Self = self.get_mut();
265        let new_start: usize = (this.get_start() + amount).min(this.get_end());
266        this.set_start(new_start);
267    }
268}
269
270/// Inherent implementation of [`Stream`].
271impl Stream {
272    /// Boxes a transport into a `Stream` for the request pipeline.
273    ///
274    /// This is the single construction path: a plain TCP socket, a TLS session
275    /// and a per-request duplex stream all enter here, so nothing above the
276    /// transport line has to know which one it is serving. The transport is
277    /// type erased immediately, which keeps `Stream` a fixed size regardless of
278    /// the concrete protocol adapter behind it.
279    ///
280    /// # Arguments
281    ///
282    /// - `T` - The transport type to serve the request cycle over.
283    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
284    /// - `bool` - Whether the connection starts already closed.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - A stream serving bytes through the boxed transport.
289    pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
290    where
291        T: Transport + 'static,
292    {
293        Self {
294            stream: Box::new(transport),
295            request_config,
296            closed,
297            leftover: Vec::new(),
298            leftover_start: 0,
299            leftover_end: 0,
300            line_buffer: String::with_capacity(REQUEST_LINE_BUFFER_CAPACITY),
301            header_line_buffer: String::with_capacity(HEADER_LINE_BUFFER_CAPACITY),
302        }
303    }
304
305    /// Boxes a TCP socket into a `Stream` for the request pipeline.
306    ///
307    /// Kept as the socket-facing constructor so the accept loop keeps its
308    /// existing call shape; it delegates to `from_transport`, so there is one
309    /// construction path rather than two.
310    ///
311    /// # Arguments
312    ///
313    /// - `TcpStream` - The accepted socket to serve the request cycle over.
314    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
315    /// - `bool` - Whether the connection starts already closed.
316    ///
317    /// # Returns
318    ///
319    /// - `Self` - A stream serving bytes through the boxed socket.
320    pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
321        Self::from_transport(stream, request_config, closed)
322    }
323
324    /// Reports the address of the remote end of the transport.
325    ///
326    /// Delegates to the transport itself, so a transport without a socket
327    /// identity answers with an error rather than a fabricated address.
328    ///
329    /// # Returns
330    ///
331    /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
332    #[inline(always)]
333    pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
334        self.get_stream().peer_addr()
335    }
336
337    /// Reports the address of the local end of the transport.
338    ///
339    /// Delegates to the transport itself, so a transport without a socket
340    /// identity answers with an error rather than a fabricated address.
341    ///
342    /// # Returns
343    ///
344    /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
345    #[inline(always)]
346    pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
347        self.get_stream().local_addr()
348    }
349
350    /// Checks if the connection should be kept alive.
351    ///
352    /// This method evaluates whether the connection should remain open based on
353    /// the closed state and the keep_alive parameter.
354    ///
355    /// # Arguments
356    ///
357    /// - `bool` - Whether keep-alive is enabled for the request.
358    ///
359    /// # Returns
360    ///
361    /// - `bool` - True if the connection should be kept alive, otherwise false.
362    #[inline(always)]
363    pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
364        !self.get_closed() && keep_alive
365    }
366
367    /// Parses the HTTP request content from the stream into the given request.
368    ///
369    /// The request is reset first, then filled in place so its existing
370    /// allocations are reused across keep-alive requests.
371    ///
372    /// # Arguments
373    ///
374    /// - `&mut Request` - The request object to fill.
375    ///
376    /// # Returns
377    ///
378    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
379    async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
380        request.reset();
381        let config: RequestConfig = *self.get_request_config();
382        let buffer_size: usize = config.get_buffer_size();
383        let max_path_size: usize = config.get_max_path_size();
384        // Move read-ahead storage and its valid window into the reader instead
385        // of allocating and copying the remaining pipeline for every request.
386        let start: usize = self.get_leftover_start();
387        let end: usize = self.get_leftover_end();
388        let buffer: Vec<u8> = mem::take(self.get_mut_leftover());
389        self.set_leftover_start(0);
390        self.set_leftover_end(0);
391        // Split the borrow of the stream: the reader takes the transport, the
392        // line buffers are separate fields, so both can be held at once.
393        let Stream {
394            stream,
395            line_buffer,
396            header_line_buffer,
397            ..
398        } = self;
399        let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
400        reader.set_start(start);
401        reader.set_end(end);
402        line_buffer.clear();
403        AsyncBufReadExt::read_line(&mut reader, line_buffer).await?;
404        let (method, path, version): (RequestMethod, &str, RequestVersion) =
405            Request::get_http_first_line(line_buffer)?;
406        Request::check_http_path_size(path, max_path_size)?;
407        let hash_index: Option<usize> = path.find(HASH);
408        let query_index: Option<usize> = path.find(QUERY);
409        let query: &str = Request::get_http_query(path, query_index, hash_index);
410        Request::fill_http_querys(query, request.get_mut_querys());
411        let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
412        request.get_mut_path().push_str(path_slice);
413        let content_size: usize = request
414            .get_http_headers(&mut reader, &config, header_line_buffer)
415            .await?;
416        request.set_method(method);
417        request.set_version(version);
418        Request::fill_http_body(&mut reader, request.get_mut_body(), content_size).await?;
419        // Preserve bytes read ahead for the next pipelined request: they have
420        // already left the socket and cannot be read again.
421        let reader_start: usize = reader.get_start();
422        let reader_end: usize = reader.get_end();
423        let pending: Vec<u8> = if reader_start < reader_end {
424            mem::take(reader.get_mut_buffer())
425        } else {
426            Vec::new()
427        };
428        drop(reader);
429        let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
430        let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
431        self.set_leftover(pending);
432        self.set_leftover_start(pending_start);
433        self.set_leftover_end(pending_end);
434        Ok(())
435    }
436
437    /// Parses an HTTP request from a TCP stream into the given request.
438    ///
439    /// The request is reset and filled in place, reusing its allocations.
440    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
441    ///
442    /// # Arguments
443    ///
444    /// - `&mut Request` - The request object to reset and fill.
445    ///
446    /// # Returns
447    ///
448    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
449    pub async fn try_fill_http_request(
450        &mut self,
451        request: &mut Request,
452    ) -> Result<(), RequestError> {
453        if self.get_closed() {
454            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
455        }
456        let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
457        if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
458            return self.fill_http_from_stream(request).await;
459        }
460        let duration: Duration = Duration::from_millis(timeout_ms);
461        let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
462        // A request whose bytes have already arrived is read on the first
463        // poll, so the ordinary case never arms a timer at all. Arming one
464        // costs a timer registration and a cancellation per request, and that
465        // churn is the most expensive thing a request path can do once the
466        // concurrency is high enough for the timer driver to become a
467        // bottleneck. The timer is armed only when the read really has to
468        // wait, which is exactly when the timeout can still fire.
469        if let Some(result) = poll_once(reading.as_mut()).await {
470            return result;
471        }
472        timeout(duration, reading).await?
473    }
474
475    /// Parses an HTTP request from a TCP stream.
476    ///
477    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
478    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
479    ///
480    /// # Returns
481    ///
482    /// - `Result<Request, RequestError>` - The parsed request or an error.
483    pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
484        let mut request: Request = Request::default();
485        self.try_fill_http_request(&mut request).await?;
486        Ok(request)
487    }
488
489    /// Parses a WebSocket request from a TCP stream.
490    ///
491    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
492    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
493    ///
494    /// # Returns
495    ///
496    /// - `Result<RequestBody, RequestError>` - The parsed WebSocket request or an error.
497    pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
498        if self.get_closed() {
499            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
500        }
501        let config: RequestConfig = *self.get_request_config();
502        let buffer_size: usize = config.get_buffer_size();
503        let read_timeout_ms: u64 = config.get_read_timeout_ms();
504        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
505        let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
506        let mut full_frame: Vec<u8> = Vec::new();
507        let mut is_client_response: bool = false;
508        let duration_opt: Option<Duration> =
509            if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
510                None
511            } else {
512                let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
513                Some(Duration::from_millis(adjusted_timeout_ms))
514            };
515        loop {
516            let len: usize = match self
517                .get_websocket_from_stream(&mut temp_buffer, duration_opt, &mut is_client_response)
518                .await
519            {
520                Ok(Some(len)) => len,
521                Ok(None) => continue,
522                Err(error) => return Err(error),
523            };
524            if len == 0 {
525                return Err(RequestError::IncompleteWebSocketFrame(
526                    HttpStatus::BadRequest,
527                ));
528            }
529            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
530            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
531                is_client_response = true;
532                dynamic_buffer.drain(0..consumed);
533                match frame.get_opcode() {
534                    WebSocketOpcode::Close => {
535                        return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
536                    }
537                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
538                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
539                        match frame.build_full_frame(&mut full_frame) {
540                            Ok(Some(result)) => return Ok(result),
541                            Ok(None) => continue,
542                            Err(error) => return Err(error),
543                        }
544                    }
545                    _ => {
546                        return Err(RequestError::WebSocketOpcodeUnsupported(
547                            HttpStatus::NotImplemented,
548                        ));
549                    }
550                }
551            }
552        }
553    }
554
555    /// Reads data from the stream with optional timeout handling.
556    ///
557    /// # Arguments
558    ///
559    /// - `&mut [u8]` - The buffer to read data into.
560    /// - `Option<Duration>` - The optional timeout duration. If Some, timeout is applied; if None, no timeout.
561    /// - `&mut bool` - Mutable reference to track if we got a client response.
562    ///
563    /// # Returns
564    ///
565    /// - `Result<Option<usize>, RequestError>` - The number of bytes read, None for timeout/ping, or an error.
566    pub(crate) async fn get_websocket_from_stream(
567        &mut self,
568        buffer: &mut [u8],
569        duration_opt: Option<Duration>,
570        is_client_response: &mut bool,
571    ) -> Result<Option<usize>, RequestError> {
572        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
573        if let Some(duration) = duration_opt {
574            return match timeout(duration, stream.read(buffer)).await {
575                Ok(result) => match result {
576                    Ok(len) => Ok(Some(len)),
577                    Err(error) => Err(error.into()),
578                },
579                Err(error) => {
580                    if !*is_client_response {
581                        return Err(error.into());
582                    }
583                    *is_client_response = false;
584                    self.try_send(&PING_FRAME).await?;
585                    Ok(None)
586                }
587            };
588        }
589        match stream.read(buffer).await {
590            Ok(len) => Ok(Some(len)),
591            Err(error) => Err(error.into()),
592        }
593    }
594
595    /// Sends data over the stream.
596    ///
597    /// # Arguments
598    ///
599    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
600    ///
601    /// # Returns
602    ///
603    /// - `Result<(), ResponseError>` - Result indicating success or failure.
604    pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
605    where
606        D: AsRef<[u8]>,
607    {
608        if self.get_closed() {
609            return Err(ResponseError::ConnectionClosed);
610        }
611        Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
612    }
613
614    /// Sends data over the stream.
615    ///
616    /// # Arguments
617    ///
618    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
619    ///
620    /// # Panics
621    ///
622    /// Panics if the write operation fails.
623    pub async fn send<D>(&mut self, data: D)
624    where
625        D: AsRef<[u8]>,
626    {
627        self.try_send(data).await.unwrap();
628    }
629
630    /// Sends multiple data.
631    ///
632    /// # Arguments
633    ///
634    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
635    ///   `D` requiring the `AsRef<[u8]>` bound.
636    ///
637    /// # Returns
638    ///
639    /// - `Result<(), ResponseError>` - Result indicating success or failure.
640    pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
641    where
642        I: IntoIterator<Item = D>,
643        D: AsRef<[u8]>,
644    {
645        if self.get_closed() {
646            return Err(ResponseError::ConnectionClosed);
647        }
648        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
649        for data in data_iter {
650            stream.write_all(data.as_ref()).await?;
651        }
652        Ok(())
653    }
654
655    /// Sends multiple data.
656    ///
657    /// # Arguments
658    ///
659    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
660    ///   `D` requiring the `AsRef<[u8]>` bound.
661    ///
662    /// # Panics
663    ///
664    /// Panics if any write operation fails.
665    pub async fn send_list<I, D>(&mut self, data_iter: I)
666    where
667        I: IntoIterator<Item = D>,
668        D: AsRef<[u8]>,
669    {
670        self.try_send_list(data_iter).await.unwrap();
671    }
672
673    /// Flushes all buffered data to the stream.
674    ///
675    /// # Returns
676    ///
677    /// - `Result<(), ResponseError>` - Result indicating success or failure.
678    pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
679        if self.get_closed() {
680            return Err(ResponseError::ConnectionClosed);
681        }
682        Ok(self.get_mut_stream().flush().await?)
683    }
684
685    /// Flushes all buffered data to the stream.
686    ///
687    /// # Panics
688    ///
689    /// Panics if the flush operation fails.
690    pub async fn flush(&mut self) {
691        self.try_flush().await.unwrap();
692    }
693}