Last active
January 1, 2017 08:16
-
-
Save hikilaka/f999a94d5b4aa2901f722722a9a6f7b1 to your computer and use it in GitHub Desktop.
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
fn base37_encode(text: String) -> u64 { | |
let mut hash = 0; | |
for ch in text.chars().take(12) { | |
let modifier = match ch { | |
'a'...'z' => 1 + (ch as u64 - 'a' as u64), | |
'A'...'Z' => 1 + (ch as u64 - 'A' as u64), | |
'0'...'9' => 33 + (ch as u64 - '0' as u64), | |
_ => 0, | |
}; | |
hash *= 37; | |
hash += modifier; | |
} | |
return hash; | |
} | |
fn base37_decode(hash: u64) -> String { | |
let mut hash = hash; | |
let mut chars = Vec::new(); | |
while hash != 0 { | |
if chars.len() >= 12 { | |
break; | |
} | |
let modifier = (hash % 37) as u8; | |
hash /= 37; | |
match modifier { | |
1...26 => chars.push((modifier + 96) as char), | |
27...36 => chars.push((modifier + 21) as char), | |
_ => chars.push(' '), | |
} | |
} | |
return chars.into_iter().rev().collect(); | |
} | |
fn main() { | |
let username = "hikilaka".to_string(); | |
let hash = base37_encode(username); | |
println!("encoded: {}", hash); | |
println!("decoded: {}", base37_decode(hash)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment