123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package util
- import (
- "math/rand"
- "time"
- "unicode/utf8"
- "unsafe"
- )
- // StrLen utf8 string length
- func StrLen(s string) int {
- return utf8.RuneCountInString(s)
- }
- // StrMax verify string's max lenth
- func StrMax(s string, max int) bool {
- n := utf8.RuneCountInString(s)
- return n <= max
- }
- // StrMin verify string's min lenth
- func StrMin(s string, min int) bool {
- n := utf8.RuneCountInString(s)
- return n >= min
- }
- // StrRange verify string's Range lenth
- func StrRange(s string, min, max int) bool {
- n := utf8.RuneCountInString(s)
- if n <= max && n >= min {
- return true
- }
- return false
- }
- // Random 指定长度的随机字符串(字母或数字)
- func Random(n int) string {
- str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- bytes := []byte(str)
- result := []byte{}
- r := rand.New(rand.NewSource(time.Now().UnixNano()))
- n1 := len(bytes)
- for i := 0; i < n; i++ {
- result = append(result, bytes[r.Intn(n1)])
- }
- return string(result)
- }
- // StringToBytes converts string to byte slice without a memory allocation.
- func StringToBytes(s string) []byte {
- return *(*[]byte)(unsafe.Pointer(
- &struct {
- string
- Cap int
- }{s, len(s)},
- ))
- }
- // BytesToString converts byte slice to string without a memory allocation.
- func BytesToString(b []byte) string {
- return *(*string)(unsafe.Pointer(&b))
- }
|