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::new(),
301            header_line_buffer: String::new(),
302            websocket_state: None,
303        }
304    }
305
306    /// Boxes a TCP socket into a `Stream` for the request pipeline.
307    ///
308    /// Kept as the socket-facing constructor so the accept loop keeps its
309    /// existing call shape; it delegates to `from_transport`, so there is one
310    /// construction path rather than two.
311    ///
312    /// # Arguments
313    ///
314    /// - `TcpStream` - The accepted socket to serve the request cycle over.
315    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
316    /// - `bool` - Whether the connection starts already closed.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - A stream serving bytes through the boxed socket.
321    pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
322        Self::from_transport(stream, request_config, closed)
323    }
324
325    /// Reports the address of the remote end of the transport.
326    ///
327    /// Delegates to the transport itself, so a transport without a socket
328    /// identity answers with an error rather than a fabricated address.
329    ///
330    /// # Returns
331    ///
332    /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
333    #[inline(always)]
334    pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
335        self.get_stream().peer_addr()
336    }
337
338    /// Reports the address of the local end of the transport.
339    ///
340    /// Delegates to the transport itself, so a transport without a socket
341    /// identity answers with an error rather than a fabricated address.
342    ///
343    /// # Returns
344    ///
345    /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
346    #[inline(always)]
347    pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
348        self.get_stream().local_addr()
349    }
350
351    /// Checks if the connection should be kept alive.
352    ///
353    /// This method evaluates whether the connection should remain open based on
354    /// the closed state and the keep_alive parameter.
355    ///
356    /// # Arguments
357    ///
358    /// - `bool` - Whether keep-alive is enabled for the request.
359    ///
360    /// # Returns
361    ///
362    /// - `bool` - True if the connection should be kept alive, otherwise false.
363    #[inline(always)]
364    pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
365        !self.get_closed() && keep_alive
366    }
367
368    /// Parses the HTTP request content from the stream into the given request.
369    ///
370    /// The request is reset first, then filled in place so its existing
371    /// allocations are reused across keep-alive requests.
372    ///
373    /// # Arguments
374    ///
375    /// - `&mut Request` - The request object to fill.
376    ///
377    /// # Returns
378    ///
379    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
380    async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
381        request.reset();
382        let config: RequestConfig = *self.get_request_config();
383        let buffer_size: usize = config.get_buffer_size();
384        let max_path_size: usize = config.get_max_path_size();
385        // Move read-ahead storage and its valid window into the reader instead
386        // of allocating and copying the remaining pipeline for every request.
387        let start: usize = self.get_leftover_start();
388        let end: usize = self.get_leftover_end();
389        let buffer: Vec<u8> = mem::take(self.get_mut_leftover());
390        self.set_leftover_start(0);
391        self.set_leftover_end(0);
392        // Split the borrow of the stream: the reader takes the transport, the
393        // line buffers are separate fields, so both can be held at once.
394        let Stream {
395            stream,
396            line_buffer,
397            header_line_buffer,
398            ..
399        } = self;
400        let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
401        reader.set_start(start);
402        reader.set_end(end);
403        line_buffer.clear();
404        let filled_len: usize = future::poll_fn(|cx: &mut Context<'_>| {
405            Pin::new(&mut reader).poll_fill_buf(cx).map_ok(<[u8]>::len)
406        })
407        .await?;
408        let fast_framing: Option<RequestFraming> = if filled_len > 0 {
409            let slice: &[u8] = &reader.get_buffer()[reader.get_start()..reader.get_end()];
410            match request.parse_http_head_from_slice(slice, &config, line_buffer)? {
411                Some((framing, consumed)) => {
412                    Pin::new(&mut reader).consume(consumed);
413                    Some(framing)
414                }
415                None => None,
416            }
417        } else {
418            None
419        };
420        let framing: RequestFraming = match fast_framing {
421            Some(framing) => framing,
422            None => {
423                line_buffer.clear();
424                AsyncBufReadExt::read_line(&mut reader, line_buffer).await?;
425                let (method, path, version): (RequestMethod, &str, RequestVersion) =
426                    Request::get_http_first_line(line_buffer)?;
427                Request::check_http_path_size(path, max_path_size)?;
428                let hash_index: Option<usize> = path.find(HASH);
429                let query_index: Option<usize> = path.find(QUERY);
430                let query: &str = Request::get_http_query(path, query_index, hash_index);
431                Request::fill_http_querys(query, request.get_mut_querys());
432                let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
433                request.get_mut_path().push_str(path_slice);
434                request.set_version(version);
435                let framing: RequestFraming = request
436                    .get_http_headers(&mut reader, &config, header_line_buffer)
437                    .await?;
438                request.set_method(method);
439                framing
440            }
441        };
442        match framing {
443            RequestFraming::Fixed(0) => {}
444            RequestFraming::Fixed(content_size) => {
445                let buffered: usize = reader.get_end() - reader.get_start();
446                if content_size <= buffered {
447                    let body: &mut RequestBody = request.get_mut_body();
448                    body.clear();
449                    let body_start: usize = reader.get_start();
450                    body.extend_from_slice(
451                        &reader.get_buffer()[body_start..body_start + content_size],
452                    );
453                    reader.set_start(body_start + content_size);
454                } else {
455                    if expects_http_continue(request) {
456                        let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
457                        transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
458                        transport.flush().await?;
459                    }
460                    Request::fill_http_body(&mut reader, request.get_mut_body(), content_size)
461                        .await?;
462                }
463            }
464            RequestFraming::Chunked => {
465                Box::pin(fill_chunked_request(&mut reader, request, &config)).await?;
466            }
467        }
468        // Preserve bytes read ahead for the next pipelined request: they have
469        // already left the socket and cannot be read again.
470        let reader_start: usize = reader.get_start();
471        let reader_end: usize = reader.get_end();
472        let pending: Vec<u8> = if reader_start < reader_end {
473            mem::take(reader.get_mut_buffer())
474        } else {
475            Vec::new()
476        };
477        drop(reader);
478        let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
479        let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
480        self.set_leftover(pending);
481        self.set_leftover_start(pending_start);
482        self.set_leftover_end(pending_end);
483        Ok(())
484    }
485
486    /// Parses an HTTP request from a TCP stream into the given request.
487    ///
488    /// The request is reset and filled in place, reusing its allocations.
489    /// An HTTP/1.1 continue expectation can write an interim response after
490    /// header validation and before waiting for the body. A chunked body is
491    /// decoded, with trailers discarded and its content length normalized.
492    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
493    ///
494    /// # Arguments
495    ///
496    /// - `&mut Request` - The request object to reset and fill.
497    ///
498    /// # Returns
499    ///
500    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
501    pub async fn try_fill_http_request(
502        &mut self,
503        request: &mut Request,
504    ) -> Result<(), RequestError> {
505        if self.get_closed() {
506            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
507        }
508        let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
509        if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
510            return self.fill_http_from_stream(request).await;
511        }
512        let duration: Duration = Duration::from_millis(timeout_ms);
513        let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
514        // A request whose bytes have already arrived is read on the first
515        // poll, so the ordinary case never arms a timer at all. Arming one
516        // costs a timer registration and a cancellation per request, and that
517        // churn is the most expensive thing a request path can do once the
518        // concurrency is high enough for the timer driver to become a
519        // bottleneck. The timer is armed only when the read really has to
520        // wait, which is exactly when the timeout can still fire.
521        if let Some(result) = poll_once(reading.as_mut()).await {
522            return result;
523        }
524        timeout(duration, reading).await?
525    }
526
527    /// Parses an HTTP request from a TCP stream.
528    ///
529    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
530    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
531    ///
532    /// # Returns
533    ///
534    /// - `Result<Request, RequestError>` - The parsed request or an error.
535    pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
536        let mut request: Request = Request::default();
537        self.try_fill_http_request(&mut request).await?;
538        Ok(request)
539    }
540
541    /// Parses a WebSocket request from a TCP stream.
542    ///
543    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
544    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
545    ///
546    /// # Returns
547    ///
548    /// - `Result<RequestBody, RequestError>` - The parsed WebSocket request or an error.
549    pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
550        if self.get_closed() {
551            return self.reset_websocket_state_on_error(Err(RequestError::ServerClosedConnection(
552                HttpStatus::BadRequest,
553            )));
554        }
555        let config: RequestConfig = *self.get_request_config();
556        let read_timeout_ms: u64 = config.get_read_timeout_ms();
557        if self.get_mut_websocket_state().is_none() {
558            let mut buffer: Vec<u8> = mem::take(self.get_mut_leftover());
559            buffer.truncate(self.get_leftover_end());
560            buffer.drain(..self.get_leftover_start());
561            self.set_leftover_start(0);
562            self.set_leftover_end(0);
563            self.set_websocket_state(Some(Box::new(WebSocketReadState {
564                buffer,
565                ..WebSocketReadState::default()
566            })));
567        }
568        let duration_opt: Option<Duration> =
569            if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
570                None
571            } else {
572                let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
573                Some(Duration::from_millis(adjusted_timeout_ms))
574            };
575        loop {
576            let parsed: Result<Option<RequestBody>, RequestError> =
577                self.try_parse_websocket_request();
578            if let Some(body) = self.reset_websocket_state_on_error(parsed)? {
579                return Ok(body);
580            }
581            let read: Result<Option<usize>, RequestError> =
582                self.get_websocket_from_stream(duration_opt).await;
583            if matches!(self.reset_websocket_state_on_error(read)?, Some(0)) {
584                return self.reset_websocket_state_on_error(Err(
585                    RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
586                ));
587            }
588        }
589    }
590
591    /// Discards cached parsing state only after an operation completes with an error.
592    ///
593    /// # Arguments
594    ///
595    /// - `Result<T, RequestError>` - The completed parsing or reading operation.
596    ///
597    /// # Returns
598    ///
599    /// - `Result<T, RequestError>` - The unchanged result after releasing failed parsing state.
600    #[inline(always)]
601    fn reset_websocket_state_on_error<T>(
602        &mut self,
603        result: Result<T, RequestError>,
604    ) -> Result<T, RequestError> {
605        if result.is_err() {
606            drop(self.get_mut_websocket_state().take());
607        }
608        result
609    }
610
611    /// Parses buffered frames without discarding incomplete or subsequent input.
612    ///
613    /// # Returns
614    ///
615    /// - `Result<Option<RequestBody>, RequestError>` - A complete message, pending input, or a protocol error.
616    fn try_parse_websocket_request(&mut self) -> Result<Option<RequestBody>, RequestError> {
617        let state: &mut WebSocketReadState = self.get_mut_websocket_state().as_deref_mut().ok_or(
618            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
619        )?;
620        let WebSocketReadState {
621            buffer,
622            full_frame,
623            is_client_response,
624        }: &mut WebSocketReadState = state;
625        while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&buffer[..]) {
626            *is_client_response = true;
627            buffer.drain(..consumed);
628            if buffer.is_empty() {
629                let mut recycled: Vec<u8> = mem::take(buffer);
630                recycled.resize(recycled.capacity().min(MAX_POOLED_READ_BUFFER_SIZE), 0);
631                return_read_buffer(recycled);
632            }
633            match frame.get_opcode() {
634                WebSocketOpcode::Close => {
635                    return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
636                }
637                WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
638                WebSocketOpcode::Text | WebSocketOpcode::Binary => {
639                    if frame.get_fin() && full_frame.is_empty() {
640                        let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
641                        return Ok(Some(payload_data));
642                    }
643                    if let Some(body) = frame.build_full_frame(full_frame)? {
644                        return Ok(Some(body));
645                    }
646                }
647                _ => {
648                    return Err(RequestError::WebSocketOpcodeUnsupported(
649                        HttpStatus::NotImplemented,
650                    ));
651                }
652            }
653        }
654        Ok(None)
655    }
656
657    /// Polls a WebSocket read using a buffer retained only while data is ready.
658    ///
659    /// # Arguments
660    ///
661    /// - `&mut Context<'_>` - The registered task context.
662    ///
663    /// # Returns
664    ///
665    /// - `Poll<io::Result<usize>>` - The bytes appended to persistent parsing state.
666    fn poll_websocket_read(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
667        let capacity: usize = self.get_request_config().get_buffer_size();
668        let mut temporary: Vec<u8> = take_read_buffer(capacity);
669        let mut read_buffer: ReadBuf<'_> = ReadBuf::new(&mut temporary[..capacity]);
670        match Pin::new(&mut **self.get_mut_stream()).poll_read(cx, &mut read_buffer) {
671            Poll::Ready(Ok(())) => {
672                let len: usize = read_buffer.filled().len();
673                temporary.truncate(len);
674                let state: &mut WebSocketReadState =
675                    match self.get_mut_websocket_state().as_deref_mut() {
676                        Some(state) => state,
677                        None => {
678                            return_read_buffer(temporary);
679                            return Poll::Ready(Err(io::Error::new(
680                                io::ErrorKind::InvalidData,
681                                WEBSOCKET_STATE_ERROR,
682                            )));
683                        }
684                    };
685                if state.get_buffer().is_empty() {
686                    mem::swap(state.get_mut_buffer(), &mut temporary);
687                } else {
688                    state.get_mut_buffer().extend_from_slice(&temporary);
689                }
690                return_read_buffer(temporary);
691                Poll::Ready(Ok(len))
692            }
693            Poll::Ready(Err(error)) => {
694                return_read_buffer(temporary);
695                Poll::Ready(Err(error))
696            }
697            Poll::Pending => {
698                return_read_buffer(temporary);
699                Poll::Pending
700            }
701        }
702    }
703
704    /// Reads data from the stream with optional timeout handling.
705    ///
706    /// # Arguments
707    ///
708    /// - `Option<Duration>` - The timeout interval, or no timeout.
709    ///
710    /// # Returns
711    ///
712    /// - `Result<Option<usize>, RequestError>` - Bytes read, a heartbeat, or an error.
713    pub(crate) async fn get_websocket_from_stream(
714        &mut self,
715        duration_opt: Option<Duration>,
716    ) -> Result<Option<usize>, RequestError> {
717        if let Some(duration) = duration_opt {
718            return match timeout(
719                duration,
720                future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx)),
721            )
722            .await
723            {
724                Ok(result) => result.map(Some).map_err(Into::into),
725                Err(error) => {
726                    let state: &mut WebSocketReadState =
727                        self.get_mut_websocket_state().as_deref_mut().ok_or(
728                            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
729                        )?;
730                    if !state.get_is_client_response() {
731                        return Err(error.into());
732                    }
733                    state.set_is_client_response(false);
734                    self.try_send(&PING_FRAME).await?;
735                    Ok(None)
736                }
737            };
738        }
739        future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx))
740            .await
741            .map(Some)
742            .map_err(Into::into)
743    }
744
745    /// Sends data over the stream.
746    ///
747    /// # Arguments
748    ///
749    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
750    ///
751    /// # Returns
752    ///
753    /// - `Result<(), ResponseError>` - Result indicating success or failure.
754    pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
755    where
756        D: AsRef<[u8]>,
757    {
758        if self.get_closed() {
759            return Err(ResponseError::ConnectionClosed);
760        }
761        Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
762    }
763
764    /// Sends data over the stream.
765    ///
766    /// # Arguments
767    ///
768    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
769    ///
770    /// # Panics
771    ///
772    /// Panics if the write operation fails.
773    pub async fn send<D>(&mut self, data: D)
774    where
775        D: AsRef<[u8]>,
776    {
777        self.try_send(data).await.unwrap();
778    }
779
780    /// Sends multiple data.
781    ///
782    /// # Arguments
783    ///
784    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
785    ///   `D` requiring the `AsRef<[u8]>` bound.
786    ///
787    /// # Returns
788    ///
789    /// - `Result<(), ResponseError>` - Result indicating success or failure.
790    pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
791    where
792        I: IntoIterator<Item = D>,
793        D: AsRef<[u8]>,
794    {
795        if self.get_closed() {
796            return Err(ResponseError::ConnectionClosed);
797        }
798        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
799        for data in data_iter {
800            stream.write_all(data.as_ref()).await?;
801        }
802        Ok(())
803    }
804
805    /// Sends multiple data.
806    ///
807    /// # Arguments
808    ///
809    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
810    ///   `D` requiring the `AsRef<[u8]>` bound.
811    ///
812    /// # Panics
813    ///
814    /// Panics if any write operation fails.
815    pub async fn send_list<I, D>(&mut self, data_iter: I)
816    where
817        I: IntoIterator<Item = D>,
818        D: AsRef<[u8]>,
819    {
820        self.try_send_list(data_iter).await.unwrap();
821    }
822
823    /// Flushes all buffered data to the stream.
824    ///
825    /// # Returns
826    ///
827    /// - `Result<(), ResponseError>` - Result indicating success or failure.
828    pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
829        if self.get_closed() {
830            return Err(ResponseError::ConnectionClosed);
831        }
832        Ok(self.get_mut_stream().flush().await?)
833    }
834
835    /// Flushes all buffered data to the stream.
836    ///
837    /// # Panics
838    ///
839    /// Panics if the flush operation fails.
840    pub async fn flush(&mut self) {
841        self.try_flush().await.unwrap();
842    }
843}