12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package buildin
- import (
- "fmt"
- "math/rand"
- "time"
- "unicode/utf8"
- "unsafe"
- )
- const (
- // 6 bits to represent a letter index
- letterIdBits = 6
- // All 1-bits as many as letterIdBits
- letterIdMask = 1<<letterIdBits - 1
- letterIdMax = 63 / letterIdBits
- )
- // SplitStringByLength 将字符串按长度划分为数组,汉字2个长度英文1个长度
- func SplitStringByLength(str string, maxLength int) []string {
- var arr []string
- index := 0
- s := ""
- for _, v := range str {
- s = s + string(v)
- if utf8.RuneLen(v) == 1 {
- index += 1
- } else {
- index += 2
- }
- if index >= maxLength {
- arr = append(arr, s)
- index = 0
- s = ""
- }
- }
- if s != "" {
- arr = append(arr, s)
- }
- return arr
- }
- // RandString 随机生成字符串 最强性能!
- func RandString(n int) string {
- letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- var src = rand.NewSource(time.Now().UnixNano())
- b := make([]byte, n)
- // A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
- for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
- if remain == 0 {
- cache, remain = src.Int63(), letterIdMax
- }
- if idx := int(cache & letterIdMask); idx < len(letters) {
- b[i] = letters[idx]
- i--
- }
- cache >>= letterIdBits
- remain--
- }
- return *(*string)(unsafe.Pointer(&b))
- }
- // RandNumberString 返回特定长度的数据随机数字字符串
- func RandNumberString(bit uint8) string {
- rand.Seed(time.Now().UnixNano())
- s := ""
- for i := 0; uint8(i) < bit; i++ {
- r := rand.Intn(9)
- s += fmt.Sprintf("%d", r)
- }
- return s
- }
|