| 1 |
#![allow(dead_code)] |
| 2 |
|
| 3 |
use std::io; |
| 4 |
use std::ops::{Deref, DerefMut}; |
| 5 |
|
| 6 |
use bytes::BytesMut; |
| 7 |
use sqlx_rt::{AsyncRead, AsyncReadExt, AsyncWrite}; |
| 8 |
|
| 9 |
use crate::error::Error; |
| 10 |
use crate::io::write_and_flush::WriteAndFlush; |
| 11 |
use crate::io::{decode::Decode, encode::Encode}; |
| 12 |
use std::io::Cursor; |
| 13 |
|
| 14 |
pub struct BufStream<S> |
| 15 |
where |
| 16 |
S: AsyncRead + AsyncWrite + Unpin, |
| 17 |
{ |
| 18 |
pub(crate) stream: S, |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
pub(crate) wbuf: Vec<u8>, |
| 23 |
|
| 24 |
|
| 25 |
rbuf: BytesMut, |
| 26 |
} |
| 27 |
|
| 28 |
impl<S> BufStream<S> |
| 29 |
where |
| 30 |
S: AsyncRead + AsyncWrite + Unpin, |
| 31 |
{ |
| 32 |
pub fn new(stream: S) -> Self { |
| 33 |
Self { |
| 34 |
stream, |
| 35 |
wbuf: Vec::with_capacity(512), |
| 36 |
rbuf: BytesMut::with_capacity(4096), |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
pub fn write<'en, T>(&mut self, value: T) |
| 41 |
where |
| 42 |
T: Encode<'en, ()>, |
| 43 |
{ |
| 44 |
self.write_with(value, ()) |
| 45 |
} |
| 46 |
|
| 47 |
pub fn write_with<'en, T, C>(&mut self, value: T, context: C) |
| 48 |
where |
| 49 |
T: Encode<'en, C>, |
| 50 |
{ |
| 51 |
value.encode_with(&mut self.wbuf, context); |
| 52 |
} |
| 53 |
|
| 54 |
pub fn flush(&mut self) -> WriteAndFlush<'_, S> { |
| 55 |
WriteAndFlush { |
| 56 |
stream: &mut self.stream, |
| 57 |
buf: Cursor::new(&mut self.wbuf), |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
pub async fn read<'de, T>(&mut self, cnt: usize) -> Result<T, Error> |
| 62 |
where |
| 63 |
T: Decode<'de, ()>, |
| 64 |
{ |
| 65 |
self.read_with(cnt, ()).await |
| 66 |
} |
| 67 |
|
| 68 |
pub async fn read_with<'de, T, C>(&mut self, cnt: usize, context: C) -> Result<T, Error> |
| 69 |
where |
| 70 |
T: Decode<'de, C>, |
| 71 |
{ |
| 72 |
T::decode_with(self.read_raw(cnt).await?.freeze(), context) |
| 73 |
} |
| 74 |
|
| 75 |
pub async fn read_raw(&mut self, cnt: usize) -> Result<BytesMut, Error> { |
| 76 |
read_raw_into(&mut self.stream, &mut self.rbuf, cnt).await?; |
| 77 |
let buf = self.rbuf.split_to(cnt); |
| 78 |
|
| 79 |
Ok(buf) |
| 80 |
} |
| 81 |
|
| 82 |
pub async fn read_raw_into(&mut self, buf: &mut BytesMut, cnt: usize) -> Result<(), Error> { |
| 83 |
read_raw_into(&mut self.stream, buf, cnt).await |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl<S> Deref for BufStream<S> |
| 88 |
where |
| 89 |
S: AsyncRead + AsyncWrite + Unpin, |
| 90 |
{ |
| 91 |
type Target = S; |
| 92 |
|
| 93 |
fn deref(&self) -> &Self::Target { |
| 94 |
&self.stream |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
impl<S> DerefMut for BufStream<S> |
| 99 |
where |
| 100 |
S: AsyncRead + AsyncWrite + Unpin, |
| 101 |
{ |
| 102 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 103 |
&mut self.stream |
| 104 |
} |
| 105 |
} |