Created
          January 20, 2024 11:43 
        
      - 
      
- 
        Save tonitrnel/2757db2ee82586d3a971eb91a77147f1 to your computer and use it in GitHub Desktop. 
    Base64 Encode
  
        
  
    
      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
    
  
  
    
  | const S_BASE_64: [char; 64] = [ | |
| 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', | |
| 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', | |
| 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', | |
| '5', '6', '7', '8', '9', '+', '/', | |
| ]; | |
| fn to_base64(bytes: &[u8]) -> String { | |
| let mut dst = String::new(); | |
| let mut padding = 0; | |
| for chunk in bytes.chunks(3) { | |
| let (a, b, c) = match chunk { | |
| [a, b, c] => (*a, *b, *c), | |
| [a, b] => { | |
| padding = 1; | |
| (*a, *b, 0) | |
| } | |
| [a] => { | |
| padding = 2; | |
| (*a, 0, 0) | |
| } | |
| _ => unreachable!(), | |
| }; | |
| let n = ((a as u32) << 16) | ((b as u32) << 8) | c as u32; | |
| dst.push(S_BASE_64[((n >> 18) & 0x3F) as usize]); | |
| dst.push(S_BASE_64[((n >> 12) & 0x3F) as usize]); | |
| if padding < 2 { | |
| dst.push(S_BASE_64[((n >> 6) & 0x3F) as usize]); | |
| } | |
| if padding < 1 { | |
| dst.push(S_BASE_64[(n & 0x3F) as usize]); | |
| } | |
| } | |
| for _ in 0..padding { | |
| dst.push('='); | |
| } | |
| dst | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment