snowflake.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "github.com/sony/sonyflake"
  4. "strconv"
  5. "strings"
  6. "time"
  7. )
  8. func main() {
  9. startTime := time.Date(2018, 9, 15, 7, 59, 59, 0, time.UTC)
  10. keyGen := sonyflake.NewSonyflake(sonyflake.Settings{
  11. StartTime: startTime,
  12. MachineID: func() (uint16, error) {
  13. return 1, nil
  14. },
  15. })
  16. n := 3
  17. for i := 0; i < 500; i++ {
  18. newId, _ := keyGen.NextID()
  19. idStr := strconv.FormatUint(newId, 10)
  20. sLen := len(idStr)
  21. subLen := sLen / n
  22. if sLen%n != 0 {
  23. subLen++
  24. }
  25. var partArr []string
  26. var codeArr []string
  27. for j := 0; j < n; j++ {
  28. start := subLen * j
  29. end := subLen * (j + 1)
  30. if end >= sLen {
  31. end = sLen
  32. }
  33. part := idStr[start:end]
  34. partArr = append(partArr, part)
  35. partNum, _ := strconv.ParseInt(part, 10, 32)
  36. code := decimalToAny(int(partNum), 35)
  37. codeArr = append(codeArr, code)
  38. }
  39. println(newId, " : ", strings.Join(partArr, "-"), " : ", strings.Join(codeArr, "-"))
  40. }
  41. }
  42. var tenToAny = map[int]string{0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", 16: "g", 17: "h", 18: "i", 19: "j", 20: "k", 21: "l", 22: "m", 23: "n", 24: "o", 25: "p", 26: "q", 27: "r", 28: "s", 29: "t", 30: "u", 31: "v", 32: "w", 33: "x", 34: "y", 35: "z", 36: ":", 37: ";", 38: "<", 39: "=", 40: ">", 41: "?", 42: "@", 43: "[", 44: "]", 45: "^", 46: "_", 47: "{", 48: "|", 49: "}", 50: "A", 51: "B", 52: "C", 53: "D", 54: "E", 55: "F", 56: "G", 57: "H", 58: "I", 59: "J", 60: "K", 61: "L", 62: "M", 63: "N", 64: "O", 65: "P", 66: "Q", 67: "R", 68: "S", 69: "T", 70: "U", 71: "V", 72: "W", 73: "X", 74: "Y", 75: "Z"}
  43. func decimalToAny(num int, n int) string {
  44. new_num_str := ""
  45. var remainder int
  46. var remainder_string string
  47. for num != 0 {
  48. remainder = num % n
  49. if 76 > remainder && remainder > 9 {
  50. remainder_string = tenToAny[remainder]
  51. } else {
  52. remainder_string = strconv.Itoa(remainder)
  53. }
  54. new_num_str = remainder_string + new_num_str
  55. num = num / n
  56. }
  57. return new_num_str
  58. }