1
1
use std:: borrow:: Cow ;
2
2
use std:: str:: { from_utf8, FromStr , Utf8Error } ;
3
3
4
+ use base64:: Engine ;
4
5
use pyo3:: prelude:: * ;
5
6
use pyo3:: types:: { PyDelta , PyDict } ;
6
7
use pyo3:: { intern, PyNativeType } ;
@@ -119,20 +120,21 @@ impl TimedeltaMode {
119
120
}
120
121
121
122
#[ derive( Default , Debug , Clone ) ]
122
- pub ( crate ) struct BytesMode {
123
- base64_config : Option < base64:: Config > ,
123
+ pub ( crate ) enum BytesMode {
124
+ #[ default]
125
+ Utf8 ,
126
+ Base64 ,
124
127
}
125
128
126
129
impl FromStr for BytesMode {
127
130
type Err = PyErr ;
128
131
129
132
fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
130
- let base64_config = match s {
131
- "utf8" => None ,
132
- "base64" => Some ( base64:: Config :: new ( base64:: CharacterSet :: UrlSafe , true ) ) ,
133
- s => return py_schema_err ! ( "Invalid bytes serialization mode: `{}`, expected `utf8` or `base64`" , s) ,
134
- } ;
135
- Ok ( Self { base64_config } )
133
+ match s {
134
+ "utf8" => Ok ( Self :: Utf8 ) ,
135
+ "base64" => Ok ( Self :: Base64 ) ,
136
+ s => py_schema_err ! ( "Invalid bytes serialization mode: `{}`, expected `utf8` or `base64`" , s) ,
137
+ }
136
138
}
137
139
}
138
140
@@ -146,23 +148,21 @@ impl BytesMode {
146
148
}
147
149
148
150
pub fn bytes_to_string < ' py > ( & self , py : Python , bytes : & ' py [ u8 ] ) -> PyResult < Cow < ' py , str > > {
149
- if let Some ( config) = self . base64_config {
150
- Ok ( Cow :: Owned ( base64:: encode_config ( bytes, config) ) )
151
- } else {
152
- from_utf8 ( bytes)
151
+ match self {
152
+ Self :: Utf8 => from_utf8 ( bytes)
153
153
. map_err ( |err| utf8_py_error ( py, err, bytes) )
154
- . map ( Cow :: Borrowed )
154
+ . map ( Cow :: Borrowed ) ,
155
+ Self :: Base64 => Ok ( Cow :: Owned ( base64:: engine:: general_purpose:: URL_SAFE . encode ( bytes) ) ) ,
155
156
}
156
157
}
157
158
158
159
pub fn serialize_bytes < S : serde:: ser:: Serializer > ( & self , bytes : & [ u8 ] , serializer : S ) -> Result < S :: Ok , S :: Error > {
159
- if let Some ( config) = self . base64_config {
160
- serializer. serialize_str ( & base64:: encode_config ( bytes, config) )
161
- } else {
162
- match from_utf8 ( bytes) {
160
+ match self {
161
+ Self :: Utf8 => match from_utf8 ( bytes) {
163
162
Ok ( s) => serializer. serialize_str ( s) ,
164
163
Err ( e) => Err ( Error :: custom ( e. to_string ( ) ) ) ,
165
- }
164
+ } ,
165
+ Self :: Base64 => serializer. serialize_str ( & base64:: engine:: general_purpose:: URL_SAFE . encode ( bytes) ) ,
166
166
}
167
167
}
168
168
}
0 commit comments