#[path = "encode_sets.rs"]
mod encode_sets;
#[derive(Copy)]
pub struct EncodeSet {
map: &'static [&'static str; 256],
}
pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE };
pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY };
pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT };
pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO };
pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD };
pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME };
pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet {
map: &encode_sets::FORM_URLENCODED,
};
#[inline]
pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) {
for &byte in input.iter() {
output.push_str(encode_set.map[byte as uint])
}
}
#[inline]
pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String {
let mut output = String::new();
percent_encode_to(input, encode_set, &mut output);
output
}
#[inline]
pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) {
percent_encode_to(input.as_bytes(), encode_set, output)
}
#[inline]
pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String {
let mut output = String::new();
utf8_percent_encode_to(input, encode_set, &mut output);
output
}
pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) {
let mut i = 0u;
while i < input.len() {
let c = input[i];
if c == b'%' && i + 2 < input.len() {
match (from_hex(input[i + 1]), from_hex(input[i + 2])) {
(Some(h), Some(l)) => {
output.push(h * 0x10 + l);
i += 3;
continue
},
_ => (),
}
}
output.push(c);
i += 1;
}
}
#[inline]
pub fn percent_decode(input: &[u8]) -> Vec<u8> {
let mut output = Vec::new();
percent_decode_to(input, &mut output);
output
}
#[inline]
pub fn lossy_utf8_percent_decode(input: &[u8]) -> String {
String::from_utf8_lossy(percent_decode(input).as_slice()).to_string()
}
#[inline]
pub fn from_hex(byte: u8) -> Option<u8> {
match byte {
b'0' ... b'9' => Some(byte - b'0'), b'A' ... b'F' => Some(byte + 10 - b'A'), b'a' ... b'f' => Some(byte + 10 - b'a'), _ => None
}
}