1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ignore-lexer-test FIXME #15679
13 //! Base64 binary-to-text encoding
15 pub use self::FromBase64Error::*;
16 pub use self::CharacterSet::*;
21 /// Available encoding character sets
23 pub enum CharacterSet {
24 /// The standard character set (uses `+` and `/`)
26 /// The URL safe character set (uses `-` and `_`)
30 /// Available newline types
33 /// A linefeed (i.e. Unix-style newline)
35 /// A carriage return and a linefeed (i.e. Windows-style newline)
39 /// Contains configuration parameters for `to_base64`.
42 /// Character set to use
43 pub char_set: CharacterSet,
46 /// True to pad output with `=` characters
48 /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping
49 pub line_length: Option<uint>
52 /// Configuration for RFC 4648 standard base64 encoding
53 pub static STANDARD: Config =
54 Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None};
56 /// Configuration for RFC 4648 base64url encoding
57 pub static URL_SAFE: Config =
58 Config {char_set: UrlSafe, newline: Newline::CRLF, pad: false, line_length: None};
60 /// Configuration for RFC 2045 MIME base64 encoding
61 pub static MIME: Config =
62 Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: Some(76)};
64 static STANDARD_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
65 abcdefghijklmnopqrstuvwxyz\
68 static URLSAFE_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
69 abcdefghijklmnopqrstuvwxyz\
72 /// A trait for converting a value to base64 encoding.
74 /// Converts the value of `self` to a base64 value following the specified
75 /// format configuration, returning the owned string.
76 fn to_base64(&self, config: Config) -> String;
79 impl ToBase64 for [u8] {
80 /// Turn a vector of `u8` bytes into a base64 string.
85 /// extern crate serialize;
86 /// use serialize::base64::{ToBase64, STANDARD};
89 /// let str = [52,32].to_base64(STANDARD);
90 /// println!("base 64 output: {}", str);
93 fn to_base64(&self, config: Config) -> String {
94 let bytes = match config.char_set {
95 Standard => STANDARD_CHARS,
96 UrlSafe => URLSAFE_CHARS
99 // In general, this Vec only needs (4/3) * self.len() memory, but
100 // addition is faster than multiplication and division.
101 let mut v = Vec::with_capacity(self.len() + self.len());
103 let mut cur_length = 0;
104 let len = self.len();
105 let mod_len = len % 3;
106 let cond_len = len - mod_len;
107 let newline = match config.newline {
108 Newline::LF => b"\n",
109 Newline::CRLF => b"\r\n"
112 let (first, second, third) = (self[i], self[i + 1], self[i + 2]);
113 if let Some(line_length) = config.line_length {
114 if cur_length >= line_length {
120 let n = (first as u32) << 16 |
121 (second as u32) << 8 |
124 // This 24-bit number gets separated into four 6-bit numbers.
125 v.push(bytes[((n >> 18) & 63) as uint]);
126 v.push(bytes[((n >> 12) & 63) as uint]);
127 v.push(bytes[((n >> 6 ) & 63) as uint]);
128 v.push(bytes[(n & 63) as uint]);
135 if let Some(line_length) = config.line_length {
136 if cur_length >= line_length {
142 // Heh, would be cool if we knew this was exhaustive
143 // (the dream of bounded integer types)
147 let n = (self[i] as u32) << 16;
148 v.push(bytes[((n >> 18) & 63) as uint]);
149 v.push(bytes[((n >> 12) & 63) as uint]);
156 let n = (self[i] as u32) << 16 |
157 (self[i + 1u] as u32) << 8;
158 v.push(bytes[((n >> 18) & 63) as uint]);
159 v.push(bytes[((n >> 12) & 63) as uint]);
160 v.push(bytes[((n >> 6 ) & 63) as uint]);
165 _ => panic!("Algebra is broken, please alert the math police")
168 unsafe { String::from_utf8_unchecked(v) }
172 /// A trait for converting from base64 encoded values.
173 pub trait FromBase64 {
174 /// Converts the value of `self`, interpreted as base64 encoded data, into
175 /// an owned vector of bytes, returning the vector.
176 fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>;
179 /// Errors that can occur when decoding a base64 encoded string
180 #[derive(Copy, Show)]
181 pub enum FromBase64Error {
182 /// The input contained a character not part of the base64 format
183 InvalidBase64Byte(u8, uint),
184 /// The input had an invalid length
188 impl fmt::Display for FromBase64Error {
189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191 InvalidBase64Byte(ch, idx) =>
192 write!(f, "Invalid character '{}' at position {}", ch, idx),
193 InvalidBase64Length => write!(f, "Invalid length"),
198 impl error::Error for FromBase64Error {
199 fn description(&self) -> &str {
201 InvalidBase64Byte(_, _) => "invalid character",
202 InvalidBase64Length => "invalid length",
207 impl FromBase64 for str {
208 /// Convert any base64 encoded string (literal, `@`, `&`, or `~`)
209 /// to the byte values it encodes.
211 /// You can use the `String::from_utf8` function to turn a `Vec<u8>` into a
212 /// string with characters corresponding to those values.
216 /// This converts a string literal to base64 and back.
219 /// extern crate serialize;
220 /// use serialize::base64::{ToBase64, FromBase64, STANDARD};
223 /// let hello_str = b"Hello, World".to_base64(STANDARD);
224 /// println!("base64 output: {}", hello_str);
225 /// let res = hello_str.as_slice().from_base64();
227 /// let opt_bytes = String::from_utf8(res.unwrap());
228 /// if opt_bytes.is_ok() {
229 /// println!("decoded from base64: {}", opt_bytes.unwrap());
235 fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
236 self.as_bytes().from_base64()
240 impl FromBase64 for [u8] {
241 fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
242 let mut r = Vec::with_capacity(self.len());
243 let mut buf: u32 = 0;
244 let mut modulus = 0i;
246 let mut it = self.iter().enumerate();
247 for (idx, &byte) in it {
248 let val = byte as u32;
251 b'A'...b'Z' => buf |= val - 0x41,
252 b'a'...b'z' => buf |= val - 0x47,
253 b'0'...b'9' => buf |= val + 0x04,
254 b'+' | b'-' => buf |= 0x3E,
255 b'/' | b'_' => buf |= 0x3F,
256 b'\r' | b'\n' => continue,
258 _ => return Err(InvalidBase64Byte(self[idx], idx)),
265 r.push((buf >> 22) as u8);
266 r.push((buf >> 14) as u8);
267 r.push((buf >> 6 ) as u8);
271 for (idx, &byte) in it {
273 b'=' | b'\r' | b'\n' => continue,
274 _ => return Err(InvalidBase64Byte(self[idx], idx)),
280 r.push((buf >> 10) as u8);
283 r.push((buf >> 16) as u8);
284 r.push((buf >> 8 ) as u8);
287 _ => return Err(InvalidBase64Length),
297 use self::test::Bencher;
298 use base64::{Config, Newline, FromBase64, ToBase64, STANDARD, URL_SAFE};
301 fn test_to_base64_basic() {
302 assert_eq!("".as_bytes().to_base64(STANDARD), "");
303 assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==");
304 assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=");
305 assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v");
306 assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==");
307 assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=");
308 assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy");
312 fn test_to_base64_crlf_line_break() {
313 assert!(![0u8; 1000].to_base64(Config {line_length: None, ..STANDARD})
315 assert_eq!(b"foobar".to_base64(Config {line_length: Some(4),
321 fn test_to_base64_lf_line_break() {
322 assert!(![0u8; 1000].to_base64(Config {line_length: None,
323 newline: Newline::LF,
327 assert_eq!(b"foobar".to_base64(Config {line_length: Some(4),
328 newline: Newline::LF,
334 fn test_to_base64_padding() {
335 assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg");
336 assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8");
340 fn test_to_base64_url_safe() {
341 assert_eq!([251, 255].to_base64(URL_SAFE), "-_8");
342 assert_eq!([251, 255].to_base64(STANDARD), "+/8=");
346 fn test_from_base64_basic() {
347 assert_eq!("".from_base64().unwrap(), b"");
348 assert_eq!("Zg==".from_base64().unwrap(), b"f");
349 assert_eq!("Zm8=".from_base64().unwrap(), b"fo");
350 assert_eq!("Zm9v".from_base64().unwrap(), b"foo");
351 assert_eq!("Zm9vYg==".from_base64().unwrap(), b"foob");
352 assert_eq!("Zm9vYmE=".from_base64().unwrap(), b"fooba");
353 assert_eq!("Zm9vYmFy".from_base64().unwrap(), b"foobar");
357 fn test_from_base64_bytes() {
358 assert_eq!(b"Zm9vYmFy".from_base64().unwrap(), b"foobar");
362 fn test_from_base64_newlines() {
363 assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
365 assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(),
367 assert_eq!("Zm9v\nYmFy".from_base64().unwrap(),
369 assert_eq!("Zm9vYg==\n".from_base64().unwrap(),
374 fn test_from_base64_urlsafe() {
375 assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
379 fn test_from_base64_invalid_char() {
380 assert!("Zm$=".from_base64().is_err());
381 assert!("Zg==$".from_base64().is_err());
385 fn test_from_base64_invalid_padding() {
386 assert!("Z===".from_base64().is_err());
390 fn test_base64_random() {
391 use std::rand::{thread_rng, random, Rng};
393 for _ in range(0u, 1000) {
394 let times = thread_rng().gen_range(1u, 100);
395 let v = thread_rng().gen_iter::<u8>().take(times).collect::<Vec<_>>();
396 assert_eq!(v.to_base64(STANDARD)
404 pub fn bench_to_base64(b: &mut Bencher) {
405 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
406 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
408 s.as_bytes().to_base64(STANDARD);
410 b.bytes = s.len() as u64;
414 pub fn bench_from_base64(b: &mut Bencher) {
415 let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
416 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
417 let sb = s.as_bytes().to_base64(STANDARD);
419 sb.from_base64().unwrap();
421 b.bytes = sb.len() as u64;