use std::{
    io,
    pin::Pin,
    task::{Context, Poll},
};

use futures_util::ready;

use crate::io::Stream as InnerStream;

/// How many zeroed bytes the first read of a call gets, and the most one
/// read gets: the window doubles while reads fill it.
const FIRST_READ_STEP: usize = 8 * 1024;
const MAX_READ_STEP: usize = 256 * 1024;

struct Guard<'a> {
    buf: &'a mut Vec<u8>,
    len: usize,
}

impl Drop for Guard<'_> {
    fn drop(&mut self) {
        self.buf.truncate(self.len);
    }
}

pub(crate) fn read_to_end(
    mut rd: Pin<&mut InnerStream>,
    cx: &mut Context<'_>,
    buf: &mut Vec<u8>,
) -> Poll<io::Result<usize>> {
    let start_len = buf.len();
    let mut g = Guard {
        len: buf.len(),
        buf,
    };
    let ret;
    let mut step = FIRST_READ_STEP;
    loop {
        if g.len == g.buf.len() {
            // The reader is given initialised memory: a window of zeroed bytes
            // past the data. The guard cuts the buffer back to what was read,
            // so a poll that finds nothing zeroes only the first window, not
            // the whole capacity left by the largest reply so far.
            g.buf.reserve(step);
            g.buf.resize(g.len + step, 0);
            step = (step * 2).min(MAX_READ_STEP);
        }

        match ready!(rd.as_mut().poll_read(cx, &mut g.buf[g.len..])) {
            Ok(0) => {
                ret = Poll::Ready(Ok(g.len - start_len));
                break;
            }
            Ok(n) => g.len += n,
            Err(e) => {
                ret = Poll::Ready(Err(e));
                break;
            }
        }
    }

    ret
}