Skip to main content

InterruptReader

Struct InterruptReader 

Source
pub struct InterruptReader<R> { /* private fields */ }
Expand description

An interruptable, buffered Reader.

This reader is created by wrapping a Read struct in the interrupt_read::pair function, which also returns an Interruptor, which is capable of sending interrupt signals, which make any read operations on the InterruptReader return an error of kind ErrorKind::Other, with a payload of InterruptReceived.

When an interrupt is received, the underlying data is not lost, it still exists, and if you call a reading function again, it will be retrieved, unless another interrupt is sent before that.

You can check if an std::io::Error is of this type by calling the is_interrupt function.

§Examples

One potential application of this struct is if you want to stop a thread that is reading from the stdout of a child process without necessarily terminating said childrop_:

use std::{
    io::{BufRead, ErrorKind},
    process::{Child, Command, Stdio},
    time::Duration,
};

use interrupt_read::{is_interrupt, pair};

struct ChildKiller(Child);
impl Drop for ChildKiller {
    fn drop(&mut self) {
        _ = self.0.kill();
    }
}

// Prints "hello\n" every second forever.
let mut child = Command::new("bash")
    .args(["-c", r#"while true; do echo "hello"; sleep 1; done"#])
    .stdout(Stdio::piped())
    .spawn()
    .unwrap();

let (mut stdout, interruptor) = pair(child.stdout.take().unwrap());
let _child_killer = ChildKiller(child);

let join_handle = std::thread::spawn(move || {
    let mut string = String::new();
    loop {
        match stdout.read_line(&mut string) {
            Ok(0) => break Ok(string),
            Ok(_) => {}
            Err(err) if is_interrupt(&err) => {
                break Ok(string);
            }
            Err(err) => break Err(err),
        }
    }
});

std::thread::sleep(Duration::new(3, 1_000_000));

interruptor.interrupt()?;

let result = join_handle.join().unwrap()?;

assert_eq!(result, "hello\nhello\nhello\n");

Ok(())

Implementations§

Source§

impl<R: Read> InterruptReader<R>

Source

pub fn into_inner(self) -> Result<R>

Unwraps this InterruptReader, returning the underlying reader.

Note that any leftover data in the internal buffer is lost. Therefore, a following read from the underlying reader may lead to data loss.

This may return Err if the underlying joined thread has panicked, probably because the Reader has done so.

Trait Implementations§

Source§

impl<R: Read> BufRead for InterruptReader<R>

Source§

fn fill_buf(&mut self) -> Result<&[u8]>

Returns the contents of the internal buffer, filling it with more data, via Read methods, if empty. Read more
Source§

fn consume(&mut self, amount: usize)

Marks the given amount of additional bytes from the internal buffer as having been read. Subsequent calls to read only return bytes that have not been marked as read. Read more
Source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if there is any data left to be read. Read more
1.0.0 · Source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
1.83.0 · Source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · Source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
1.0.0 · Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · Source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
Source§

impl<R: Debug> Debug for InterruptReader<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: Read> Read for InterruptReader<R>

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
where Self: Sized,

🔬This is a nightly-only experimental API. (read_array)
Read and return a fixed array of bytes from this source. Read more

Auto Trait Implementations§

§

impl<R> Freeze for InterruptReader<R>

§

impl<R> !RefUnwindSafe for InterruptReader<R>

§

impl<R> Send for InterruptReader<R>

§

impl<R> !Sync for InterruptReader<R>

§

impl<R> Unpin for InterruptReader<R>

§

impl<R> UnsafeUnpin for InterruptReader<R>

§

impl<R> !UnwindSafe for InterruptReader<R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.