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 /// - `&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 /// - `&Stream` - 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 Stream` - 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
144impl Drop for PooledReader<'_> {
145 /// Releases the buffer back to the pool for reuse by later requests.
146 fn drop(&mut self) {
147 let buffer: Vec<u8> = mem::take(self.get_mut_buffer());
148 return_read_buffer(buffer);
149 }
150}
151
152/// Implements non-blocking buffered reads for `PooledReader`.
153///
154/// Buffered bytes are served first; once drained, reads are delegated
155/// directly to the underlying stream.
156impl AsyncRead for PooledReader<'_> {
157 /// Polls to read data into the provided buffer.
158 ///
159 /// # Arguments
160 ///
161 /// - `Pin<&mut Self>` - The pinned reader.
162 /// - `&mut Context<'_>` - The task context.
163 /// - `&mut ReadBuf<'_>` - The destination buffer.
164 ///
165 /// # Returns
166 ///
167 /// - `Poll<io::Result<()>>` - Ready when data was read or an error occurred.
168 fn poll_read(
169 self: Pin<&mut Self>,
170 cx: &mut Context<'_>,
171 buf: &mut ReadBuf<'_>,
172 ) -> Poll<io::Result<()>> {
173 let this: &mut Self = self.get_mut();
174 if *this.get_start() < *this.get_end() {
175 let available: usize = *this.get_end() - *this.get_start();
176 let amount: usize = available.min(buf.remaining());
177 let end: usize = *this.get_start() + amount;
178 buf.put_slice(&this.get_buffer()[*this.get_start()..end]);
179 this.set_start(end);
180 return Poll::Ready(Ok(()));
181 }
182 Pin::new(&mut **this.get_mut_stream()).poll_read(cx, buf)
183 }
184}
185
186/// Implements buffered-read support for `PooledReader`.
187///
188/// The internal buffer is refilled from the stream only when fully
189/// consumed, so a single socket read serves multiple line parses.
190impl AsyncBufRead for PooledReader<'_> {
191 /// Polls to fill the internal buffer and returns the available data.
192 ///
193 /// # Arguments
194 ///
195 /// - `Pin<&mut Self>` - The pinned reader.
196 /// - `&mut Context<'_>` - The task context.
197 ///
198 /// # Returns
199 ///
200 /// - `Poll<io::Result<&[u8]>>` - Ready with the unconsumed bytes, or an error.
201 fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
202 let this: &mut Self = self.get_mut();
203 let PooledReader {
204 stream,
205 buffer,
206 start,
207 end,
208 } = this;
209 if *start >= *end {
210 *start = 0;
211 *end = 0;
212 let mut read_buf: ReadBuf<'_> = ReadBuf::new(buffer);
213 match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
214 Poll::Ready(Ok(())) => {
215 *end = read_buf.filled().len();
216 }
217 Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
218 Poll::Pending => return Poll::Pending,
219 }
220 }
221 Poll::Ready(Ok(&buffer[*start..*end]))
222 }
223
224 /// Marks the given number of bytes as consumed.
225 ///
226 /// # Arguments
227 ///
228 /// - `Pin<&mut Self>` - The pinned reader.
229 /// - `usize` - The number of bytes to consume.
230 fn consume(self: Pin<&mut Self>, amount: usize) {
231 let this: &mut Self = self.get_mut();
232 let new_start: usize = (*this.get_start() + amount).min(*this.get_end());
233 this.set_start(new_start);
234 }
235}
236
237impl Stream {
238 /// Checks if the connection should be kept alive.
239 ///
240 /// This method evaluates whether the connection should remain open based on
241 /// the closed state and the keep_alive parameter.
242 ///
243 /// # Arguments
244 ///
245 /// - `bool` - Whether keep-alive is enabled for the request.
246 ///
247 /// # Returns
248 ///
249 /// - `bool` - True if the connection should be kept alive, otherwise false.
250 #[inline(always)]
251 pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
252 !self.get_closed() && keep_alive
253 }
254
255 /// Parses the HTTP request content from the stream into the given request.
256 ///
257 /// The request is reset first, then filled in place so its existing
258 /// allocations are reused across keep-alive requests.
259 ///
260 /// # Arguments
261 ///
262 /// - `&mut Request` - The request object to fill.
263 ///
264 /// # Returns
265 ///
266 /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
267 async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
268 request.reset();
269 let config: RequestConfig = *self.get_request_config();
270 let buffer_size: usize = config.get_buffer_size();
271 let max_path_size: usize = config.get_max_path_size();
272 let buffer: Vec<u8> = take_read_buffer(buffer_size);
273 let mut reader: PooledReader<'_> = PooledReader::new(self.get_mut_stream(), buffer);
274 let mut line: String = String::with_capacity(REQUEST_LINE_BUFFER_CAPACITY);
275 AsyncBufReadExt::read_line(&mut reader, &mut line).await?;
276 let (method, path, version): (RequestMethod, &str, RequestVersion) =
277 Request::get_http_first_line(&line)?;
278 Request::check_http_path_size(path, max_path_size)?;
279 let hash_index: Option<usize> = path.find(HASH);
280 let query_index: Option<usize> = path.find(QUERY);
281 let query: &str = Request::get_http_query(path, query_index, hash_index);
282 Request::fill_http_querys(query, request.get_mut_querys());
283 let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
284 request.get_mut_path().push_str(path_slice);
285 let content_size: usize = request.get_http_headers(&mut reader, &config).await?;
286 request.set_method(method);
287 request.set_version(version);
288 Request::fill_http_body(&mut reader, request.get_mut_body(), content_size).await?;
289 Ok(())
290 }
291
292 /// Parses an HTTP request from a TCP stream into the given request.
293 ///
294 /// The request is reset and filled in place, reusing its allocations.
295 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
296 ///
297 /// # Arguments
298 ///
299 /// - `&mut Request` - The request object to reset and fill.
300 ///
301 /// # Returns
302 ///
303 /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
304 pub async fn try_fill_http_request(
305 &mut self,
306 request: &mut Request,
307 ) -> Result<(), RequestError> {
308 if self.get_closed() {
309 return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
310 }
311 let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
312 if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
313 return self.fill_http_from_stream(request).await;
314 }
315 let duration: Duration = Duration::from_millis(timeout_ms);
316 timeout(duration, self.fill_http_from_stream(request)).await?
317 }
318
319 /// Parses an HTTP request from a TCP stream.
320 ///
321 /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
322 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
323 ///
324 /// # Returns
325 ///
326 /// - `Result<Request, RequestError>` - The parsed request or an error.
327 pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
328 let mut request: Request = Request::default();
329 self.try_fill_http_request(&mut request).await?;
330 Ok(request)
331 }
332
333 /// Parses a WebSocket request from a TCP stream.
334 ///
335 /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
336 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
337 ///
338 /// # Returns
339 ///
340 /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
341 pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
342 if self.get_closed() {
343 return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
344 }
345 let config: RequestConfig = *self.get_request_config();
346 let buffer_size: usize = config.get_buffer_size();
347 let read_timeout_ms: u64 = config.get_read_timeout_ms();
348 let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
349 let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
350 let mut full_frame: Vec<u8> = Vec::new();
351 let mut is_client_response: bool = false;
352 let duration_opt: Option<Duration> =
353 if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
354 None
355 } else {
356 let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
357 Some(Duration::from_millis(adjusted_timeout_ms))
358 };
359 loop {
360 let len: usize = match self
361 .get_websocket_from_stream(&mut temp_buffer, duration_opt, &mut is_client_response)
362 .await
363 {
364 Ok(Some(len)) => len,
365 Ok(None) => continue,
366 Err(error) => return Err(error),
367 };
368 if len == 0 {
369 return Err(RequestError::IncompleteWebSocketFrame(
370 HttpStatus::BadRequest,
371 ));
372 }
373 dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
374 while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
375 is_client_response = true;
376 dynamic_buffer.drain(0..consumed);
377 match frame.get_opcode() {
378 WebSocketOpcode::Close => {
379 return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
380 }
381 WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
382 WebSocketOpcode::Text | WebSocketOpcode::Binary => {
383 match frame.build_full_frame(&mut full_frame) {
384 Ok(Some(result)) => return Ok(result),
385 Ok(None) => continue,
386 Err(error) => return Err(error),
387 }
388 }
389 _ => {
390 return Err(RequestError::WebSocketOpcodeUnsupported(
391 HttpStatus::NotImplemented,
392 ));
393 }
394 }
395 }
396 }
397 }
398
399 /// Reads data from the stream with optional timeout handling.
400 ///
401 /// # Arguments
402 ///
403 /// - `&mut [u8]` - The buffer to read data into.
404 /// - `Option<Duration>` - The optional timeout duration. If Some, timeout is applied; if None, no timeout.
405 /// - `&mut bool` - Mutable reference to track if we got a client response.
406 ///
407 /// # Returns
408 ///
409 /// - `Result<Option<usize>, RequestError>` - The number of bytes read, None for timeout/ping, or an error.
410 pub(crate) async fn get_websocket_from_stream(
411 &mut self,
412 buffer: &mut [u8],
413 duration_opt: Option<Duration>,
414 is_client_response: &mut bool,
415 ) -> Result<Option<usize>, RequestError> {
416 let stream: &mut TcpStream = self.get_mut_stream();
417 if let Some(duration) = duration_opt {
418 return match timeout(duration, stream.read(buffer)).await {
419 Ok(result) => match result {
420 Ok(len) => Ok(Some(len)),
421 Err(error) => Err(error.into()),
422 },
423 Err(error) => {
424 if !*is_client_response {
425 return Err(error.into());
426 }
427 *is_client_response = false;
428 self.try_send(&PING_FRAME).await?;
429 Ok(None)
430 }
431 };
432 }
433 match stream.read(buffer).await {
434 Ok(len) => Ok(Some(len)),
435 Err(error) => Err(error.into()),
436 }
437 }
438
439 /// Sends data over the stream.
440 ///
441 /// # Arguments
442 ///
443 /// - `AsRef<[u8]>` - The data to send (must implement AsRef<[u8]>).
444 ///
445 /// # Returns
446 ///
447 /// - `Result<(), ResponseError>` - Result indicating success or failure.
448 pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
449 where
450 D: AsRef<[u8]>,
451 {
452 if self.get_closed() {
453 return Err(ResponseError::ConnectionClosed);
454 }
455 Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
456 }
457
458 /// Sends data over the stream.
459 ///
460 /// # Arguments
461 ///
462 /// - `AsRef<[u8]>` - The data to send (must implement AsRef<[u8]>).
463 ///
464 /// # Panics
465 ///
466 /// Panics if the write operation fails.
467 pub async fn send<D>(&mut self, data: D)
468 where
469 D: AsRef<[u8]>,
470 {
471 self.try_send(data).await.unwrap();
472 }
473
474 /// Sends multiple data.
475 ///
476 /// # Arguments
477 ///
478 /// - `IntoIterator<Item = AsRef<[u8]>>` - The data list to send.
479 ///
480 /// # Returns
481 ///
482 /// - `Result<(), ResponseError>` - Result indicating success or failure.
483 pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
484 where
485 I: IntoIterator<Item = D>,
486 D: AsRef<[u8]>,
487 {
488 if self.get_closed() {
489 return Err(ResponseError::ConnectionClosed);
490 }
491 let stream: &mut TcpStream = self.get_mut_stream();
492 for data in data_iter {
493 stream.write_all(data.as_ref()).await?;
494 }
495 Ok(())
496 }
497
498 /// Sends multiple data.
499 ///
500 /// # Arguments
501 ///
502 /// - `IntoIterator<Item = AsRef<[u8]>>` - The data list to send.
503 ///
504 /// # Panics
505 ///
506 /// Panics if any write operation fails.
507 pub async fn send_list<I, D>(&mut self, data_iter: I)
508 where
509 I: IntoIterator<Item = D>,
510 D: AsRef<[u8]>,
511 {
512 self.try_send_list(data_iter).await.unwrap();
513 }
514
515 /// Flushes all buffered data to the stream.
516 ///
517 /// # Returns
518 ///
519 /// - `Result<(), ResponseError>` - Result indicating success or failure.
520 pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
521 if self.get_closed() {
522 return Err(ResponseError::ConnectionClosed);
523 }
524 Ok(self.get_mut_stream().flush().await?)
525 }
526
527 /// Flushes all buffered data to the stream.
528 ///
529 /// # Panics
530 ///
531 /// Panics if the flush operation fails.
532 pub async fn flush(&mut self) {
533 self.try_flush().await.unwrap();
534 }
535}