hyperlane/context/impl.rs
1use crate::*;
2
3/// Implementation of `Default` trait for `Context`.
4impl Default for Context {
5 /// Creates a default `Context` instance.
6 ///
7 /// # Returns
8 ///
9 /// - `Context` - A new context with default values and a static default server.
10 #[inline(always)]
11 fn default() -> Self {
12 Self {
13 aborted: false,
14 closed: false,
15 stream: None,
16 request: Request::default(),
17 response: Response::default(),
18 route_params: RouteParams::default(),
19 attributes: ThreadSafeAttributeStore::default(),
20 server: default_server(),
21 }
22 }
23}
24
25/// Implementation of `PartialEq` trait for `Context`.
26impl PartialEq for Context {
27 /// Compares two `Context` instances for equality.
28 ///
29 /// # Arguments
30 ///
31 /// - `&Self` - The first `Context` instance.
32 /// - `&Self` - The second `Context` instance.
33 ///
34 /// # Returns
35 ///
36 /// - `bool` - True if the instances are equal, otherwise false.
37 #[inline(always)]
38 fn eq(&self, other: &Self) -> bool {
39 self.get_aborted() == other.get_aborted()
40 && self.get_closed() == other.get_closed()
41 && self.get_request() == other.get_request()
42 && self.get_response() == other.get_response()
43 && self.get_route_params() == other.get_route_params()
44 && self.get_attributes().len() == other.get_attributes().len()
45 && self.try_get_stream().is_some() == other.try_get_stream().is_some()
46 && self.get_server() == other.get_server()
47 }
48}
49
50/// Implementation of `Eq` trait for `Context`.
51impl Eq for Context {}
52
53/// Implementation of `From` trait for `Context` from `&'static Server`.
54impl From<&'static Server> for Context {
55 /// Converts a `&'static Server` into a `Context` with default request and response.
56 ///
57 /// # Arguments
58 ///
59 /// - `&'static Server` - The server reference to convert.
60 ///
61 /// # Returns
62 ///
63 /// - `Context` - The newly created context instance.
64 #[inline(always)]
65 fn from(server: &'static Server) -> Self {
66 let mut ctx: Context = Context::default();
67 ctx.set_server(server);
68 ctx
69 }
70}
71
72/// Implementation of `From` trait for converting `&ArcRwLockStream` into `Context`.
73impl From<&ArcRwLockStream> for Context {
74 /// Converts a reference to a network stream into a `Context` with default request.
75 ///
76 /// # Arguments
77 ///
78 /// - `&ArcRwLockStream` - The network stream reference to convert.
79 ///
80 /// # Returns
81 ///
82 /// - `Context` - The newly created context instance.
83 #[inline(always)]
84 fn from(stream: &ArcRwLockStream) -> Self {
85 let mut ctx: Context = Context::default();
86 ctx.set_stream(Some(stream.clone()));
87 ctx
88 }
89}
90
91/// Implementation of `From` trait for converting `ArcRwLockStream` into `Context`.
92impl From<ArcRwLockStream> for Context {
93 /// Converts a network stream into a `Context` with default request.
94 ///
95 /// # Arguments
96 ///
97 /// - `ArcRwLockStream` - The network stream to convert.
98 ///
99 /// # Returns
100 ///
101 /// - `Context` - The newly created context instance.
102 #[inline(always)]
103 fn from(stream: ArcRwLockStream) -> Self {
104 (&stream).into()
105 }
106}
107
108/// Implementation of `From` trait for converting `usize` address into `Context`.
109impl From<usize> for Context {
110 /// Converts a memory address into an owned `Context` by cloning from the reference.
111 ///
112 /// # Arguments
113 ///
114 /// - `usize` - The memory address of the `Context` instance.
115 ///
116 /// # Returns
117 ///
118 /// - `Context` - A cloned `Context` instance from the given address.
119 #[inline(always)]
120 fn from(addr: usize) -> Self {
121 let ctx: &Context = addr.into();
122 ctx.clone()
123 }
124}
125
126/// Implementation of `From` trait for converting `usize` address into `&Context`.
127impl From<usize> for &'static Context {
128 /// Converts a memory address into a reference to `Context`.
129 ///
130 /// # Arguments
131 ///
132 /// - `usize` - The memory address of the `Context` instance.
133 ///
134 /// # Returns
135 ///
136 /// - `&'static Context` - A reference to the `Context` at the given address.
137 #[inline(always)]
138 fn from(addr: usize) -> &'static Context {
139 unsafe { &*(addr as *const Context) }
140 }
141}
142
143/// Implementation of `From` trait for converting `usize` address into `&mut Context`.
144impl<'a> From<usize> for &'a mut Context {
145 /// Converts a memory address into a mutable reference to `Context`.
146 ///
147 /// # Arguments
148 ///
149 /// - `usize` - The memory address of the `Context` instance.
150 ///
151 /// # Returns
152 ///
153 /// - `&mut Context` - A mutable reference to the `Context` at the given address.
154 #[inline(always)]
155 fn from(addr: usize) -> &'a mut Context {
156 unsafe { &mut *(addr as *mut Context) }
157 }
158}
159
160/// Implementation of `From` trait for converting `&Context` into `usize` address.
161impl From<&Context> for usize {
162 /// Converts a reference to `Context` into its memory address.
163 ///
164 /// # Arguments
165 ///
166 /// - `&Context` - The reference to the `Context` instance.
167 ///
168 /// # Returns
169 ///
170 /// - `usize` - The memory address of the `Context` instance.
171 #[inline(always)]
172 fn from(ctx: &Context) -> Self {
173 ctx as *const Context as usize
174 }
175}
176
177/// Implementation of `From` trait for converting `&mut Context` into `usize` address.
178impl From<&mut Context> for usize {
179 /// Converts a mutable reference to `Context` into its memory address.
180 ///
181 /// # Arguments
182 ///
183 /// - `&mut Context` - The mutable reference to the `Context` instance.
184 ///
185 /// # Returns
186 ///
187 /// - `usize` - The memory address of the `Context` instance.
188 #[inline(always)]
189 fn from(ctx: &mut Context) -> Self {
190 ctx as *mut Context as usize
191 }
192}
193
194/// Implementation of `AsRef` trait for `Context`.
195impl AsRef<Context> for Context {
196 /// Converts `&Context` to `&Context` via memory address conversion.
197 ///
198 /// # Returns
199 ///
200 /// - `&Context` - A reference to the `Context` instance.
201 #[inline(always)]
202 fn as_ref(&self) -> &Context {
203 let addr: usize = (self as &Context).into();
204 addr.into()
205 }
206}
207
208/// Implementation of `AsMut` trait for `Context`.
209impl AsMut<Context> for Context {
210 /// Converts `&mut Context` to `&mut Context` via memory address conversion.
211 ///
212 /// # Returns
213 ///
214 /// - `&mut Context` - A mutable reference to the `Context` instance.
215 #[inline(always)]
216 fn as_mut(&mut self) -> &mut Context {
217 let addr: usize = (self as &mut Context).into();
218 addr.into()
219 }
220}
221
222/// Implementation of methods for `Context` structure.
223impl Context {
224 /// Creates a new `Context` with the provided network stream, HTTP request and server.
225 ///
226 /// # Arguments
227 ///
228 /// - `&ArcRwLockStream` - The network stream.
229 /// - `&Request` - The HTTP request.
230 /// - `&'static Server` - The server.
231 ///
232 /// # Returns
233 ///
234 /// - `Context` - The newly created context.
235 #[inline(always)]
236 pub(crate) fn new(
237 stream: &ArcRwLockStream,
238 request: &Request,
239 server: &'static Server,
240 ) -> Context {
241 let mut ctx: Context = Context::default();
242 ctx.set_stream(Some(stream.clone()))
243 .set_request(request.clone())
244 .set_server(server)
245 .get_mut_response()
246 .set_version(request.get_version().clone());
247 ctx
248 }
249
250 /// Reads an HTTP request from the underlying stream.
251 ///
252 /// # Returns
253 ///
254 /// - `Result<Request, RequestError>` - The parsed request or error.
255 pub async fn http_from_stream(&mut self) -> Result<Request, RequestError> {
256 if self.get_aborted() {
257 return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
258 }
259 if let Some(stream) = self.try_get_stream() {
260 let request_res: Result<Request, RequestError> =
261 Request::http_from_stream(stream, self.get_server().get_request_config()).await;
262 if let Ok(request) = request_res.as_ref() {
263 self.set_request(request.clone());
264 }
265 return request_res;
266 };
267 Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
268 }
269
270 /// Reads a WebSocket frame from the underlying stream.
271 ///
272 /// # Returns
273 ///
274 /// - `Result<Request, RequestError>` - The parsed frame or error.
275 pub async fn ws_from_stream(&mut self) -> Result<Request, RequestError> {
276 if self.get_aborted() {
277 return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
278 }
279 if let Some(stream) = self.try_get_stream() {
280 let last_request: &Request = self.get_request();
281 let request_res: Result<Request, RequestError> = last_request
282 .ws_from_stream(stream, self.get_server().get_request_config())
283 .await;
284 match request_res.as_ref() {
285 Ok(request) => {
286 self.set_request(request.clone());
287 }
288 Err(_) => {
289 self.set_request(last_request.clone());
290 }
291 }
292 return request_res;
293 };
294 Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
295 }
296
297 /// Checks if the connection has been terminated (aborted or closed).
298 ///
299 /// # Returns
300 ///
301 /// - `bool` - True if the connection is either aborted or closed, otherwise false.
302 #[inline(always)]
303 pub fn is_terminated(&self) -> bool {
304 self.get_aborted() || self.get_closed()
305 }
306
307 /// Checks if the connection should be kept alive.
308 ///
309 /// This method evaluates whether the connection should remain open based on
310 /// the closed state and the keep_alive parameter.
311 ///
312 /// # Arguments
313 ///
314 /// - `bool` - Whether keep-alive is enabled for the request.
315 ///
316 /// # Returns
317 ///
318 /// - `bool` - True if the connection should be kept alive, otherwise false.
319 #[inline(always)]
320 pub(crate) fn is_keep_alive(&self, keep_alive: bool) -> bool {
321 !self.get_closed() && keep_alive
322 }
323
324 /// Retrieves the remote socket address of the connection.
325 ///
326 /// # Returns
327 ///
328 /// - `Option<SocketAddr>` - The socket address of the remote peer if available.
329 pub async fn try_get_socket_addr(&self) -> Option<SocketAddr> {
330 self.try_get_stream()
331 .as_ref()?
332 .read()
333 .await
334 .peer_addr()
335 .ok()
336 }
337
338 /// Retrieves the remote socket address.
339 ///
340 /// # Returns
341 ///
342 /// - `SocketAddr` - The socket address of the remote peer.
343 ///
344 /// # Panics
345 ///
346 /// - If the socket address is not found.
347 pub async fn get_socket_addr(&self) -> SocketAddr {
348 self.try_get_socket_addr().await.unwrap()
349 }
350
351 /// Retrieves the remote socket address as a string.
352 ///
353 /// # Returns
354 ///
355 /// - `Option<String>` - The string representation of the socket address if available.
356 pub async fn try_get_socket_addr_string(&self) -> Option<String> {
357 self.try_get_socket_addr()
358 .await
359 .map(|data| data.to_string())
360 }
361
362 /// Retrieves the remote socket address as a string.
363 ///
364 /// # Returns
365 ///
366 /// - `String` - The string representation of the socket address.
367 ///
368 /// # Panics
369 ///
370 /// - If the socket address is not found.
371 pub async fn get_socket_addr_string(&self) -> String {
372 self.get_socket_addr().await.to_string()
373 }
374
375 /// Retrieves the IP address part of the remote socket address.
376 ///
377 /// # Returns
378 ///
379 /// - `Option<SocketHost>` - The IP address of the remote peer.
380 pub async fn try_get_socket_host(&self) -> Option<SocketHost> {
381 self.try_get_socket_addr()
382 .await
383 .map(|socket_addr: SocketAddr| socket_addr.ip())
384 }
385
386 /// Retrieves the IP address part of the remote socket address.
387 ///
388 /// # Returns
389 ///
390 /// - `SocketHost` - The IP address of the remote peer.
391 ///
392 /// # Panics
393 ///
394 /// - If the socket address is not found.
395 pub async fn get_socket_host(&self) -> SocketHost {
396 self.try_get_socket_host().await.unwrap()
397 }
398
399 /// Retrieves the port number part of the remote socket address.
400 ///
401 /// # Returns
402 ///
403 /// - `Option<SocketPort>` - The port number of the remote peer if available.
404 pub async fn try_get_socket_port(&self) -> Option<SocketPort> {
405 self.try_get_socket_addr()
406 .await
407 .map(|socket_addr: SocketAddr| socket_addr.port())
408 }
409
410 /// Retrieves the port number part of the remote socket address.
411 ///
412 /// # Returns
413 ///
414 /// - `SocketPort` - The port number of the remote peer.
415 ///
416 /// # Panics
417 ///
418 /// - If the socket address is not found.
419 pub async fn get_socket_port(&self) -> SocketPort {
420 self.try_get_socket_port().await.unwrap()
421 }
422
423 /// Attempts to retrieve a specific route parameter by its name.
424 ///
425 /// # Arguments
426 ///
427 /// - `AsRef<str>` - The name of the route parameter to retrieve.
428 ///
429 /// # Returns
430 ///
431 /// - `Option<String>` - The value of the route parameter if it exists.
432 #[inline(always)]
433 pub fn try_get_route_param<T>(&self, name: T) -> Option<String>
434 where
435 T: AsRef<str>,
436 {
437 self.get_route_params().get(name.as_ref()).cloned()
438 }
439
440 /// Retrieves a specific route parameter by its name, panicking if not found.
441 ///
442 /// # Arguments
443 ///
444 /// - `AsRef<str>` - The name of the route parameter to retrieve.
445 ///
446 /// # Returns
447 ///
448 /// - `String` - The value of the route parameter if it exists.
449 ///
450 /// # Panics
451 ///
452 /// - If the route parameter is not found.
453 #[inline(always)]
454 pub fn get_route_param<T>(&self, name: T) -> String
455 where
456 T: AsRef<str>,
457 {
458 self.try_get_route_param(name).unwrap()
459 }
460
461 /// Attempts to retrieve a specific attribute by its key, casting it to the specified type.
462 ///
463 /// # Arguments
464 ///
465 /// - `AsRef<str>` - The key of the attribute to retrieve.
466 ///
467 /// # Returns
468 ///
469 /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
470 #[inline(always)]
471 pub fn try_get_attribute<V>(&self, key: impl AsRef<str>) -> Option<V>
472 where
473 V: AnySendSyncClone,
474 {
475 self.get_attributes()
476 .get(&Attribute::External(key.as_ref().to_owned()).to_string())
477 .and_then(|arc| arc.downcast_ref::<V>())
478 .cloned()
479 }
480
481 /// Retrieves a specific attribute by its key, casting it to the specified type, panicking if not found.
482 ///
483 /// # Arguments
484 ///
485 /// - `AsRef<str>` - The key of the attribute to retrieve.
486 ///
487 /// # Returns
488 ///
489 /// - `AnySendSyncClone` - The attribute value if it exists and can be cast to the specified type.
490 ///
491 /// # Panics
492 ///
493 /// - If the attribute is not found.
494 #[inline(always)]
495 pub fn get_attribute<V>(&self, key: impl AsRef<str>) -> V
496 where
497 V: AnySendSyncClone,
498 {
499 self.try_get_attribute(key).unwrap()
500 }
501
502 /// Sets an attribute in the context.
503 ///
504 /// # Arguments
505 ///
506 /// - `AsRef<str>` - The key of the attribute to set.
507 /// - `AnySendSyncClone` - The value of the attribute.
508 ///
509 /// # Returns
510 ///
511 /// - `&mut Self` - A reference to the modified context.
512 #[inline(always)]
513 pub fn set_attribute<K, V>(&mut self, key: K, value: V) -> &mut Self
514 where
515 K: AsRef<str>,
516 V: AnySendSyncClone,
517 {
518 self.get_mut_attributes().insert(
519 Attribute::External(key.as_ref().to_owned()).to_string(),
520 Arc::new(value),
521 );
522 self
523 }
524
525 /// Removes an attribute from the context.
526 ///
527 /// # Arguments
528 ///
529 /// - `AsRef<str>` - The key of the attribute to remove.
530 ///
531 /// # Returns
532 ///
533 /// - `&mut Self` - A reference to the modified context.
534 #[inline(always)]
535 pub fn remove_attribute<K>(&mut self, key: K) -> &mut Self
536 where
537 K: AsRef<str>,
538 {
539 self.get_mut_attributes()
540 .remove(&Attribute::External(key.as_ref().to_owned()).to_string());
541 self
542 }
543
544 /// Clears all attributes from the context.
545 ///
546 /// # Returns
547 ///
548 /// - `&mut Self` - A reference to the modified context.
549 #[inline(always)]
550 pub fn clear_attribute(&mut self) -> &mut Self {
551 self.get_mut_attributes().clear();
552 self
553 }
554
555 /// Retrieves an internal framework attribute.
556 ///
557 /// # Arguments
558 ///
559 /// - `InternalAttribute` - The internal attribute key to retrieve.
560 ///
561 /// # Returns
562 ///
563 /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
564 #[inline(always)]
565 fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
566 where
567 V: AnySendSyncClone,
568 {
569 self.get_attributes()
570 .get(&Attribute::Internal(key).to_string())
571 .and_then(|arc| arc.downcast_ref::<V>())
572 .cloned()
573 }
574
575 /// Retrieves an internal framework attribute.
576 ///
577 /// # Arguments
578 ///
579 /// - `InternalAttribute` - The internal attribute key to retrieve.
580 ///
581 /// # Returns
582 ///
583 /// - `AnySendSyncClone` - The attribute value if it exists and can be cast to the specified type.
584 ///
585 /// # Panics
586 ///
587 /// - If the attribute is not found.
588 #[inline(always)]
589 fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
590 where
591 V: AnySendSyncClone,
592 {
593 self.try_get_internal_attribute(key).unwrap()
594 }
595
596 /// Sets an internal framework attribute.
597 ///
598 /// # Arguments
599 ///
600 /// - `InternalAttribute` - The internal attribute key to set.
601 /// - `AnySendSyncClone` - The value of the attribute.
602 ///
603 /// # Returns
604 ///
605 /// - `&mut Self` - A reference to the modified context.
606 #[inline(always)]
607 fn set_internal_attribute<V>(&mut self, key: InternalAttribute, value: V) -> &mut Self
608 where
609 V: AnySendSyncClone,
610 {
611 self.get_mut_attributes()
612 .insert(Attribute::Internal(key).to_string(), Arc::new(value));
613 self
614 }
615
616 /// Stores panic data for the current task context.
617 ///
618 /// # Arguments
619 ///
620 /// - `PanicData` - The panic data specific to the current task.
621 ///
622 /// # Returns
623 ///
624 /// - `&mut Self` - Reference to the modified context for method chaining.
625 #[inline(always)]
626 pub(crate) fn set_task_panic(&mut self, panic_data: PanicData) -> &mut Self {
627 self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
628 }
629
630 /// Retrieves panic data associated with the current task.
631 ///
632 /// # Returns
633 ///
634 /// - `Option<PanicData>` - Task panic data if a panic was caught during execution.
635 #[inline(always)]
636 pub fn try_get_task_panic_data(&self) -> Option<PanicData> {
637 self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
638 }
639
640 /// Retrieves panic data associated with the current task.
641 ///
642 /// # Returns
643 ///
644 /// - `PanicData` - Task panic data if available.
645 ///
646 /// # Panics
647 ///
648 /// - If no task panic data is found.
649 #[inline(always)]
650 pub fn get_task_panic_data(&self) -> PanicData {
651 self.get_internal_attribute(InternalAttribute::TaskPanicData)
652 }
653
654 /// Sets the request error information for the context.
655 ///
656 /// # Arguments
657 ///
658 /// - `RequestError` - The request error information to store.
659 ///
660 /// # Returns
661 ///
662 /// - `&mut Self` - A reference to the modified context.
663 #[inline(always)]
664 pub(crate) fn set_request_error_data(&mut self, request_error: RequestError) -> &mut Self {
665 self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
666 }
667
668 /// Retrieves request error information if an error occurred during handling.
669 ///
670 /// # Returns
671 ///
672 /// - `Option<RequestError>` - The request error information if an error was caught.
673 #[inline(always)]
674 pub fn try_get_request_error_data(&self) -> Option<RequestError> {
675 self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
676 }
677
678 /// Retrieves request error information if an error occurred during handling.
679 ///
680 /// # Returns
681 ///
682 /// - `RequestError` - The request error information if an error was caught.
683 ///
684 /// # Panics
685 ///
686 /// - If the request error information is not found.
687 #[inline(always)]
688 pub fn get_request_error_data(&self) -> RequestError {
689 self.get_internal_attribute(InternalAttribute::RequestErrorData)
690 }
691
692 /// Sends HTTP response data over the stream.
693 ///
694 /// # Returns
695 ///
696 /// - `Result<(), ResponseError>` - Result indicating success or failure.
697 pub async fn try_send(&mut self) -> Result<(), ResponseError> {
698 if self.is_terminated() {
699 return Err(ResponseError::Terminated);
700 }
701 let response_data: ResponseData = self.get_mut_response().build();
702 if let Some(stream) = self.try_get_stream() {
703 return stream.try_send(response_data).await;
704 }
705 Err(ResponseError::NotFoundStream)
706 }
707
708 /// Sends HTTP response data over the stream.
709 ///
710 /// # Panics
711 ///
712 /// Panics if the write operation fails.
713 pub async fn send(&mut self) {
714 self.try_send().await.unwrap();
715 }
716
717 /// Sends HTTP response body.
718 ///
719 /// # Returns
720 ///
721 /// - `Result<(), ResponseError>` - Result indicating success or failure.
722 pub async fn try_send_body(&self) -> Result<(), ResponseError> {
723 if self.is_terminated() {
724 return Err(ResponseError::Terminated);
725 }
726 self.try_send_body_with_data(self.get_response().get_body())
727 .await
728 }
729
730 /// Sends HTTP response body.
731 ///
732 /// # Panics
733 ///
734 /// Panics if the write operation fails.
735 pub async fn send_body(&self) {
736 self.try_send_body().await.unwrap();
737 }
738
739 /// Sends only the response body to the client with additional data.
740 ///
741 /// This method is useful for streaming data or for responses where headers have already been sent.
742 ///
743 /// # Arguments
744 ///
745 /// - `AsRef<[u8]>` - The additional data to send as the body.
746 ///
747 /// # Returns
748 ///
749 /// - `Result<(), ResponseError>` - The result of the send operation.
750 pub async fn try_send_body_with_data<D>(&self, data: D) -> Result<(), ResponseError>
751 where
752 D: AsRef<[u8]>,
753 {
754 if self.is_terminated() {
755 return Err(ResponseError::Terminated);
756 }
757 if let Some(stream) = self.try_get_stream() {
758 return stream.try_send_body(data).await;
759 }
760 Err(ResponseError::NotFoundStream)
761 }
762
763 /// Sends HTTP response body.
764 ///
765 /// # Arguments
766 ///
767 /// - `AsRef<[u8]>` - The response body data (must implement AsRef<[u8]>).
768 ///
769 /// # Panics
770 ///
771 /// Panics if the write operation fails.
772 pub async fn send_body_with_data<D>(&self, data: D)
773 where
774 D: AsRef<[u8]>,
775 {
776 self.try_send_body_with_data(data).await.unwrap();
777 }
778
779 /// Sends multiple HTTP response bodies sequentially.
780 ///
781 /// # Arguments
782 ///
783 /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The response body data list to send.
784 ///
785 /// # Returns
786 ///
787 /// - `Result<(), ResponseError>` - Result indicating success or failure.
788 pub async fn try_send_body_list<I, D>(&self, data_iter: I) -> Result<(), ResponseError>
789 where
790 I: IntoIterator<Item = D>,
791 D: AsRef<[u8]>,
792 {
793 if self.is_terminated() {
794 return Err(ResponseError::Terminated);
795 }
796 if let Some(stream) = self.try_get_stream() {
797 return stream.try_send_body_list(data_iter).await;
798 }
799 Err(ResponseError::NotFoundStream)
800 }
801
802 /// Sends multiple HTTP response bodies sequentially.
803 ///
804 /// # Arguments
805 ///
806 /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The response body data list to send.
807 ///
808 /// # Panics
809 ///
810 /// Panics if any write operation fails.
811 pub async fn send_body_list<I, D>(&self, data_iter: I)
812 where
813 I: IntoIterator<Item = D>,
814 D: AsRef<[u8]>,
815 {
816 self.try_send_body_list(data_iter).await.unwrap();
817 }
818
819 /// Sends a list of response bodies to the client with additional data.
820 ///
821 /// This is useful for streaming multiple data chunks or for responses where headers have already been sent.
822 ///
823 /// # Arguments
824 ///
825 /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The additional data to send as a list of bodies.
826 ///
827 /// # Returns
828 ///
829 /// - `Result<(), ResponseError>` - The result of the send operation.
830 pub async fn try_send_body_list_with_data<I, D>(
831 &self,
832 data_iter: I,
833 ) -> Result<(), ResponseError>
834 where
835 I: IntoIterator<Item = D>,
836 D: AsRef<[u8]>,
837 {
838 if self.is_terminated() {
839 return Err(ResponseError::Terminated);
840 }
841 if let Some(stream) = self.try_get_stream() {
842 return stream.try_send_body_list(data_iter).await;
843 }
844 Err(ResponseError::NotFoundStream)
845 }
846
847 /// Sends a list of response bodies to the client with additional data.
848 ///
849 /// # Arguments
850 ///
851 /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The additional data to send as a list of bodies.
852 ///
853 /// # Panics
854 ///
855 /// Panics if any write operation fails.
856 pub async fn send_body_list_with_data<I, D>(&self, data_iter: I)
857 where
858 I: IntoIterator<Item = D>,
859 D: AsRef<[u8]>,
860 {
861 self.try_send_body_list_with_data(data_iter).await.unwrap()
862 }
863
864 /// Flushes the underlying network stream, ensuring all buffered data is sent.
865 ///
866 /// # Returns
867 ///
868 /// - `Result<(), ResponseError>` - The result of the flush operation.
869 pub async fn try_flush(&self) -> Result<(), ResponseError> {
870 if self.is_terminated() {
871 return Err(ResponseError::Terminated);
872 }
873 if let Some(stream) = self.try_get_stream() {
874 return stream.try_flush().await;
875 }
876 Err(ResponseError::NotFoundStream)
877 }
878
879 /// Flushes all buffered data to the stream.
880 ///
881 /// # Panics
882 ///
883 /// Panics if the flush operation fails.
884 pub async fn flush(&self) {
885 self.try_flush().await.unwrap();
886 }
887}