github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekarand/randstrgen.go (about) 1 // Copyright © 2020. All rights reserved. 2 // Author: Ilya Stroy. 3 // Contacts: iyuryevich@pm.me, https://github.com/qioalice 4 // License: https://opensource.org/licenses/MIT 5 6 package ekarand 7 8 import ( 9 mrand "math/rand" 10 11 "github.com/qioalice/ekago/v3/ekastr" 12 ) 13 14 const ( 15 charSetLetters = `abcdefghijklmnopqrstuvwxyz` 16 charSetDigits = `1234567890` 17 charSetAll = charSetLetters + charSetDigits 18 ) 19 20 // WithLen generates a random sequence with n length that contains both of 21 // english letters and arabic digits. Returns "" if n <= 0. 22 func WithLen(n int) string { 23 return genWithLenFrom(charSetAll, n) 24 } 25 26 // WithLenOnlyLetters generates a random sequence with n length that contains 27 // only english letters. Returns "" if n <= 0. 28 func WithLenOnlyLetters(n int) string { 29 return genWithLenFrom(charSetLetters, n) 30 } 31 32 // WithLenOnlyNumbers generates a random sequence with n length that contains 33 // only arabic digits. Returns "" if n <= 0. 34 func WithLenOnlyNumbers(n int) string { 35 return genWithLenFrom(charSetDigits, n) 36 } 37 38 func genWithLenFrom(charSet string, n int) string { 39 if n <= 0 { 40 return "" 41 } 42 res := make([]byte, n) 43 for i := 0; i < n; i++ { 44 res[i] = charSet[mrand.Intn(len(charSet))] 45 } 46 return ekastr.B2S(res) 47 }