David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2015 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package utils |
| 5 | |
| 6 | import ( |
| 7 | "math/rand" |
| 8 | "sync" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | // Can be used as a sane default argument for RandomString |
| 13 | var ( |
| 14 | LowerAlpha = []rune("abcdefghijklmnopqrstuvwxyz") |
| 15 | UpperAlpha = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ") |
| 16 | Digits = []rune("0123456789") |
| 17 | ) |
| 18 | |
| 19 | var ( |
| 20 | randomStringMu sync.Mutex |
| 21 | randomStringRand *rand.Rand |
| 22 | ) |
| 23 | |
| 24 | func init() { |
| 25 | randomStringRand = rand.New( |
| 26 | rand.NewSource(time.Now().UnixNano()), |
| 27 | ) |
| 28 | } |
| 29 | |
| 30 | // RandomString will return a string of length n that will only |
| 31 | // contain runes inside validRunes |
| 32 | func RandomString(n int, validRunes []rune) string { |
| 33 | randomStringMu.Lock() |
| 34 | defer randomStringMu.Unlock() |
| 35 | |
| 36 | runes := make([]rune, n) |
| 37 | for i := range runes { |
| 38 | runes[i] = validRunes[randomStringRand.Intn(len(validRunes))] |
| 39 | } |
| 40 | |
| 41 | return string(runes) |
| 42 | } |