#stdio #pipe #stdout #stdin #command-line #broken-pipe

std_io_iterators

An iterator for STDIN and a wrapper for STDOUT. Allows easy piping, and graceful closing of application if pipe breaks

1 stable release

1.0.0 Nov 25, 2022

#1426 in Rust patterns

MIT license

23KB
277 lines

std_io_iterators

An iterator for STDIN and a wrapper for STDOUT. Allows easy piping, and graceful closing of application if pipe breaks

Project by SnS Development

Problem

Using STDIN and STDOUT (piping in or piping out) is more complicated than is necessary. The developer should be able to obtain an iterator for the data being piped in through STDIN, and should be able to easily pipe out through STDOUT any iterator of elements implementing the std::fmt::Debug trait.

Also, if the STDOUT pipe is "broken" (i.e. the data being piped into exits), the iterator being piped out through STDOUT should be recoverable so the data can be re-directed. (See Warning in prelude::PipeOut::pipe_out)

Solution

  • A struct prelude::PipeInIterator - An [Iterator] that abstracts the process of piping in through STDIN
  • A trait prelude::PipeOut - Implemented on any [Iterator] over elements that implement std::fmt::Debug (like [String]) that abstracts the process of piping out through STDOUT

Example

use std_io_iterators::prelude::*;

fn main() -> Result<(), std::io::Error> {
    // Pipe in, lazy transform, pipe out
    match PipeInIterator::try_new()
        .expect("1669235203 - Unable to lock STDIN")
        .map(INTERNAL_FUNCTION)
        .pipe_out()
    {
        Err(e) if e.is_broken_pipe() => {
            // Log Broken Pipe
            return Ok(());
        }
        Err(e) => return e.dump_data().into(),
        _ => (),
    }

    // Pipe out array, re-direct additional data
    if let Err(mut e) = (["test1", "test2", "test3"].iter()).pipe_out() {
        e.by_ref()
            .for_each(|_recovered_datum| todo!("Handle recovered data"));
        return e.result.into();
    }

    Ok(())
}

const INTERNAL_FUNCTION: fn(std::rc::Rc<String>) -> String =
    |line| format!("Prepend-{}", line);

How To: Update Documentation

The documentation in this project is contained in the documentation comments throughout the code. Such comments are then compiled into the final documentation for the project via rustdoc when the code is published.

It is good practice to include a README.md file in root folder of the source code for displaying in the respective version management system. In compliance with DRY principle:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system

and in-order to keep the file from getting out-of-sync with the documentation, I simply duplicate the root page of the documentation via the enclosed script.

update_documentation.sh Run in the root of project

# Update CargoDocs from source code
cargo doc

# Update README.md from source code
cargo readme > README.md

License: MIT

No runtime deps