unique-message-id-provider.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict'
  2. const NumberAllocator = require('number-allocator').NumberAllocator
  3. /**
  4. * UniqueMessageAllocator constructor
  5. * @constructor
  6. */
  7. function UniqueMessageIdProvider () {
  8. if (!(this instanceof UniqueMessageIdProvider)) {
  9. return new UniqueMessageIdProvider()
  10. }
  11. this.numberAllocator = new NumberAllocator(1, 65535)
  12. }
  13. /**
  14. * allocate
  15. *
  16. * Get the next messageId.
  17. * @return if messageId is fully allocated then return null,
  18. * otherwise return the smallest usable unsigned int messageId.
  19. */
  20. UniqueMessageIdProvider.prototype.allocate = function () {
  21. this.lastId = this.numberAllocator.alloc()
  22. return this.lastId
  23. }
  24. /**
  25. * getLastAllocated
  26. * Get the last allocated messageId.
  27. * @return unsigned int
  28. */
  29. UniqueMessageIdProvider.prototype.getLastAllocated = function () {
  30. return this.lastId
  31. }
  32. /**
  33. * register
  34. * Register messageId. If success return true, otherwise return false.
  35. * @param { unsigned int } - messageId to register,
  36. * @return boolean
  37. */
  38. UniqueMessageIdProvider.prototype.register = function (messageId) {
  39. return this.numberAllocator.use(messageId)
  40. }
  41. /**
  42. * deallocate
  43. * Deallocate messageId.
  44. * @param { unsigned int } - messageId to deallocate,
  45. */
  46. UniqueMessageIdProvider.prototype.deallocate = function (messageId) {
  47. this.numberAllocator.free(messageId)
  48. }
  49. /**
  50. * clear
  51. * Deallocate all messageIds.
  52. */
  53. UniqueMessageIdProvider.prototype.clear = function () {
  54. this.numberAllocator.clear()
  55. }
  56. module.exports = UniqueMessageIdProvider