From 72f25a8b033c09f201d00b13f0472ec0772ed85e Mon Sep 17 00:00:00 2001 From: Lyra Naeseth Date: Sun, 3 Dec 2023 16:12:48 -0800 Subject: [PATCH] Simplify the example program --- Cargo.toml | 1 + examples/base64.rs | 42 +++++++++++++++++------------------------- 2 files changed, 18 insertions(+), 25 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 36b0778..1ca4364 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ rustdoc-args = ["--generate-link-to-definition"] criterion = "0.4.0" rand = { version = "0.8.5", features = ["small_rng"] } structopt = "0.3.26" +strum = { version = "0.25", features = ["derive"] } # test fixtures for engine tests rstest = "0.13.0" rstest_reuse = "0.6.0" diff --git a/examples/base64.rs b/examples/base64.rs index 0a214d2..5c82061 100644 --- a/examples/base64.rs +++ b/examples/base64.rs @@ -2,46 +2,35 @@ use std::fs::File; use std::io::{self, Read}; use std::path::PathBuf; use std::process; -use std::str::FromStr; use base64::{alphabet, engine, read, write}; use structopt::StructOpt; -#[derive(Debug, StructOpt)] +#[derive(StructOpt, strum::EnumString, Default, Debug)] +#[strum(serialize_all = "kebab-case")] enum Alphabet { + #[default] Standard, UrlSafe, } -impl Default for Alphabet { - fn default() -> Self { - Self::Standard - } -} - -impl FromStr for Alphabet { - type Err = String; - fn from_str(s: &str) -> Result { - match s { - "standard" => Ok(Self::Standard), - "urlsafe" => Ok(Self::UrlSafe), - _ => Err(format!("alphabet '{}' unrecognized", s)), - } - } -} - /// Base64 encode or decode FILE (or standard input), to standard output. #[derive(Debug, StructOpt)] struct Opt { - /// decode data + /// Decode the base64-encoded input (default: encode the input as base64). #[structopt(short = "d", long = "decode")] decode: bool, - /// The alphabet to choose. Defaults to the standard base64 alphabet. - /// Supported alphabets include "standard" and "urlsafe". + + /// The encoding alphabet: "standard" (default) or "url-safe". #[structopt(long = "alphabet")] alphabet: Option, - /// The file to encode/decode. - #[structopt(parse(from_os_str))] + + /// Omit padding characters while encoding, and reject them while decoding. + #[structopt(short = "p")] + no_padding: bool, + + /// The file to encode or decode. + #[structopt(name = "FILE", parse(from_os_str))] file: Option, } @@ -66,7 +55,10 @@ fn main() { Alphabet::Standard => alphabet::STANDARD, Alphabet::UrlSafe => alphabet::URL_SAFE, }, - engine::general_purpose::PAD, + match opt.no_padding { + true => engine::general_purpose::NO_PAD, + false => engine::general_purpose::PAD, + }, ); let stdout = io::stdout();