1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
extern crate hex;
extern crate regex;
extern crate buffer;
extern crate num_bigint;
use std::str;
use self::num_bigint::{BigInt, Sign};
pub fn encode_string(s: String) -> String {
return add_prefix(hex::encode(s).to_lowercase());
}
pub fn decode_string(hex_str: String) -> Vec<u8> {
return hex::decode(strip_prefix(hex_str)).unwrap();
}
pub fn encode_to_string(buf: Vec<u8>) -> String {
let bufstr = match str::from_utf8(&buf) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
return add_prefix(hex::encode(bufstr)).to_lowercase();
}
pub fn decode_to_string(buf: Vec<u8>) -> String {
let decoded = hex::decode(buf).unwrap();
let bufstr = match str::from_utf8(&decoded) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
return bufstr.to_string();
}
pub fn encode_bytes(src: Vec<u8>) -> Vec<u8> {
return strip_prefix(encode_to_string(src)).to_owned().into_bytes()
}
pub fn decode_bytes(src: Vec<u8>) -> Vec<u8> {
let bufstr = match str::from_utf8(&src) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
return hex::decode(bufstr).unwrap();
}
pub fn encode_big_int(bn: BigInt) -> Vec<u8> {
let _ = bn;
return vec![0];
}
pub fn decode_big_int(hex_str: String) -> BigInt {
let _ = hex_str;
return BigInt::new(Sign::Plus, vec![0]);
}
pub fn strip_prefix(s: String) -> String {
let re = regex::Regex::new(r"^0x").unwrap();
return re.replace_all(&s, "").to_string();
}
pub fn add_prefix(s: String) -> String {
return format!("0x{}", strip_prefix(s));
}