github.com/icyphox/x@v0.0.355-0.20220311094250-029bd783e8b8/randx/sequence.go (about) 1 /* 2 * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io> 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 * @author Aeneas Rekkas <aeneas+oss@aeneas.io> 17 * @copyright 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io> 18 * @license Apache-2.0 19 */ 20 21 package randx 22 23 import ( 24 "crypto/rand" 25 "math/big" 26 ) 27 28 var rander = rand.Reader // random function 29 30 var ( 31 // AlphaNum contains runes [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]. 32 AlphaNum = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") 33 // Alpha contains runes [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]. 34 Alpha = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") 35 // AlphaLowerNum contains runes [abcdefghijklmnopqrstuvwxyz0123456789]. 36 AlphaLowerNum = []rune("abcdefghijklmnopqrstuvwxyz0123456789") 37 // AlphaUpperNum contains runes [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]. 38 AlphaUpperNum = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") 39 // AlphaLower contains runes [abcdefghijklmnopqrstuvwxyz]. 40 AlphaLower = []rune("abcdefghijklmnopqrstuvwxyz") 41 // AlphaUpper contains runes [ABCDEFGHIJKLMNOPQRSTUVWXYZ]. 42 AlphaUpper = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 43 // Numeric contains runes [0123456789]. 44 Numeric = []rune("0123456789") 45 ) 46 47 // RuneSequence returns a random sequence using the defined allowed runes. 48 func RuneSequence(l int, allowedRunes []rune) (seq []rune, err error) { 49 c := big.NewInt(int64(len(allowedRunes))) 50 seq = make([]rune, l) 51 52 for i := 0; i < l; i++ { 53 r, err := rand.Int(rander, c) 54 if err != nil { 55 return seq, err 56 } 57 rn := allowedRunes[r.Uint64()] 58 seq[i] = rn 59 } 60 61 return seq, nil 62 } 63 64 // MustString returns a random string sequence using the defined runes. Panics on error. 65 func MustString(l int, allowedRunes []rune) string { 66 seq, err := RuneSequence(l, allowedRunes) 67 if err != nil { 68 panic(err) 69 } 70 return string(seq) 71 }