Rust Base62 Sample Code

Learn how to implement Base62 encoding and decoding in Rust programming with sample code for efficient data handling.

const BASE62: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

fn encode(input: &[u8]) -> String {
    if input.is_empty() {
        return String::new();
    }

    let mut value = BigInt::from_bytes_be(Sign::Plus, input);
    let mut result = String::new();

    while value > BigInt::from(0) {
        let (div, rem) = value.div_rem(&BigInt::from(62));
        result.push(BASE62.chars().nth(rem.to_usize().unwrap()).unwrap());
        value = div;
    }

    for &byte in input {
        if byte == 0 {
            result.push(BASE62.chars().nth(0).unwrap());
        } else {
            break;
        }
    }

    result.chars().rev().collect()
}

fn decode(input: &str) -> Vec<u8> {
    if input.is_empty() {
        return Vec::new();
    }

    let mut value = BigInt::from(0);
    for c in input.chars() {
        value = value * 62 + BigInt::from(BASE62.find(c).unwrap());
    }

    let mut bytes = value.to_bytes_be().1;
    if bytes[0] == 0 {
        bytes = bytes[1..].to_vec();
    }

    let leading_zeroes = input.chars().take_while(|&c| c == BASE62.chars().nth(0).unwrap()).count();
    let mut result = vec![0; leading_zeroes];
    result.extend(bytes);
    result
}

fn main() {
    let input = "回□〓≡╝╚╔╗";
    let encoded = encode(input.as_bytes());
    println!("Encoded: {}", encoded);

    let decoded = decode(&encoded);
    let decoded_str = String::from_utf8(decoded).unwrap();
    println!("Decoded: {}", decoded_str);
}
Base62 Sample Code