crates/edge/json/src/b64.rs 2.2 KiB 74 lines Raw
1 //! Standard base64 (RFC 4648) with padding.2 //!3 //! The event object carries bytes as base64 and the JSON mirror does too, so4 //! the encoder lives beside the value tree and neither side invents its own.5 6 /// The standard alphabet of RFC 4648, with padding.7 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";8 9 /// Standard base64 of `bytes`, with `=` padding.10 pub fn encode(bytes: &[u8]) -> String {11     let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);12     for chunk in bytes.chunks(3) {13         let b0 = chunk[0];14         let b1 = chunk.get(1).copied().unwrap_or(0);15         let b2 = chunk.get(2).copied().unwrap_or(0);16         out.push(ALPHABET[(b0 >> 2) as usize] as char);17         out.push(ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);18         if chunk.len() > 1 {19             out.push(ALPHABET[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);20         } else {21             out.push('=');22         }23         if chunk.len() > 2 {24             out.push(ALPHABET[(b2 & 0x3f) as usize] as char);25         } else {26             out.push('=');27         }28     }29     out30 }31 32 /// The bytes of a standard base64 string.33 ///34 /// The inverse of [`encode`], so a test can compare bytes rather than a string.35 pub fn decode(text: &str) -> Option<Vec<u8>> {36     let bytes = text.as_bytes();37     if !bytes.len().is_multiple_of(4) {38         return None;39     }40     let mut out = Vec::with_capacity(bytes.len() / 4 * 3);41     for chunk in bytes.chunks(4) {42         let a = value(chunk[0])?;43         let b = value(chunk[1])?;44         let c = if chunk[2] == b'=' {45             6446         } else {47             value(chunk[2])?48         };49         let d = if chunk[3] == b'=' {50             6451         } else {52             value(chunk[3])?53         };54         out.push((a << 2) | (b >> 4));55         if c < 64 {56             out.push(((b & 0x0f) << 4) | (c >> 2));57         }58         if d < 64 {59             out.push(((c & 0x03) << 6) | d);60         }61     }62     Some(out)63 }64 65 fn value(byte: u8) -> Option<u8> {66     match byte {67         b'A'..=b'Z' => Some(byte - b'A'),68         b'a'..=b'z' => Some(byte - b'a' + 26),69         b'0'..=b'9' => Some(byte - b'0' + 52),70         b'+' => Some(62),71         b'/' => Some(63),72         _ => None,73     }74 }