Skip to content

Commit

Permalink
Simplify the example program
Browse files Browse the repository at this point in the history
  • Loading branch information
silverlyra committed Dec 4, 2023
1 parent 40e162c commit 72f25a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 25 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
42 changes: 17 additions & 25 deletions examples/base64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, String> {
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<Alphabet>,
/// 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<PathBuf>,
}

Expand All @@ -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();
Expand Down

0 comments on commit 72f25a8

Please sign in to comment.