row_key.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package dao
  2. import (
  3. "strconv"
  4. "strings"
  5. "go-common/library/log"
  6. )
  7. const (
  8. _int64Max = 0x7fffffffffffffff
  9. _uint32Max = 0xffffffff
  10. )
  11. // reverseID reverse a digital number represented in string,
  12. // if len(id) < len, fill 0 on the right of reverse id to make reverse id len 10,
  13. // if len(id) > len, will return empty string.
  14. func reverseID(id string, l int) string {
  15. if len(id) > l {
  16. log.Error("len(%s) is %d, greater than the given l %d", id, len(id), l)
  17. return ""
  18. }
  19. // reverse id string
  20. runes := []rune(id)
  21. for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
  22. runes[from], runes[to] = runes[to], runes[from]
  23. }
  24. rid := string(runes)
  25. if len(id) == l {
  26. return rid
  27. }
  28. // fill with 0 on rid's right
  29. rid += strings.Repeat("0", l-len(id))
  30. return rid
  31. }
  32. func checkIDLen(id string) bool {
  33. return len(id) <= _maxIDLen
  34. }
  35. // diffTs return the last 10 digit of (int64_max - ts).
  36. func diffTs(ts int64) string {
  37. i := _int64Max - ts
  38. s := strconv.FormatInt(i, 10)
  39. // during ts 0 - (int64 - now), cut the [9,19) part of s as result
  40. return s[9:19]
  41. }
  42. // diffID return the (unsigned_int32_max - id) convert to string in base 10.
  43. // if len of the string < 10, fill 0 on the left to make len(res) equal to 10.
  44. func diffID(id int64) string {
  45. i := _uint32Max - id
  46. s := strconv.FormatInt(i, 10)
  47. if len(s) == 10 {
  48. return s
  49. }
  50. return strings.Repeat("0", 10-len(s)) + s
  51. }