1use base64::Engine;
2use base64::engine::general_purpose::STANDARD as BASE64;
3use hex;
4use urlencoding;
5use html_escape;
6use teaql_tool_core::{Result, TeaQLToolError};
7
8pub struct CodecTool;
9
10impl CodecTool {
11 pub fn new() -> Self {
12 Self
13 }
14
15 pub fn base64_encode<T: AsRef<[u8]>>(&self, data: T) -> String {
16 BASE64.encode(data)
17 }
18
19 pub fn base64_decode(&self, data: &str) -> Result<Vec<u8>> {
20 BASE64.decode(data).map_err(|e| TeaQLToolError::ParseError(e.to_string()))
21 }
22
23 pub fn hex_encode<T: AsRef<[u8]>>(&self, data: T) -> String {
24 hex::encode(data)
25 }
26
27 pub fn hex_decode(&self, data: &str) -> Result<Vec<u8>> {
28 hex::decode(data).map_err(|e| TeaQLToolError::ParseError(e.to_string()))
29 }
30
31 pub fn url_encode(&self, data: &str) -> String {
32 urlencoding::encode(data).into_owned()
33 }
34
35 pub fn url_decode(&self, data: &str) -> Result<String> {
36 urlencoding::decode(data)
37 .map(|cow| cow.into_owned())
38 .map_err(|e| TeaQLToolError::ParseError(e.to_string()))
39 }
40
41 pub fn html_escape(&self, data: &str) -> String {
42 html_escape::encode_text(data).into_owned()
43 }
44
45 pub fn html_unescape(&self, data: &str) -> String {
46 html_escape::decode_html_entities(data).into_owned()
47 }
48}
49
50impl Default for CodecTool {
51 fn default() -> Self {
52 Self::new()
53 }
54}