Created
August 8, 2018 13:48
-
-
Save colelawrence/f31aad92b0a405d70b9ac437e944379c to your computer and use it in GitHub Desktop.
Random alpha-numeric rust and golang
This file contains 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
extern crate rand; | |
use self::rand::random; | |
fn get_rand_alphanum() -> char { | |
// >>> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~<<< | |
// lowercase 97...122 = 26 | |
// uppercase 65...90 = 26 | |
// numerals 48...57 = 10 | |
// lowercase 0...25, + 97 | |
// uppercase 26...51, + 39 | |
// numerals 52...61, - 4 | |
let mut val = (random::<f32>() * 62.0) as u8; | |
if val >= 52 { | |
val = val - 4; | |
} else if val >= 26 { | |
val = val + 39; | |
} else { | |
val = val + 97; | |
} | |
val as char | |
} | |
pub fn random_string(len: usize) -> String { | |
(0..len).map(|_| get_rand_alphanum()).collect() | |
} |
This file contains 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
func randAlphanum() byte { | |
// >>> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~<<< | |
// lowercase 97...122 = 26 | |
// uppercase 65...90 = 26 | |
// numerals 48...57 = 10 | |
// lowercase 0...25, + 97 | |
// uppercase 26...51, + 39 | |
// numerals 52...61, - 4 | |
var val = rand.Intn(62) | |
if val >= 52 { | |
val = val - 4 | |
} else if val >= 26 { | |
val = val + 39 | |
} else { | |
val = val + 97 | |
} | |
return byte(val) | |
} | |
func randomString(l int) string { | |
bytes := make([]byte, l) | |
for i := 0; i < l; i++ { | |
bytes[i] = randAlphanum() | |
} | |
return string(bytes) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment