fork download
  1. struct B64 {
  2. table: Vec<char>,
  3. }
  4. impl B64 {
  5. fn new() -> B64 {
  6. B64{table: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".chars().collect()}
  7. }
  8. fn encode(&self, s: &str) -> String {
  9. let mut bs: Vec<bool> = s.as_bytes().iter()
  10. .flat_map(|b| (0..8).map(move |i| b >> (7 - i) & 1u8 != 0u8)).collect();
  11. while 0 < bs.len() % 6 {bs.push(false)}
  12. let mut cs: Vec<char> = bs.chunks(6)
  13. .map(|b6| b6.iter().enumerate().fold(0, |acc, (i, b)| acc + ((*b as u8) << (5 - i))))
  14. .map(|u| self.table[u as usize]).collect();
  15. while 0 < cs.len() % 4 {cs.push('=')}
  16. cs.into_iter().collect()
  17. }
  18. fn decode(&self, s: &str) -> String {
  19. let us: Vec<u8> = s.chars().take_while(|d| *d != '=')
  20. .flat_map(|c| self.table.iter().position(|e| *e == c))
  21. .flat_map(|b| (0..6).map(move |i| b as u8 >> (5 - i) & 1u8 != 0u8))
  22. .collect::<Vec<bool>>().chunks(8).filter(|b8| b8.len() == 8)
  23. .map(|b8| b8.iter().enumerate().fold(0, |acc, (i, b)| acc + ((*b as u8) << (7 - i))))
  24. .collect();
  25. String::from_utf8(us).unwrap_or(String::new())
  26. }
  27. }
  28. fn main() {
  29. let b64 = B64::new();
  30. let p = |s| {
  31. let e = b64.encode(s);
  32. let d = b64.decode(e.as_str());
  33. println!("{}\n{}\n{}\n", s, e, d);
  34. };
  35. p("ABCDEFG");
  36. p("Hello, World!");
  37. p("0123456789\"#$%&'()`=@");
  38. p("💖");
  39. }
Success #stdin #stdout 0s 14872KB
stdin
Standard input is empty
stdout
ABCDEFG
QUJDREVGRw==
ABCDEFG

Hello, World!
SGVsbG8sIFdvcmxkIQ==
Hello, World!

0123456789"#$%&'()`=@
MDEyMzQ1Njc4OSIjJCUmJygpYD1A
0123456789"#$%&'()`=@

💖
8J+Slg==
💖