default-message-id-provider.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. /**
  3. * DefaultMessageAllocator constructor
  4. * @constructor
  5. */
  6. function DefaultMessageIdProvider () {
  7. if (!(this instanceof DefaultMessageIdProvider)) {
  8. return new DefaultMessageIdProvider()
  9. }
  10. /**
  11. * MessageIDs starting with 1
  12. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  13. */
  14. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  15. }
  16. /**
  17. * allocate
  18. *
  19. * Get the next messageId.
  20. * @return unsigned int
  21. */
  22. DefaultMessageIdProvider.prototype.allocate = function () {
  23. // id becomes current state of this.nextId and increments afterwards
  24. const id = this.nextId++
  25. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  26. if (this.nextId === 65536) {
  27. this.nextId = 1
  28. }
  29. return id
  30. }
  31. /**
  32. * getLastAllocated
  33. * Get the last allocated messageId.
  34. * @return unsigned int
  35. */
  36. DefaultMessageIdProvider.prototype.getLastAllocated = function () {
  37. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  38. }
  39. /**
  40. * register
  41. * Register messageId. If success return true, otherwise return false.
  42. * @param { unsigned int } - messageId to register,
  43. * @return boolean
  44. */
  45. DefaultMessageIdProvider.prototype.register = function (messageId) {
  46. return true
  47. }
  48. /**
  49. * deallocate
  50. * Deallocate messageId.
  51. * @param { unsigned int } - messageId to deallocate,
  52. */
  53. DefaultMessageIdProvider.prototype.deallocate = function (messageId) {
  54. }
  55. /**
  56. * clear
  57. * Deallocate all messageIds.
  58. */
  59. DefaultMessageIdProvider.prototype.clear = function () {
  60. }
  61. module.exports = DefaultMessageIdProvider