Debian Codegraph @

third_party/rust/ron/examples/base64.rs

raw
1 //! ron initially encoded byte-slices and byte-bufs as base64-encoded strings.
2 //! However, since v0.9, ron now uses Rusty byte string literals instead.
3 //!
4 //! This example shows how the previous behaviour can be restored by serialising
5 //! bytes with strongly-typed base64-encoded strings, or accepting both Rusty
6 //! byte strings and the legacy base64-encoded string syntax.
7
8 use base64::engine::{general_purpose::STANDARD as BASE64, Engine};
9 use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
10
11 #[derive(Debug, PartialEq, Serialize, Deserialize)]
12 struct Config {
13 #[serde(with = "ByteStr")]
14 bytes: Vec<u8>,
15 #[serde(with = "Base64")]
16 base64: Vec<u8>,
17 #[serde(with = "ByteStrOrBase64")]
18 bytes_or_base64: Vec<u8>,
19 }
20
21 enum ByteStr {}
22
23 impl ByteStr {
24 fn serialize<S: Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
25 serializer.serialize_bytes(data)
26 }
27
28 fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
29 struct ByteStrVisitor;
30
31 impl<'de> Visitor<'de> for ByteStrVisitor {
32 type Value = Vec<u8>;
33
34 fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
35 fmt.write_str("a Rusty byte string")
36 }
37
38 fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
39 Ok(bytes.to_vec())
40 }
41
42 fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
43 Ok(bytes)
44 }
45 }
46
47 deserializer.deserialize_byte_buf(ByteStrVisitor)
48 }
49 }
50
51 enum Base64 {}
52
53 impl Base64 {
54 fn serialize<S: Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
55 serializer.serialize_str(&BASE64.encode(data))
56 }
57
58 fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
59 let base64_str = <&str>::deserialize(deserializer)?;
60 BASE64.decode(base64_str).map_err(serde::de::Error::custom)
61 }
62 }
63
64 enum ByteStrOrBase64 {}
65
66 impl ByteStrOrBase64 {
67 fn serialize<S: Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
68 if cfg!(all()) {
69 // either of these would work
70 serializer.serialize_str(&BASE64.encode(data))
71 } else {
72 serializer.serialize_bytes(data)
73 }
74 }
75
76 fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
77 struct ByteStrOrBase64Visitor;
78
79 impl<'de> Visitor<'de> for ByteStrOrBase64Visitor {
80 type Value = Vec<u8>;
81
82 fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
83 fmt.write_str("a Rusty byte string or a base64-encoded string")
84 }
85
86 fn visit_str<E: serde::de::Error>(self, base64_str: &str) -> Result<Self::Value, E> {
87 BASE64.decode(base64_str).map_err(serde::de::Error::custom)
88 }
89
90 fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
91 Ok(bytes.to_vec())
92 }
93
94 fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
95 Ok(bytes)
96 }
97 }
98
99 deserializer.deserialize_any(ByteStrOrBase64Visitor)
100 }
101 }
102
103 fn main() {
104 let ron = r#"Config(
105 bytes: b"only byte strings are allowed",
106 base64: "b25seSBiYXNlNjQtZW5jb2RlZCBzdHJpbmdzIGFyZSBhbGxvd2Vk",
107 bytes_or_base64: b"both byte strings and base64-encoded strings work",
108 )"#;
109
110 assert_eq!(
111 ron::from_str::<Config>(ron).unwrap(),
112 Config {
113 bytes: b"only byte strings are allowed".to_vec(),
114 base64: b"only base64-encoded strings are allowed".to_vec(),
115 bytes_or_base64: b"both byte strings and base64-encoded strings work".to_vec()
116 }
117 );
118
119 let ron = r#"Config(
120 bytes: b"only byte strings are allowed",
121 base64: "b25seSBiYXNlNjQtZW5jb2RlZCBzdHJpbmdzIGFyZSBhbGxvd2Vk",
122 bytes_or_base64: "Ym90aCBieXRlIHN0cmluZ3MgYW5kIGJhc2U2NC1lbmNvZGVkIHN0cmluZ3Mgd29yaw==",
123 )"#;
124
125 assert_eq!(
126 ron::from_str::<Config>(ron).unwrap(),
127 Config {
128 bytes: b"only byte strings are allowed".to_vec(),
129 base64: b"only base64-encoded strings are allowed".to_vec(),
130 bytes_or_base64: b"both byte strings and base64-encoded strings work".to_vec()
131 }
132 );
133
134 println!(
135 "{}",
136 ron::ser::to_string_pretty(
137 &Config {
138 bytes: b"only byte strings are allowed".to_vec(),
139 base64: b"only base64-encoded strings are allowed".to_vec(),
140 bytes_or_base64: b"both byte strings and base64-encoded strings work".to_vec()
141 },
142 ron::ser::PrettyConfig::default().struct_names(true)
143 )
144 .unwrap()
145 );
146 }