about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2014-01-19 22:31:42 -0800
committerbors <bors@rust-lang.org>2014-01-19 22:31:42 -0800
commita0ecb154110d397aa241ee95da89b3a35ff6e503 (patch)
treeaa2067f832194f282d275f867a4d1d8dc9137c02
parent764f2cb6f3517869e31fc7b93ff11dd840db8d30 (diff)
parent99cde8482efaed4757422d24cd46de8fa64c92cb (diff)
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.
-rw-r--r--src/libextra/base64.rs7
1 files changed, 5 insertions, 2 deletions
diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs
index 6f9475d091a..1043f700aa7 100644
--- a/src/libextra/base64.rs
+++ b/src/libextra/base64.rs
@@ -237,8 +237,9 @@ impl<'a> FromBase64 for &'a str {
         }
 
         for (idx, byte) in it {
-            if (byte as char) != '=' {
-                return Err(InvalidBase64Character(self.char_at(idx), idx));
+            match byte as char {
+                '='|'\r'|'\n' => continue,
+                _ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
             }
         }
 
@@ -310,6 +311,8 @@ mod test {
     fn test_from_base64_newlines() {
         assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
                    "foobar".as_bytes().to_owned());
+        assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(),
+                   "foob".as_bytes().to_owned());
     }
 
     #[test]