1use std::sync::Arc;
2
3use derive_more::{Deref, DerefMut, From, Into};
4use either::Either;
5use rquickjs::{Ctx, Result, TypedArray};
6use tokio::{
7 io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
8 sync::RwLock,
9};
10
11#[derive(Clone, From, Into, Deref, DerefMut)]
12pub struct AsyncReadWrapper(pub Arc<RwLock<dyn AsyncRead + Unpin>>);
13
14impl AsyncReadWrapper {
15 pub async fn read_to_end(self) -> Result<Vec<u8>> {
16 let mut buf = vec![];
17 let mut write = self.write().await;
18 write.read_to_end(&mut buf).await?;
19 Ok(buf)
20 }
21
22 pub async fn read_to_string(self) -> Result<String> {
23 let mut str = String::new();
24 let mut write = self.write().await;
25 write.read_to_string(&mut str).await?;
26 Ok(str)
27 }
28
29 pub async fn read<'js>(self, bytes: usize, ctx: Ctx<'js>) -> Result<TypedArray<'js, u8>> {
30 let mut buf = vec![0; bytes];
31 let mut write = self.write().await;
32 write.read(&mut buf).await?;
33 TypedArray::new(ctx, buf)
34 }
35}
36
37#[derive(Clone, From, Into, Deref, DerefMut)]
38pub struct AsyncWriteWrapper(pub Arc<RwLock<dyn AsyncWrite + Unpin>>);
39
40impl AsyncWriteWrapper {
41 pub async fn write_all<'js>(
42 self,
43 buf: Either<String, Either<Vec<u8>, TypedArray<'js, u8>>>,
44 ) -> Result<()> {
45 let buf = match buf {
46 Either::Left(ref x) => x.as_bytes(),
47 Either::Right(Either::Left(ref x)) => x.as_slice(),
48 Either::Right(Either::Right(ref x)) => x.as_bytes().unwrap(),
49 };
50 let mut write = self.write().await;
51 write.write_all(buf).await?;
52 Ok(())
53 }
54
55 pub async fn flush(self) -> Result<()> {
56 let mut write = self.write().await;
57 write.flush().await?;
58 Ok(())
59 }
60
61 pub async fn shutdown(self) -> Result<()> {
62 let mut write = self.write().await;
63 write.shutdown().await?;
64 Ok(())
65 }
66}