Enum patharg::InputArg

source ·
pub enum InputArg {
    Stdin,
    Path(PathBuf),
}
Expand description

An input path that can refer to either standard input or a file system path

Variants§

§

Stdin

Refers to standard input.

This is the variant returned by InputArg::default().

§

Path(PathBuf)

Refers to a file system path (stored in .0)

Implementations§

source§

impl InputArg

source

pub fn from_arg<S: Into<PathBuf>>(arg: S) -> InputArg

Construct an InputArg from a string, usually one taken from command-line arguments. If the string equals "-" (i.e., it contains only a single hyphen/dash), InputArg::Stdin is returned; otherwise, an InputArg::Path is returned.

Example
use patharg::InputArg;
use std::path::PathBuf;

let p1 = InputArg::from_arg("-");
assert_eq!(p1, InputArg::Stdin);

let p2 = InputArg::from_arg("./-");
assert_eq!(p2, InputArg::Path(PathBuf::from("./-")));
source

pub fn is_stdin(&self) -> bool

Returns true if the input arg is the Stdin variant of InputArg.

Example
use patharg::InputArg;

let p1 = InputArg::from_arg("-");
assert!(p1.is_stdin());

let p2 = InputArg::from_arg("file.txt");
assert!(!p2.is_stdin());
source

pub fn is_path(&self) -> bool

Returns true if the input arg is the Path variant of InputArg.

Example
use patharg::InputArg;

let p1 = InputArg::from_arg("-");
assert!(!p1.is_path());

let p2 = InputArg::from_arg("file.txt");
assert!(p2.is_path());
source

pub fn path_ref(&self) -> Option<&PathBuf>

Retrieve a reference to the inner PathBuf. If the input arg is the Stdin variant, this returns None.

Example
use patharg::InputArg;
use std::path::PathBuf;

let p1 = InputArg::from_arg("-");
assert_eq!(p1.path_ref(), None);

let p2 = InputArg::from_arg("file.txt");
assert_eq!(p2.path_ref(), Some(&PathBuf::from("file.txt")));
source

pub fn path_mut(&mut self) -> Option<&mut PathBuf>

Retrieve a mutable reference to the inner PathBuf. If the input arg is the Stdin variant, this returns None.

Example
use patharg::InputArg;
use std::path::PathBuf;

let mut p1 = InputArg::from_arg("-");
assert_eq!(p1.path_mut(), None);

let mut p2 = InputArg::from_arg("file.txt");
assert_eq!(p2.path_mut(), Some(&mut PathBuf::from("file.txt")));
source

pub fn into_path(self) -> Option<PathBuf>

Consume the input arg and return the inner PathBuf. If the input arg is the Stdin variant, this returns None.

Example
use patharg::InputArg;
use std::path::PathBuf;

let p1 = InputArg::from_arg("-");
assert_eq!(p1.into_path(), None);

let p2 = InputArg::from_arg("file.txt");
assert_eq!(p2.into_path(), Some(PathBuf::from("file.txt")));
source

pub fn open(&self) -> Result<InputArgReader>

Open the input arg for reading.

If the input arg is the Stdin variant, this returns a locked reference to stdin. Otherwise, if the path arg is a Path variant, the given path is opened for reading.

The returned reader implements std::io::BufRead.

Errors

Has the same error conditions as std::fs::File::open.

Example
use patharg::InputArg;
use std::env::args_os;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let mut f = infile.open()?;
    let mut buffer = [0; 16];
    let n = f.read(&mut buffer)?;
    println!("First {} bytes: {:?}", n, &buffer[..n]);
    Ok(())
}
source

pub fn read(&self) -> Result<Vec<u8>>

Read the entire contents of the input arg into a bytes vector.

If the input arg is the Stdin variant, the entire contents of stdin are read. Otherwise, if the input arg is a Path variant, the contents of the given path are read.

Errors

Has the same error conditions as std::io::Read::read_to_end and std::fs::read.

Example
use patharg::InputArg;
use std::env::args_os;
use std::io;

fn main() -> io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let input = infile.read()?;
    println!("Read {} bytes from input", input.len());
    Ok(())
}
source

pub fn read_to_string(&self) -> Result<String>

Read the entire contents of the input arg into a string.

If the input arg is the Stdin variant, the entire contents of stdin are read. Otherwise, if the input arg is a Path variant, the contents of the given path are read.

Errors

Has the same error conditions as std::io::read_to_string and std::fs::read_to_string.

Example
use patharg::InputArg;
use std::env::args_os;
use std::io;

fn main() -> io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let input = infile.read_to_string()?;
    println!("Read {} characters from input", input.len());
    Ok(())
}
source

pub fn lines(&self) -> Result<Lines>

Return an iterator over the lines of the input arg.

If the input arg is the Stdin variant, this locks stdin and returns an iterator over its lines; the lock is released once the iterator is dropped. Otherwise, if the input arg is a Path variant, the given path is opened for reading, and an iterator over its lines is returned.

