blob: 662f514b2bdf4d14aa489ea0b870821bb331b132 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2015 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package utils
5
6import (
7 "math/rand"
8 "sync"
9 "time"
10)
11
12// Can be used as a sane default argument for RandomString
13var (
14 LowerAlpha = []rune("abcdefghijklmnopqrstuvwxyz")
15 UpperAlpha = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
16 Digits = []rune("0123456789")
17)
18
19var (
20 randomStringMu sync.Mutex
21 randomStringRand *rand.Rand
22)
23
24func 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
32func 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}