Skip to main content

x402_types/util/
b64.rs

1//! Base64 encoding and decoding utilities.
2//!
3//! This module provides [`Base64Bytes`], a wrapper type for working with
4//! base64-encoded data in the x402 protocol.
5
6use base64::Engine;
7use base64::engine::general_purpose::STANDARD as b64;
8use std::borrow::Cow;
9use std::fmt::Display;
10
11/// A wrapper for base64-encoded byte data.
12///
13/// This type holds bytes that represent base64-encoded data and provides
14/// methods for encoding and decoding. It uses copy-on-write semantics
15/// to avoid unnecessary allocations.
16///
17/// # Example
18///
19/// ```rust
20/// use x402_types::util::Base64Bytes;
21///
22/// // Encode some data
23/// let encoded = Base64Bytes::encode(b"hello world");
24/// assert_eq!(encoded.to_string(), "aGVsbG8gd29ybGQ=");
25///
26/// // Decode it back
27/// let decoded = encoded.decode().unwrap();
28/// assert_eq!(decoded, b"hello world");
29/// ```
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Base64Bytes<'a>(pub Cow<'a, [u8]>);
32
33impl Base64Bytes<'_> {
34    /// Decodes the base64 string bytes to raw binary data.
35    ///
36    /// # Errors
37    ///
38    /// Returns an error if the data is not valid base64.
39    pub fn decode(&self) -> Result<Vec<u8>, base64::DecodeError> {
40        b64.decode(&self.0)
41    }
42
43    /// Encodes raw binary data into base64 string bytes.
44    pub fn encode<T: AsRef<[u8]>>(input: T) -> Base64Bytes<'static> {
45        let encoded = b64.encode(input.as_ref());
46        Base64Bytes(Cow::Owned(encoded.into_bytes()))
47    }
48}
49
50impl AsRef<[u8]> for Base64Bytes<'_> {
51    fn as_ref(&self) -> &[u8] {
52        self.0.as_ref()
53    }
54}
55
56impl<'a> From<&'a [u8]> for Base64Bytes<'a> {
57    fn from(slice: &'a [u8]) -> Self {
58        Base64Bytes(Cow::Borrowed(slice))
59    }
60}
61
62impl Display for Base64Bytes<'_> {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(f, "{}", String::from_utf8_lossy(self.0.as_ref()))
65    }
66}