string.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "math/rand"
  4. "time"
  5. "unicode/utf8"
  6. "unsafe"
  7. )
  8. // StrLen utf8 string length
  9. func StrLen(s string) int {
  10. return utf8.RuneCountInString(s)
  11. }
  12. // StrMax verify string's max lenth
  13. func StrMax(s string, max int) bool {
  14. n := utf8.RuneCountInString(s)
  15. return n <= max
  16. }
  17. // StrMin verify string's min lenth
  18. func StrMin(s string, min int) bool {
  19. n := utf8.RuneCountInString(s)
  20. return n >= min
  21. }
  22. // StrRange verify string's Range lenth
  23. func StrRange(s string, min, max int) bool {
  24. n := utf8.RuneCountInString(s)
  25. if n <= max && n >= min {
  26. return true
  27. }
  28. return false
  29. }
  30. // Random 指定长度的随机字符串(字母或数字)
  31. func Random(n int) string {
  32. str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  33. bytes := []byte(str)
  34. result := []byte{}
  35. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  36. n1 := len(bytes)
  37. for i := 0; i < n; i++ {
  38. result = append(result, bytes[r.Intn(n1)])
  39. }
  40. return string(result)
  41. }
  42. // StringToBytes converts string to byte slice without a memory allocation.
  43. func StringToBytes(s string) []byte {
  44. return *(*[]byte)(unsafe.Pointer(
  45. &struct {
  46. string
  47. Cap int
  48. }{s, len(s)},
  49. ))
  50. }
  51. // BytesToString converts byte slice to string without a memory allocation.
  52. func BytesToString(b []byte) string {
  53. return *(*string)(unsafe.Pointer(&b))
  54. }