grapple_utils/base_x.rs
1use data_encoding::Encoding;
2
3/// Encodes data into a BaseX string using the specified encoding method.
4///
5/// # Parameters
6/// - `content`: The data to be encoded. Can be any type that implements `AsRef<[u8]>`.
7/// - `encoding`: The BaseX encoding method to be used.
8///
9/// # Returns
10/// A string representing the encoded data.
11pub fn encode(content: impl AsRef<[u8]>, encoding: Encoding) -> String {
12 encoding.encode(content.as_ref())
13}
14
15/// Decodes a BaseX string into a vector of bytes using the specified decoding method.
16///
17/// # Parameters
18/// - `value`: A string containing the encoded BaseX data.
19/// - `encoding`: The BaseX decoding method to be used.
20///
21/// # Returns
22/// A result containing a vector of bytes if decoding is successful, or an error.
23pub fn decode(value: &str, encoding: Encoding) -> Result<Vec<u8>> {
24 encoding
25 .decode(value.as_bytes())
26 .map_err(|_| Error::DecodeError(value.to_string()))
27}
28
29/// Decodes a BaseX string into a string using the specified decoding method.
30///
31/// # Parameters
32/// - `value`: A string containing the encoded BaseX data.
33/// - `encoding`: The BaseX decoding method to be used.
34///
35/// # Returns
36/// A result containing a string if decoding is successful and the data is valid UTF-8, or an error.
37pub fn decode_to_string(value: &str, encoding: Encoding) -> Result<String> {
38 let decoded = decode(value, encoding)?;
39 String::from_utf8(decoded).map_err(|_| Error::InvalidUtf8)
40}
41
42// region: --- Error
43
44pub type Result<T> = core::result::Result<T, Error>;
45
46#[derive(Debug)]
47pub enum Error {
48 DecodeError(String),
49 InvalidUtf8,
50}
51
52// region: --- Error Boilerplate
53
54impl core::fmt::Display for Error {
55 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
56 match self {
57 Error::DecodeError(b64) => write!(fmt, "Failed to decode string: {}", b64),
58 Error::InvalidUtf8 => write!(fmt, "Decoded bytes are not valid UTF-8"),
59 }
60 }
61}
62
63impl std::error::Error for Error {}
64// endregion: --- Error Boilerplate
65
66// endregion: --- Error