Created
August 18, 2014 13:57
-
-
Save gioele/a1422b4862c6934639c1 to your computer and use it in GitHub Desktop.
matches in rust with variable values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
impl<'a> FromBase64 for &'a [u8] { | |
fn from_base64(&self, config: Config) -> Result<Vec<u8>, FromBase64Error> { | |
let mut r = Vec::new(); | |
let mut buf: u32 = 0; | |
let mut modulus = 0i; | |
let chars = match config.char_set { | |
Standard => STANDARD_CHARS, | |
UrlSafe => URLSAFE_CHARS, | |
XmlNmtoken => XML_NMTOKEN_CHARS, | |
XmlName => XML_NAME_CHARS, | |
}; | |
let (c62, c63) = (chars[62], chars[63]); | |
let mut it = self.iter().enumerate(); | |
for (idx, &byte) in it { | |
let val = byte as u32; | |
match byte { | |
b'A'..b'Z' => buf |= val - 0x41, | |
b'a'..b'z' => buf |= val - 0x47, | |
b'0'..b'9' => buf |= val + 0x04, | |
c62 => buf |= 0x3E, | |
c63 => buf |= 0x3F, | |
b'\r' | b'\n' => continue, | |
b'=' => break, | |
_ => return Err(InvalidBase64Byte(self[idx], idx)), | |
} | |
buf <<= 6; | |
modulus += 1; | |
if modulus == 4 { | |
modulus = 0; | |
r.push((buf >> 22) as u8); | |
r.push((buf >> 14) as u8); | |
r.push((buf >> 6 ) as u8); | |
} | |
} | |
for (idx, &byte) in it { | |
match byte { | |
b'=' | b'\r' | b'\n' => continue, | |
_ => return Err(InvalidBase64Byte(self[idx], idx)), | |
} | |
} | |
match modulus { | |
2 => { | |
r.push((buf >> 10) as u8); | |
} | |
3 => { | |
r.push((buf >> 16) as u8); | |
r.push((buf >> 8 ) as u8); | |
} | |
0 => (), | |
_ => return Err(InvalidBase64Length), | |
} | |
Ok(r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment