http_type/stream/impl.rs
1use crate::*;
2
3impl ArcRwLockStream {
4 /// Creates a new ArcRwLockStream from an Arc<RwLock<TcpStream>>.
5 ///
6 /// # Arguments
7 ///
8 /// - `Arc<RwLock<TcpStream>>` - The stream to wrap.
9 ///
10 /// # Returns
11 ///
12 /// - `ArcRwLockStream` - The new stream wrapper.
13 pub fn from(arc_rw_lock_stream: ArcRwLock<TcpStream>) -> Self {
14 Self(arc_rw_lock_stream)
15 }
16
17 /// Creates a new ArcRwLockStream from a TcpStream.
18 ///
19 /// Wraps the stream in an Arc<RwLock<_>>.
20 ///
21 /// # Arguments
22 ///
23 /// - `TcpStream` - The raw stream to wrap.
24 ///
25 /// # Returns
26 ///
27 /// - `ArcRwLockStream` - The new thread-safe stream wrapper.
28 pub fn from_stream(stream: TcpStream) -> Self {
29 Self(arc_rwlock(stream))
30 }
31
32 /// Gets a read lock on the inner TcpStream.
33 ///
34 /// Allows shared read access to the stream.
35 ///
36 /// # Returns
37 ///
38 /// - `RwLockReadGuardTcpStream` - The read guard for the stream.
39 pub async fn read(&self) -> RwLockReadGuardTcpStream {
40 self.get_0().read().await
41 }
42
43 /// Gets a write lock on the inner TcpStream.
44 ///
45 /// Allows exclusive write access to the stream.
46 ///
47 /// # Returns
48 ///
49 /// - `RwLockWriteGuardTcpStream` - The write guard for the stream.
50 pub(crate) async fn write(&self) -> RwLockWriteGuardTcpStream {
51 self.get_0().write().await
52 }
53
54 /// Sends HTTP response data over the stream.
55 ///
56 /// # Arguments
57 ///
58 /// - `ResponseData` - The response data to send.
59 ///
60 /// # Returns
61 ///
62 /// - `ResponseResult` - Result indicating success or failure.
63 pub async fn send(&self, data: ResponseData) -> ResponseResult {
64 self.write()
65 .await
66 .write_all(&data)
67 .await
68 .map_err(|err| ResponseError::Response(err.to_string()))?;
69 Ok(())
70 }
71
72 /// Sends HTTP response body (non-WebSocket).
73 ///
74 /// # Arguments
75 ///
76 /// - `&ResponseBody` - The response body data.
77 ///
78 /// # Returns
79 ///
80 /// - `ResponseResult` - Result indicating success or failure.
81 pub async fn send_body(&self, body: ResponseBody) -> ResponseResult {
82 self.write()
83 .await
84 .write_all(&body)
85 .await
86 .map_err(|err| ResponseError::Response(err.to_string()))?;
87 Ok(())
88 }
89
90 /// Flushes all buffered data to the stream.
91 ///
92 /// # Returns
93 ///
94 /// - `&Self` - Reference to self for method chaining.
95 pub async fn flush(&self) -> &Self {
96 let _ = self.write().await.flush();
97 self
98 }
99}