konv/src/main.rs
src/main.rsRaw
1use clap::App;
2
3use termion::{color, style};
4
5extern crate base64;
6extern crate hex;
7extern crate num_bigint;
8extern crate num_traits;
9use num_bigint::{BigInt, Sign};
10
11fn main() {
12 let matches = App::new("myapp")
13 .version("0.0.1")
14 .about("Convert between string formats.\nhttps://github.com/arnaucube/konv")
15 .arg("<INPUT> 'Value to parse'")
16 .arg("-b 'Read input in BigEndian (by default uses LittleEndian)'")
17 .get_matches();
18
19 let inp = matches.value_of("INPUT").unwrap();
20
21 println!("input {}", inp);
22
23 let r: BigInt;
24 if inp.starts_with("0x") {
25 r = d_hex(inp, matches.is_present("b"));
26 } else {
27 r = d_dec(inp, matches.is_present("b"));
28 }
29
30 // print decimal
31 println!(
32 " dec {}{}{}",
33 color::Fg(color::Yellow),
34 r.to_string(),
35 style::Reset
36 );
37
38 // print hexadecimal
39 println!(
40 " hex {}{}{}",
41 color::Fg(color::Blue),
42 r.to_str_radix(16),
43 style::Reset
44 );
45
46 // print base64
47 let (_, byt) = r.to_bytes_be();
48 let b64 = base64::encode(&byt);
49 println!(" b64 {}{}{}", color::Fg(color::Cyan), b64, style::Reset);
50
51 // print bytes
52 let mut byte_str: String = byt[0].to_string();
53 for x in byt.iter().skip(1) {
54 byte_str = format!("{}, {}", byte_str, x);
55 }
56 println!(" byt [{}]", byte_str);
57}
58
59fn d_hex(raw_inp: &str, bigendian: bool) -> BigInt {
60 let inp;
61 if raw_inp.starts_with("0x") {
62 inp = raw_inp.trim_start_matches("0x");
63 } else {
64 inp = raw_inp;
65 }
66 let b = hex::decode(inp).expect("Decoding failed");
67 let bi: BigInt;
68 if bigendian {
69 bi = BigInt::from_bytes_be(Sign::Plus, &b);
70 } else {
71 bi = BigInt::from_bytes_le(Sign::Plus, &b);
72 }
73 bi
74}
75
76fn d_dec(inp: &str, bigendian: bool) -> BigInt {
77 let or = BigInt::parse_bytes(inp.as_bytes(), 10).unwrap();
78 let (_, b) = or.to_bytes_be();
79 if bigendian {
80 return BigInt::from_bytes_be(Sign::Plus, &b);
81 }
82 BigInt::from_bytes_le(Sign::Plus, &b)
83}