Skip to content

Instantly share code, notes, and snippets.

@lawliet89
Created March 2, 2017 03:01
Show Gist options
  • Save lawliet89/f4551f03b5550e37ad0c65eeefec8ffe to your computer and use it in GitHub Desktop.
Save lawliet89/f4551f03b5550e37ad0c65eeefec8ffe to your computer and use it in GitHub Desktop.
Rust Base64 Conversion Stuff
extern crate rustc_serialize;
use rustc_serialize::base64::{self, ToBase64, FromBase64};
#[derive(Clone, Eq, PartialEq)]
pub enum Base64 {
Standard(String),
UrlSafe(String),
Mime(String),
}
macro_rules! implement_to {
($name:ident, $variant_type:expr, $variant_pat:pat) => (
fn $name(&self) -> Result<Base64, Error> {
match *self {
Base64::Standard(ref base64) | Base64::UrlSafe(ref base64) | Base64::Mime(ref base64) => {
let decoded = str::from_base64(base64)?;
let encoded = decoded.to_base64()?;
Ok($variant_type(encoded))
}
}
}
)
}
impl Base64 {
fn config(&self) -> base64::Config {
use Base64::*;
match *self {
Standard(_) => base64::STANDARD,
UrlSafe(_) => base64::URL_SAFE,
Mime(_) => base64::MIME,
}
}
implement_to!(to_standard, Base64::Standard, Base64::Standard(_));
implement_to!(to_url_safe, Base64::UrlSafe, Base64::UrlSafe(_));
implement_to!(to_mime, Base64::Mime, Base64::Mime(_));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment