Skip to content

Commit 2966488

Browse files
committed
Avoid some allocs
1 parent e8a5303 commit 2966488

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

src/validators/config.rs

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,31 @@ impl ValBytesMode {
2828
pub fn deserialize_string<'py>(self, s: &str) -> Result<EitherBytes<'_, 'py>, ErrorType> {
2929
match self.ser {
3030
BytesMode::Utf8 => Ok(EitherBytes::Cow(Cow::Borrowed(s.as_bytes()))),
31-
BytesMode::Base64 => match base64::engine::general_purpose::URL_SAFE.decode(to_base64_urlsafe(s)) {
32-
Ok(bytes) => Ok(EitherBytes::from(bytes)),
33-
Err(err) => Err(ErrorType::BytesInvalidEncoding {
34-
encoding: "base64".to_string(),
35-
encoding_error: err.to_string(),
36-
context: None,
37-
}),
38-
},
31+
BytesMode::Base64 => {
32+
fn decode(input: &str) -> Result<Vec<u8>, ErrorType> {
33+
base64::engine::general_purpose::URL_SAFE.decode(input).map_err(|err| {
34+
ErrorType::BytesInvalidEncoding {
35+
encoding: "base64".to_string(),
36+
encoding_error: err.to_string(),
37+
context: None,
38+
}
39+
})
40+
}
41+
let result = if s.contains(|c| c == '+' || c == '/') {
42+
let replaced: String = s
43+
.chars()
44+
.map(|c| match c {
45+
'+' => '-',
46+
'/' => '_',
47+
_ => c,
48+
})
49+
.collect();
50+
decode(&replaced)
51+
} else {
52+
decode(s)
53+
};
54+
result.map(EitherBytes::from)
55+
}
3956
BytesMode::Hex => match hex::decode(s) {
4057
Ok(vec) => Ok(EitherBytes::from(vec)),
4158
Err(err) => Err(ErrorType::BytesInvalidEncoding {
@@ -47,11 +64,3 @@ impl ValBytesMode {
4764
}
4865
}
4966
}
50-
51-
fn to_base64_urlsafe(s: &str) -> String {
52-
if s.contains(|c| c == '+' || c == '/') {
53-
s.replace('+', "-").replace('/', "_")
54-
} else {
55-
s.to_string()
56-
}
57-
}

0 commit comments

Comments
 (0)