工具包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.4 KiB

  1. package utils
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. )
  7. const (
  8. KC_RAND_KIND_NUM = 0 // 纯数字
  9. KC_RAND_KIND_LOWER = 1 // 小写字母
  10. KC_RAND_KIND_UPPER = 2 // 大写字母
  11. KC_RAND_KIND_ALL = 3 // 数字、大小写字母
  12. )
  13. func newUUID() *[16]byte {
  14. u := &[16]byte{}
  15. rand.Read(u[:16])
  16. u[8] = (u[8] | 0x80) & 0xBf
  17. u[6] = (u[6] | 0x40) & 0x4f
  18. return u
  19. }
  20. func UUIDString() string {
  21. u := newUUID()
  22. return fmt.Sprintf("%x-%x-%x-%x-%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  23. }
  24. func UUIDHexString() string {
  25. u := newUUID()
  26. return fmt.Sprintf("%x%x%x%x%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  27. }
  28. func UUIDBinString() string {
  29. u := newUUID()
  30. return fmt.Sprintf("%s", [16]byte(*u))
  31. }
  32. func Krand(size int, kind int) []byte {
  33. ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
  34. isAll := kind > 2 || kind < 0
  35. rand.Seed(time.Now().UnixNano())
  36. for i := 0; i < size; i++ {
  37. if isAll { // random ikind
  38. ikind = rand.Intn(3)
  39. }
  40. scope, base := kinds[ikind][0], kinds[ikind][1]
  41. result[i] = uint8(base + rand.Intn(scope))
  42. }
  43. return result
  44. }
  45. // OrderUUID is only num for uuid
  46. func OrderUUID(uid int) string {
  47. ustr := IntToStr(uid)
  48. tstr := Int64ToStr(time.Now().Unix())
  49. ulen := len(ustr)
  50. tlen := len(tstr)
  51. rlen := 18 - ulen - tlen
  52. krb := Krand(rlen, KC_RAND_KIND_NUM)
  53. return ustr + tstr + string(krb)
  54. }