Skip to content

Commit a0ecb15

Browse files
committed
auto merge of #11652 : hdima/rust/base64-padding-newlines, r=alexcrichton
Ignore all newline characters in Base64 decoder to make it compatible with other Base64 decoders. Most of the Base64 decoder implementations ignore all newline characters in the input string. There are some examples: Python: ```python >>> " A Q = = ".decode("base64") '\x01' ``` Ruby: ```ruby irb(main):001:0> " A Q = = ".unpack("m") => ["�"] ``` Erlang: ```erlang 1> base64:decode(" A Q = = "). <<1>> ``` Moreover some Base64 encoders append newline character at the end of the output string by default: Python: ```python >>> "�".encode("base64") 'AQ== ' ``` Ruby: ```ruby irb(main):001:0> ["�"].pack("m") => "AQ== " ``` So I think it's fairly important for Rust Base64 decoder to accept Base64 inputs even with newline characters in the padding.
2 parents 764f2cb + 99cde84 commit a0ecb15

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/libextra/base64.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,9 @@ impl<'a> FromBase64 for &'a str {
237237
}
238238

239239
for (idx, byte) in it {
240-
if (byte as char) != '=' {
241-
return Err(InvalidBase64Character(self.char_at(idx), idx));
240+
match byte as char {
241+
'='|'\r'|'\n' => continue,
242+
_ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
242243
}
243244
}
244245

@@ -310,6 +311,8 @@ mod test {
310311
fn test_from_base64_newlines() {
311312
assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
312313
"foobar".as_bytes().to_owned());
314+
assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(),
315+
"foob".as_bytes().to_owned());
313316
}
314317

315318
#[test]

0 commit comments

Comments
 (0)