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

DefaultIdGenerator.v 1.6 kB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module gen
  2. import contract
  3. import core
  4. import time
  5. pub struct DefaultIdGenerator {
  6. mut:
  7. options &contract.IdGeneratorOptions
  8. snow_worker &contract.ISnowWorker
  9. }
  10. pub fn make_generator(options &contract.IdGeneratorOptions) &DefaultIdGenerator {
  11. min_time := i64(631123200000)
  12. if options.base_time < min_time || options.base_time > time.now().unix_time_milli() {
  13. panic("base_time error.")
  14. }
  15. if options.seq_bitlength+options.workerid_bitlength > 22 {
  16. panic("error:workerid_bitlength + seq_bitlength <= 22")
  17. }
  18. max_workerid_number := 1<<options.workerid_bitlength - 1
  19. if options.worker_id > max_workerid_number {
  20. panic("WorkerId error. (range:[1, " + max_workerid_number.str() + "]")
  21. }
  22. if options.seq_bitlength < 2 || options.seq_bitlength > 21 {
  23. panic("seq_bitlength error. (range:[2, 21])")
  24. }
  25. max_seqnumber := 1<<options.seq_bitlength - 1
  26. if options.max_seqnumber > max_seqnumber {
  27. panic("MaxSeqNumber error. (range:[1, " + max_seqnumber.str() + "]")
  28. }
  29. if options.min_seqnumber > max_seqnumber {
  30. panic("MinSeqNumber error. (range:[1, " + max_seqnumber.str() + "]")
  31. }
  32. match options.method {
  33. 1 {
  34. return &DefaultIdGenerator{
  35. options: options,
  36. snow_worker: core.make_sf_m1(options),
  37. }
  38. }
  39. 2 {
  40. return &DefaultIdGenerator{
  41. options: options,
  42. snow_worker: core.make_sf_m2(options),
  43. }
  44. }
  45. else {
  46. return &DefaultIdGenerator{
  47. options: options,
  48. snow_worker: core.make_sf_m1(options),
  49. }
  50. }
  51. }
  52. }
  53. pub fn (mut dig DefaultIdGenerator) new_long() u64 {
  54. return dig.snow_worker.next_id()
  55. }

雪花算法中非常好用的数字ID生成器