diff --git a/src/cmd_base58.rs b/src/cmd_base58.rs index 82afca6..7dd442e 100644 --- a/src/cmd_base58.rs +++ b/src/cmd_base58.rs @@ -1,14 +1,39 @@ -use clap::Args; -use rust_util::XResult; +use std::io::Write; +use base58::{FromBase58, ToBase58}; use crate::CmdExec; +use clap::Args; +use rust_util::{opt_result, simple_error, XResult}; +use crate::util::read_file_or_stdin; #[derive(Debug, Args)] pub struct CmdBase58 { - + /// Encode + #[arg(long, short = 'e')] + pub encode: bool, + /// Decode + #[arg(long, short = 'd')] + pub decode: bool, + /// Input file + #[arg(long, short = 'i')] + pub r#in: Option, } impl CmdExec for CmdBase58 { fn exec(&self) -> XResult<()> { - todo!() + if self.encode && self.decode { + return simple_error!("Encode and decode cannot both assigned."); + } + + let input = read_file_or_stdin(&self.r#in)?; + + if self.decode { + let s = opt_result!(String::from_utf8(input), "Decode UTF8 failed: {}"); + let decoded = opt_result!(s.from_base58(), "Decode base58 failed: {:?}"); + std::io::stdout().write_all(&decoded)?; + } else { + let encoded = input.to_base58(); + print!("{}", encoded); + } + Ok(()) } } \ No newline at end of file diff --git a/src/cmd_base64.rs b/src/cmd_base64.rs index 901e9b1..551ea90 100644 --- a/src/cmd_base64.rs +++ b/src/cmd_base64.rs @@ -1,12 +1,54 @@ +use crate::util::read_file_or_stdin; use crate::CmdExec; +use base64::engine::general_purpose::{ + STANDARD, STANDARD_NO_PAD, + URL_SAFE, URL_SAFE_NO_PAD, +}; +use base64::Engine; use clap::Args; -use rust_util::XResult; +use rust_util::{opt_result, simple_error, XResult}; +use std::io::Write; #[derive(Debug, Args)] -pub struct CmdBase64 {} +pub struct CmdBase64 { + /// Encode + #[arg(long, short = 'e')] + pub encode: bool, + /// Decode + #[arg(long, short = 'd')] + pub decode: bool, + /// URL Safe + #[arg(long, short = 'u')] + pub url_safe: bool, + /// No pad + #[arg(long, short = 'P')] + pub no_pad: bool, + /// Input file + #[arg(long, short = 'i')] + pub r#in: Option, +} impl CmdExec for CmdBase64 { fn exec(&self) -> XResult<()> { - todo!() + if self.encode && self.decode { + return simple_error!("Encode and decode cannot both assigned."); + } + + let input = read_file_or_stdin(&self.r#in)?; + let encoder = match (self.url_safe, self.no_pad) { + (false, false) => STANDARD, + (false, true) => STANDARD_NO_PAD, + (true, false) => URL_SAFE, + (true, true) => URL_SAFE_NO_PAD, + }; + + if self.decode { + let decoded = opt_result!(encoder.decode(&input), "Decode failed: {}"); + std::io::stdout().write_all(&decoded)?; + } else { + let encoded = encoder.encode(&input); + print!("{}", encoded); + } + Ok(()) } } \ No newline at end of file