The returned iterator yields instances of std::io::Result<String>, where each individual item has the same error conditions as std::io::BufRead::read_line().

Errors

Has the same error conditions as InputArg::open().

Example
use patharg::InputArg;
use std::env::args_os;
use std::io;

fn main() -> io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    for (i, r) in infile.lines()?.enumerate() {
        let line = r?;
        println!("Line {} is {} characters long.", i + 1, line.len());
    }
    Ok(())
}
source§

impl InputArg

source

pub async fn async_open(&self) -> Result<AsyncInputArgReader>

Available on crate feature tokio only.

Asynchronously open the input arg for reading.

If the input arg is the Stdin variant, this returns a reference to stdin. Otherwise, if the path arg is a Path variant, the given path is opened for reading.

The returned reader implements tokio::io::AsyncRead.

Errors

Has the same error conditions as tokio::fs::File::open.

Example
use patharg::InputArg;
use std::env::args_os;
use tokio::io::AsyncReadExt;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let mut f = infile.async_open().await?;
    let mut buffer = [0; 16];
    let n = f.read(&mut buffer).await?;
    println!("First {} bytes: {:?}", n, &buffer[..n]);
    Ok(())
}
source

pub async fn async_read(&self) -> Result<Vec<u8>>

Available on crate feature tokio only.

Asynchronously read the entire contents of the input arg into a bytes vector.

If the input arg is the Stdin variant, the entire contents of stdin are read. Otherwise, if the input arg is a Path variant, the contents of the given path are read.

Errors

Has the same error conditions as tokio::io::AsyncReadExt::read_to_end and tokio::fs::read.

Example
use patharg::InputArg;
use std::env::args_os;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let input = infile.async_read().await?;
    println!("Read {} bytes from input", input.len());
    Ok(())
}
source

pub async fn async_read_to_string(&self) -> Result<String>

Available on crate feature tokio only.

Asynchronously read the entire contents of the input arg into a string.

If the input arg is the Stdin variant, the entire contents of stdin are read. Otherwise, if the input arg is a Path variant, the contents of the given path are read.

Errors

Has the same error conditions as tokio::io::AsyncReadExt::read_to_string and tokio::fs::read_to_string.

Example
use patharg::InputArg;
use std::env::args_os;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let input = infile.async_read_to_string().await?;
    println!("Read {} characters from input", input.len());
    Ok(())
}
source

pub async fn async_lines(&self) -> Result<AsyncLines>

Available on crate feature tokio only.

Return a stream over the lines of the input arg.

If the input arg is the Stdin variant, this returns a stream over the lines of stdin. Otherwise, if the input arg is a Path variant, the given path is opened for reading, and a stream over its lines is returned.

The returned stream yields instances of std::io::Result<String>, where each individual item has the same error conditions as tokio::io::AsyncBufReadExt::read_line().

Errors

Has the same error conditions as InputArg::async_open().

Example
use patharg::InputArg;
use std::env::args_os;
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let infile = args_os().nth(1)
                          .map(InputArg::from_arg)
                          .unwrap_or_default();
    let mut i = 1;
    let mut stream = infile.async_lines().await?;
    while let Some(r) = stream.next().await {
        let line = r?;
        println!("Line {} is {} characters long.", i, line.len());
        i += 1;
    }
    Ok(())
}

Trait Implementations§

source§

impl Clone for InputArg

source§

fn clone(&self) -> InputArg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for InputArg

source§

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

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

impl Default for InputArg

source§

fn default() -> InputArg

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for InputArg

Available on crate feature serde only.
source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,

Deserializes a string and converts it to an InputArg with InputArg::from_arg().

source§

impl Display for InputArg

source§

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

Displays InputArg::Stdin as - (a single hyphen/dash) or as <stdin> if the {:#} format is used. Always displays InputArg::Path using std::path::Path::display().

source§

impl From<InputArg> for OsString

source§

fn from(arg: InputArg) -> OsString

Converts an input arg back to an OsString: InputArg::Stdin becomes "-", and InputArg::Path(p) becomes p.into().

source§

impl<S: Into<PathBuf>> From<S> for InputArg

source§

fn from(s: S) -> InputArg

Convert a string to a InputArg using InputArg::from_arg().

source§

impl Hash for InputArg

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for InputArg

source§

fn cmp(&self, other: &InputArg) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<InputArg> for InputArg

source§

fn eq(&self, other: &InputArg) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<InputArg> for InputArg

source§

fn partial_cmp(&self, other: &InputArg) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for InputArg

Available on crate feature serde only.
source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serializes InputArg::Stdin as "-" (a string containing a single hyphen/dash). Serializes InputArg::Path as the inner PathBuf; this will fail if the path is not valid UTF-8.

source§

impl Eq for InputArg

source§

impl StructuralEq for InputArg

source§

impl StructuralPartialEq for InputArg

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

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

§

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 Twhere U: TryFrom<T>,

§

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.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,