Skip to content

Commit

Permalink
Add test to show that #436 is solved with strongly typed base64 user-…
Browse files Browse the repository at this point in the history
…side types
  • Loading branch information
juntyr committed Sep 1, 2023
1 parent 9d96262 commit a073fe4
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tests/436_untagged_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,49 @@ fn test_bytes() {

assert_eq!(s, r#"(b:b"test")"#);
}

#[test]
fn test_strongly_typed_base64() {
use base64::engine::{general_purpose::STANDARD as BASE64, Engine};

enum Base64 {}

impl Base64 {
fn serialize<S: serde::Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&BASE64.encode(data))
}

fn deserialize<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Vec<u8>, D::Error> {
let base64_str: &str = serde::Deserialize::deserialize(deserializer)?;
BASE64.decode(base64_str).map_err(serde::de::Error::custom)
}
}

#[derive(Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename = "b")]
struct BytesVal {
#[serde(with = "Base64")]
pub b: Vec<u8>,
}

#[derive(Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
enum Bad {
Bytes(BytesVal),
}

let v: Bad = ron::from_str(r#"(b: "dGVzdA==")"#).unwrap();

assert_eq!(
v,
Bad::Bytes(BytesVal {
b: b"test".to_vec()
})
);

let s = ron::to_string(&v).unwrap();

assert_eq!(s, r#"(b:"dGVzdA==")"#);
}

0 comments on commit a073fe4

Please sign in to comment.