Skip to content

Commit 60d8460

Browse files
committed
cli: read data from stdin if no '-i' argument is given
This is especially useful for binary data, which may not survive in an argument list (e.g. due to the presence of NUL bytes). The 'encode' and 'decode' commands are now exact inverses of each other, so data will roundtrip correctly, e.g. $ echo "hello world" | ./multibase encode | ./multibase decode hello world $ echo "hello world" | ./multibase encode | ./multibase decode | ./multibase encode z2yGEbwRFyhPZZckJm $ echo "hello world" | ./multibase encode z2yGEbwRFyhPZZckJm
1 parent 73bdfb1 commit 60d8460

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

cli/main.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,42 @@ enum Mode {
2020
/// The base to use for encoding.
2121
#[structopt(short = "b", long = "base", default_value = "base58btc")]
2222
base: StrBase,
23-
/// The data need to be encoded.
23+
/// The data to encode. Reads from stdin if not provided.
2424
#[structopt(short = "i", long = "input")]
25-
input: String,
25+
input: Option<String>,
2626
},
2727
#[structopt(name = "decode")]
2828
Decode {
29-
/// The data need to be decoded.
29+
/// The data to decode. Reads from stdin if not provided.
3030
#[structopt(short = "i", long = "input")]
31-
input: String,
31+
input: Option<String>,
3232
},
3333
}
3434

3535
fn main() -> Result<()> {
3636
env_logger::init();
3737
let opts = Opts::from_args();
3838
match opts.mode {
39-
Mode::Encode { base, input } => encode(base, input.as_bytes()),
40-
Mode::Decode { input } => decode(&input),
39+
Mode::Encode { base, input } => {
40+
let input_bytes = if let Some(s) = input {
41+
s.into_bytes()
42+
} else {
43+
let mut buf = Vec::new();
44+
io::stdin().read_to_end(&mut buf)?;
45+
buf
46+
};
47+
encode(base, &input_bytes)
48+
}
49+
Mode::Decode { input } => {
50+
let input_str = if let Some(s) = input {
51+
s
52+
} else {
53+
let mut buf = String::new();
54+
io::stdin().read_to_string(&mut buf)?;
55+
buf
56+
};
57+
decode(&input_str)
58+
}
4159
}
4260
}
4361

0 commit comments

Comments
 (0)