use crate::*;
impl ArcRwLockStream {
pub fn from(arc_rw_lock_stream: ArcRwLock<TcpStream>) -> Self {
Self(arc_rw_lock_stream)
}
pub fn from_stream(stream: TcpStream) -> Self {
Self(Arc::new(RwLock::new(stream)))
}
pub async fn read(&self) -> ArcRwLockReadGuard<'_, TcpStream> {
self.0.read().await
}
pub async fn write(&self) -> ArcRwLockWriteGuard<'_, TcpStream> {
self.0.write().await
}
pub async fn try_send<D>(&self, data: D) -> ResponseResult
where
D: AsRef<[u8]>,
{
let mut stream: ArcRwLockWriteGuard<'_, TcpStream> = self.write().await;
stream
.write_all(data.as_ref())
.await
.map_err(|e| ResponseError::WriteError(e.to_string()))?;
Ok(())
}
pub async fn send<D>(&self, data: D)
where
D: AsRef<[u8]>,
{
self.try_send(data).await.unwrap();
}
pub async fn try_flush(&self) -> ResponseResult {
let mut stream: ArcRwLockWriteGuard<'_, TcpStream> = self.write().await;
stream
.flush()
.await
.map_err(|e| ResponseError::FlushError(e.to_string()))?;
Ok(())
}
pub async fn flush(&self) {
self.try_flush().await.unwrap();
}
pub async fn try_get_peer_addr(&self) -> OptionSocketAddr {
let stream: ArcRwLockReadGuard<'_, TcpStream> = self.read().await;
stream.peer_addr().ok()
}
pub async fn get_peer_addr(&self) -> SocketAddr {
self.try_get_peer_addr().await.unwrap()
}
pub async fn try_shutdown(&self) -> ResponseResult {
let mut stream: ArcRwLockWriteGuard<'_, TcpStream> = self.write().await;
stream
.shutdown()
.await
.map_err(|e| ResponseError::WriteError(e.to_string()))?;
Ok(())
}
pub async fn shutdown(&self) {
self.try_shutdown().await.unwrap();
}
}
impl From<TcpStream> for ArcRwLockStream {
fn from(stream: TcpStream) -> Self {
Self::from_stream(stream)
}
}