rust-postgres/postgres/src/copy_out_reader.rs

56 lines
1.5 KiB
Rust
Raw Normal View History

use crate::connection::ConnectionRef;
2019-12-16 01:01:53 +00:00
use crate::lazy_pin::LazyPin;
2018-12-29 05:01:10 +00:00
use bytes::{Buf, Bytes};
use futures::StreamExt;
2019-12-16 01:01:53 +00:00
use std::io::{self, BufRead, Read};
use tokio_postgres::CopyOutStream;
2018-12-29 05:01:10 +00:00
2019-03-31 03:58:01 +00:00
/// The reader returned by the `copy_out` method.
pub struct CopyOutReader<'a> {
pub(crate) connection: ConnectionRef<'a>,
2019-12-16 01:01:53 +00:00
pub(crate) stream: LazyPin<CopyOutStream>,
cur: Bytes,
2018-12-29 05:01:10 +00:00
}
impl<'a> CopyOutReader<'a> {
pub(crate) fn new(connection: ConnectionRef<'a>, stream: CopyOutStream) -> CopyOutReader<'a> {
2019-12-16 01:01:53 +00:00
CopyOutReader {
connection,
2019-12-16 01:01:53 +00:00
stream: LazyPin::new(stream),
cur: Bytes::new(),
}
2018-12-29 05:01:10 +00:00
}
}
impl Read for CopyOutReader<'_> {
2018-12-29 05:01:10 +00:00
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let b = self.fill_buf()?;
let len = usize::min(buf.len(), b.len());
buf[..len].copy_from_slice(&b[..len]);
self.consume(len);
Ok(len)
}
}
impl BufRead for CopyOutReader<'_> {
2018-12-29 05:01:10 +00:00
fn fill_buf(&mut self) -> io::Result<&[u8]> {
while !self.cur.has_remaining() {
let mut stream = self.stream.pinned();
match self
.connection
2020-06-10 23:54:07 +00:00
.block_on(async { stream.next().await.transpose() })
{
Ok(Some(cur)) => self.cur = cur,
Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
Ok(None) => break,
2018-12-29 05:01:10 +00:00
};
}
2020-12-24 02:03:15 +00:00
Ok(&self.cur)
2018-12-29 05:01:10 +00:00
}
fn consume(&mut self, amt: usize) {
self.cur.advance(amt);
}
}