Debian Codegraph @

src/io/write_and_flush.rs

raw symbols SCIP
1 use crate::error::Error;
2 use futures_core::Future;
3 use futures_util::ready;
4 use sqlx_rt::AsyncWrite;
5 use std::io::{BufRead, Cursor};
6 use std::pin::Pin;
7 use std::task::{Context, Poll};
8
9 // Atomic operation that writes the full buffer to the stream, flushes the stream, and then
10 // clears the buffer (even if either of the two previous operations failed).
11 pub struct WriteAndFlush<'a, S> {
12 pub(super) stream: &'a mut S,
13 pub(super) buf: Cursor<&'a mut Vec<u8>>,
14 }
15
16 impl<S: AsyncWrite + Unpin> Future for WriteAndFlush<'_, S> {
17 type Output = Result<(), Error>;
18
19 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
20 let Self {
21 ref mut stream,
22 ref mut buf,
23 } = *self;
24
25 loop {
26 let read = buf.fill_buf()?;
27
28 if !read.is_empty() {
29 let written = ready!(Pin::new(&mut *stream).poll_write(cx, read)?);
30 buf.consume(written);
31 } else {
32 break;
33 }
34 }
35
36 Pin::new(stream).poll_flush(cx).map_err(Error::Io)
37 }
38 }
39
40 impl<'a, S> Drop for WriteAndFlush<'a, S> {
41 fn drop(&mut self) {
42 // clear the buffer regardless of whether the flush succeeded or not
43 self.buf.get_mut().clear();
44 }
45 }