messageids.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2013 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution, and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Seth Hoenig
  11. * Allan Stockdill-Mander
  12. * Mike Robertson
  13. */
  14. package mqtt
  15. import (
  16. "sync"
  17. )
  18. // MId is 16 bit message id as specified by the MQTT spec.
  19. // In general, these values should not be depended upon by
  20. // the client application.
  21. type MId uint16
  22. type messageIds struct {
  23. sync.RWMutex
  24. index map[uint16]Token
  25. }
  26. const (
  27. midMin uint16 = 1
  28. midMax uint16 = 65535
  29. )
  30. func (mids *messageIds) freeID(id uint16) {
  31. mids.Lock()
  32. defer mids.Unlock()
  33. delete(mids.index, id)
  34. }
  35. func (mids *messageIds) getID(t Token) uint16 {
  36. mids.Lock()
  37. defer mids.Unlock()
  38. for i := midMin; i < midMax; i++ {
  39. if _, ok := mids.index[i]; !ok {
  40. mids.index[i] = t
  41. return i
  42. }
  43. }
  44. return 0
  45. }
  46. func (mids *messageIds) getToken(id uint16) Token {
  47. mids.RLock()
  48. defer mids.RUnlock()
  49. if token, ok := mids.index[id]; ok {
  50. return token
  51. }
  52. return nil
  53. }