http_type/stream/impl.rs
1use crate::*;
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 Stream {
145 /// Checks if the connection should be kept alive.
146 ///
147 /// This method evaluates whether the connection should remain open based on
148 /// the closed state and the keep_alive parameter.
149 ///
150 /// # Arguments
151 ///
152 /// - `bool` - Whether keep-alive is enabled for the request.
153 ///
154 /// # Returns
155 ///
156 /// - `bool` - True if the connection should be kept alive, otherwise false.
157 #[inline(always)]
158 pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
159 !self.get_closed() && keep_alive
160 }
161
162 /// Parses the HTTP request content from the stream.
163 ///
164 /// This is an internal helper function that performs the actual parsing.
165 ///
166 /// # Returns
167 ///
168 /// - `Result<Request, RequestError>`: The parsed request or an error.
169 async fn get_http_from_stream(&mut self) -> Result<Request, RequestError> {
170 let config: RequestConfig = *self.get_request_config();
171 let buffer_size: usize = config.get_buffer_size();
172 let max_path_size: usize = config.get_max_path_size();
173 let reader: &mut BufReader<&mut TcpStream> =
174 &mut BufReader::with_capacity(buffer_size, self.get_mut_stream());
175 let mut line: String = String::with_capacity(buffer_size);
176 AsyncBufReadExt::read_line(reader, &mut line).await?;
177 let (method, path, version): (RequestMethod, &str, RequestVersion) =
178 Request::get_http_first_line(&line)?;
179 Request::check_http_path_size(path, max_path_size)?;
180 let hash_index: Option<usize> = path.find(HASH);
181 let query_index: Option<usize> = path.find(QUERY);
182 let query: &str = Request::get_http_query(path, query_index, hash_index);
183 let querys: RequestQuerys = Request::get_http_querys(query);
184 let path: RequestPath = Request::get_http_path(path, query_index, hash_index);
185 let (headers, host, content_size): (RequestHeaders, RequestHost, usize) =
186 Request::get_http_headers(reader, &config).await?;
187 let body: RequestBody = Request::get_http_body(reader, content_size).await?;
188 Ok(Request {
189 method,
190 host,
191 version,
192 path,
193 querys,
194 headers,
195 body,
196 })
197 }
198
199 /// Parses an HTTP request from a TCP stream.
200 ///
201 /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
202 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
203 ///
204 /// # Returns
205 ///
206 /// - `Result<Request, RequestError>` - The parsed request or an error.
207 pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
208 if self.get_closed() {
209 return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
210 }
211 let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
212 if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
213 return self.get_http_from_stream().await;
214 }
215 let duration: Duration = Duration::from_millis(timeout_ms);
216 timeout(duration, self.get_http_from_stream()).await?
217 }
218
219 /// Parses a WebSocket request from a TCP stream.
220 ///
221 /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
222 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
223 ///
224 /// # Returns
225 ///
226 /// - `Result<Request, RequestError>`: The parsed WebSocket request or an error.
227 pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
228 if self.get_closed() {
229 return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
230 }
231 let config: RequestConfig = *self.get_request_config();
232 let buffer_size: usize = config.get_buffer_size();
233 let read_timeout_ms: u64 = config.get_read_timeout_ms();
234 let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
235 let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
236 let mut full_frame: Vec<u8> = Vec::new();
237 let mut is_client_response: bool = false;
238 let duration_opt: Option<Duration> =
239 if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
240 None
241 } else {
242 let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
243 Some(Duration::from_millis(adjusted_timeout_ms))
244 };
245 loop {
246 let len: usize = match self
247 .get_websocket_from_stream(&mut temp_buffer, duration_opt, &mut is_client_response)
248 .await
249 {
250 Ok(Some(len)) => len,
251 Ok(None) => continue,
252 Err(error) => return Err(error),
253 };
254 if len == 0 {
255 return Err(RequestError::IncompleteWebSocketFrame(
256 HttpStatus::BadRequest,
257 ));
258 }
259 dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
260 while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
261 is_client_response = true;
262 dynamic_buffer.drain(0..consumed);
263 match frame.get_opcode() {
264 WebSocketOpcode::Close => {
265 return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
266 }
267 WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
268 WebSocketOpcode::Text | WebSocketOpcode::Binary => {
269 match frame.build_full_frame(&mut full_frame) {
270 Ok(Some(result)) => return Ok(result),
271 Ok(None) => continue,
272 Err(error) => return Err(error),
273 }
274 }
275 _ => {
276 return Err(RequestError::WebSocketOpcodeUnsupported(
277 HttpStatus::NotImplemented,
278 ));
279 }
280 }
281 }
282 }
283 }
284
285 /// Reads data from the stream with optional timeout handling.
286 ///
287 /// # Arguments
288 ///
289 /// - `&mut [u8]`: The buffer to read data into.
290 /// - `Option<Duration>`: The optional timeout duration. If Some, timeout is applied; if None, no timeout.
291 /// - `&mut bool`: Mutable reference to track if we got a client response.
292 ///
293 /// # Returns
294 ///
295 /// - `Result<Option<usize>, RequestError>`: The number of bytes read, None for timeout/ping, or an error.
296 pub(crate) async fn get_websocket_from_stream(
297 &mut self,
298 buffer: &mut [u8],
299 duration_opt: Option<Duration>,
300 is_client_response: &mut bool,
301 ) -> Result<Option<usize>, RequestError> {
302 let stream: &mut TcpStream = self.get_mut_stream();
303 if let Some(duration) = duration_opt {
304 return match timeout(duration, stream.read(buffer)).await {
305 Ok(result) => match result {
306 Ok(len) => Ok(Some(len)),
307 Err(error) => Err(error.into()),
308 },
309 Err(error) => {
310 if !*is_client_response {
311 return Err(error.into());
312 }
313 *is_client_response = false;
314 self.try_send(&PING_FRAME).await?;
315 Ok(None)
316 }
317 };
318 }
319 match stream.read(buffer).await {
320 Ok(len) => Ok(Some(len)),
321 Err(error) => Err(error.into()),
322 }
323 }
324
325 /// Sends data over the stream.
326 ///
327 /// # Arguments
328 ///
329 /// - `AsRef<[u8]>` - The data to send (must implement AsRef<[u8]>).
330 ///
331 /// # Returns
332 ///
333 /// - `Result<(), ResponseError>` - Result indicating success or failure.
334 pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
335 where
336 D: AsRef<[u8]>,
337 {
338 if self.get_closed() {
339 return Err(ResponseError::ConnectionClosed);
340 }
341 Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
342 }
343
344 /// Sends data over the stream.
345 ///
346 /// # Arguments
347 ///
348 /// - `AsRef<[u8]>` - The data to send (must implement AsRef<[u8]>).
349 ///
350 /// # Panics
351 ///
352 /// Panics if the write operation fails.
353 pub async fn send<D>(&mut self, data: D)
354 where
355 D: AsRef<[u8]>,
356 {
357 self.try_send(data).await.unwrap();
358 }
359
360 /// Sends multiple data.
361 ///
362 /// # Arguments
363 ///
364 /// - `IntoIterator<Item = AsRef<[u8]>>` - The data list to send.
365 ///
366 /// # Returns
367 ///
368 /// - `Result<(), ResponseError>` - Result indicating success or failure.
369 pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
370 where
371 I: IntoIterator<Item = D>,
372 D: AsRef<[u8]>,
373 {
374 if self.get_closed() {
375 return Err(ResponseError::ConnectionClosed);
376 }
377 let stream: &mut TcpStream = self.get_mut_stream();
378 for data in data_iter {
379 stream.write_all(data.as_ref()).await?;
380 }
381 Ok(())
382 }
383
384 /// Sends multiple data.
385 ///
386 /// # Arguments
387 ///
388 /// - `IntoIterator<Item = AsRef<[u8]>>` - The data list to send.
389 ///
390 /// # Panics
391 ///
392 /// Panics if any write operation fails.
393 pub async fn send_list<I, D>(&mut self, data_iter: I)
394 where
395 I: IntoIterator<Item = D>,
396 D: AsRef<[u8]>,
397 {
398 self.try_send_list(data_iter).await.unwrap();
399 }
400
401 /// Flushes all buffered data to the stream.
402 ///
403 /// # Returns
404 ///
405 /// - `Result<(), ResponseError>` - Result indicating success or failure.
406 pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
407 if self.get_closed() {
408 return Err(ResponseError::ConnectionClosed);
409 }
410 Ok(self.get_mut_stream().flush().await?)
411 }
412
413 /// Flushes all buffered data to the stream.
414 ///
415 /// # Panics
416 ///
417 /// Panics if the flush operation fails.
418 pub async fn flush(&mut self) {
419 self.try_flush().await.unwrap();
420 }
421}