Enum patharg::OutputArg

source ·
pub enum OutputArg {
    Stdout,
    Path(PathBuf),
}
Expand description

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

Variants§

§

Stdout

Refers to standard output.

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

§

Path(PathBuf)

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

Implementations§

source§

impl OutputArg

source

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

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

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

let p1 = OutputArg::from_arg("-");
assert_eq!(p1, OutputArg::Stdout);

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

pub fn is_stdout(&self) -> bool

Returns true if the output arg is the Stdout variant of OutputArg.

Example
use patharg::OutputArg;

let p1 = OutputArg::from_arg("-");
assert!(p1.is_stdout());

let p2 = OutputArg::from_arg("file.txt");
assert!(!p2.is_stdout());
source

pub fn is_path(&self) -> bool

Returns true if the output arg is the Path variant of OutputArg.

Example
use patharg::OutputArg;

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

let p2 = OutputArg::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 output arg is the Stdout variant, this returns None.

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

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

let p2 = OutputArg::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 output arg is the Stdout variant, this returns None.

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

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

let mut p2 = OutputArg::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 output arg and return the inner PathBuf. If the output arg is the Stdout variant, this returns None.

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

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

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

pub fn create(&self) -> Result<OutputArgWriter>

Open the output arg for writing.

If the output arg is the Stdout variant, this returns a locked reference to stdout. Otherwise, if the output arg is a Path variant, the given path is opened for writing; if the path does not exist, it is created.

The returned writer implements std::io::Write.

Errors

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

Example
use patharg::OutputArg;
use std::env::args_os;
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let outfile = args_os().nth(1)
                           .map(OutputArg::from_arg)
                           .unwrap_or_default();
    let mut f = outfile.create()?;
    // The "{}" is replaced by either the output filepath or a hyphen.
    write!(&mut f, "I am writing to {}.", outfile)?;
    Ok(())
}
source

pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> Result<()>

Write a slice as the entire contents of the output arg.

If the output arg is the Stdout variant, the given data is written to stdout. Otherwise, if the output arg is a Path variant, the contents of the given path are replaced with the given data; if the path does not exist, it is created first.

Errors

Has the same error conditions as std::io::Write::write_all and std::fs::write.

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

fn main() -> io::Result<()> {
    let outfile = args_os().nth(1)
                           .map(OutputArg::from_arg)
                           .unwrap_or_default();
    outfile.write("This is the output arg's new content.\n")?;
    Ok(())
}
source§

impl OutputArg

source

pub async fn async_create(&self) -> Result<AsyncOutputArgWriter>

Available on crate feature tokio only.

Asynchronously open the output arg for writing.

If the output arg is the Stdout variant, this returns a reference to stdout. Otherwise, if the output arg is a Path variant, the given path is opened for writing; if the path does not exist, it is created.

The returned writer implements tokio::io::AsyncWrite.

Errors

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

Example
use patharg::OutputArg;
use std::env::args_os;
use tokio::io::AsyncWriteExt;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let outfile = args_os().nth(1)
                           .map(OutputArg::from_arg)
                           .unwrap_or_default();
    let mut f = outfile.async_create().await?;
    // The "{}" is replaced by either the output filepath or a hyphen.
    let msg = format!("I am writing to {}.\n", outfile);
    f.write_all(msg.as_ref()).await?;
    Ok(())
}
source

pub async fn async_write<C: AsRef<[u8]>>(&self, contents: C) -> Result<()>

Available on crate feature tokio only.

Asynchronously write a slice as the entire contents of the output arg.

If the output arg is the Stdout variant, the given data is written to stdout. Otherwise, if the output arg is a Path variant, the contents of the given path are replaced with the given data; if the path does not exist, it is created first.

Errors

Has the same error conditions as tokio::io::AsyncWriteExt::write_all and tokio::fs::write.

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

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let outfile = args_os().nth(1)
                           .map(OutputArg::from_arg)
                           .unwrap_or_default();
    outfile.async_write("This is the output arg's new content.\n").await?;
    Ok(())
}

Trait Implementations§

source§

impl Clone for OutputArg

source§

fn clone(&self) -> OutputArg

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 OutputArg

source§

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

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

impl Default for OutputArg

source§

fn default() -> OutputArg

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

impl<'de> Deserialize<'de> for OutputArg

Available on crate feature serde only.
source§

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

Deserializes a PathBuf and converts it to an OutputArg with OutputArg::from_arg().

source§

impl Display for OutputArg

source§

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

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

source§

impl From<OutputArg> for OsString

source§

fn from(arg: OutputArg) -> OsString

Convert an OutputArg back to an OsString: OutputArg::Stdout becomes "-", and OutputArg::Path(p) becomes p.into().

source§

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

source§

fn from(s: S) -> OutputArg

Convert an string to an OutputArg using OutputArg::from_arg().

source§

impl FromStr for OutputArg

source§

fn from_str(s: &str) -> Result<OutputArg, Self::Err>

Convert a string to an OutputArg using OutputArg::from_arg().

§

type Err = Infallible

The associated error which can be returned from parsing.
source§

impl Hash for OutputArg

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 OutputArg

source§

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

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

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

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

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

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

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

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

impl PartialEq for OutputArg

source§

fn eq(&self, other: &OutputArg) -> 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 for OutputArg

source§

fn partial_cmp(&self, other: &OutputArg) -> 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 OutputArg

Available on crate feature serde only.
source§

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

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

source§

impl Eq for OutputArg

source§

impl StructuralEq for OutputArg

source§

impl StructuralPartialEq for OutputArg

Auto Trait Implementations§

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> ToOwned for T
where 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 T
where 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 T
where 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 T
where 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 T
where T: for<'de> Deserialize<'de>,