use std::cell::Cell;
use std::io::{self, Read, Seek, SeekFrom};
#[derive(Default)]
pub(crate) struct Latch(Cell<Option<io::Error>>);
impl Latch {
pub(crate) fn take(&self) -> Option<io::Error> {
self.0.take()
}
fn record(&self, err: io::Error) -> io::Error {
let stand_in = io::Error::new(err.kind(), "the reader failed");
let first = self.0.take();
self.0.set(Some(first.unwrap_or(err)));
stand_in
}
}
pub(crate) struct Latched<'a, R> {
inner: R,
latch: &'a Latch,
}
impl<'a, R> Latched<'a, R> {
pub(crate) fn new(inner: R, latch: &'a Latch) -> Self {
Self { inner, latch }
}
}
impl<R: Read> Read for Latched<'_, R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf).map_err(|e| self.latch.record(e))
}
}
impl<R: Seek> Seek for Latched<'_, R> {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.inner.seek(pos).map_err(|e| self.latch.record(e))
}
}