feat(serialize):基本完成Hex和Base64的编解码。
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
use base64::Engine;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum HexSerializeError {
|
||||
#[error("Invalid hex char: {0}")]
|
||||
InvalidHexChar(#[from] hex::FromHexError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Base64SerializeError {
|
||||
#[error("Cannot encode Base64 slice: {0}")]
|
||||
EncodeFailed(#[from] base64::EncodeSliceError),
|
||||
#[error("Cannot decode Base64 string: {0}")]
|
||||
DecodeFailed(#[from] base64::DecodeError),
|
||||
}
|
||||
|
||||
/// 将指定可以转换为字节数组的内容以十六进制字符串的形式输出。
|
||||
pub fn to_hex<T: AsRef<[u8]>>(input: T) -> String {
|
||||
hex::encode(input)
|
||||
}
|
||||
|
||||
/// 将十六进制字符串转换为字节数组,如果字符串中存在非十六进制字符,则返回错误。
|
||||
pub fn from_hex(input: &str) -> Result<Vec<u8>, HexSerializeError> {
|
||||
hex::decode(input).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
/// 将给定的可以转换为字节数组的内容以Base64编码的字符串形式输出。
|
||||
pub fn to_base64_str<T: AsRef<[u8]>>(input: T) -> String {
|
||||
base64::prelude::BASE64_STANDARD.encode(input)
|
||||
}
|
||||
|
||||
/// 将给定的可以转换为字节数组的内容以Base64编码的字节数组形式输出。
|
||||
pub fn to_base64_vec<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, Base64SerializeError> {
|
||||
let mut buf = Vec::new();
|
||||
base64::prelude::BASE64_STANDARD
|
||||
.encode_slice(input.as_ref(), &mut buf)
|
||||
.map_err(|e| Base64SerializeError::EncodeFailed(e))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// 将给定的Base64编码的字符串转换为字节数组,如果字符串中存在不能被识别的内容,则返回错误。
|
||||
pub fn from_base64_str(input: &str) -> Result<Vec<u8>, Base64SerializeError> {
|
||||
base64::prelude::BASE64_STANDARD
|
||||
.decode(input)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
/// 将给定的Base64编码的字节数组转换为原始字节数组,如果字节数组中存在不能被识别转换的内容,则返回错误。
|
||||
pub fn from_base64_vec<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, Base64SerializeError> {
|
||||
let mut buf = Vec::new();
|
||||
base64::prelude::BASE64_STANDARD
|
||||
.decode_vec(input.as_ref(), &mut buf)
|
||||
.map_err(|e| Base64SerializeError::DecodeFailed(e))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user