waves_rust/model/
base64string.rs1use crate::error::Result;
2use crate::model::ByteString;
3use std::fmt;
4
5#[derive(Eq, PartialEq, Clone, Hash)]
6pub struct Base64String {
7 bytes: Vec<u8>,
8}
9
10impl fmt::Debug for Base64String {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 write!(f, "Base64String {{ {} }}", self.encoded())
13 }
14}
15
16impl Base64String {
17 pub fn from_bytes(bytes: Vec<u8>) -> Base64String {
18 Base64String { bytes }
19 }
20
21 pub fn from_string(encoded: &str) -> Result<Base64String> {
22 let base64str = if encoded.starts_with("base64:") {
23 encoded.replace("base64:", "")
24 } else {
25 encoded.to_owned()
26 };
27 Ok(Base64String {
28 bytes: base64::decode(base64str)?,
29 })
30 }
31
32 pub fn empty() -> Base64String {
33 Base64String { bytes: vec![] }
34 }
35}
36
37impl ByteString for Base64String {
38 fn bytes(&self) -> Vec<u8> {
39 self.bytes.clone()
40 }
41
42 fn encoded(&self) -> String {
43 base64::encode(&self.bytes)
44 }
45
46 fn encoded_with_prefix(&self) -> String {
47 format!("base64:{}", base64::encode(&self.bytes))
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use crate::model::{Base64String, ByteString};
54
55 #[test]
56 fn base64string_test() {
57 let binary_value: [u8; 12] = [0; 12];
58 let base64string = Base64String::from_bytes(binary_value.to_vec());
59 assert_eq!("AAAAAAAAAAAAAAAA", base64string.encoded())
60 }
61}