cid.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
  2. // Use of this source code is governed by an MIT-style license that can be
  3. // found in the LICENSE file.
  4. // Package cid provides a manager for mappings between node ID:s and connection ID:s.
  5. package cid
  6. import "sync"
  7. type Map struct {
  8. sync.Mutex
  9. toCid map[string]uint
  10. toName []string
  11. }
  12. var (
  13. LocalName = "<local>"
  14. LocalID uint = 0
  15. )
  16. func NewMap() *Map {
  17. return &Map{
  18. toCid: map[string]uint{"<local>": 0},
  19. toName: []string{"<local>"},
  20. }
  21. }
  22. func (m *Map) Get(name string) uint {
  23. m.Lock()
  24. defer m.Unlock()
  25. cid, ok := m.toCid[name]
  26. if ok {
  27. return cid
  28. }
  29. // Find a free slot to get a new ID
  30. for i, n := range m.toName {
  31. if n == "" {
  32. m.toName[i] = name
  33. m.toCid[name] = uint(i)
  34. return uint(i)
  35. }
  36. }
  37. // Add it to the end since we didn't find a free slot
  38. m.toName = append(m.toName, name)
  39. cid = uint(len(m.toName) - 1)
  40. m.toCid[name] = cid
  41. return cid
  42. }
  43. func (m *Map) Name(cid uint) string {
  44. m.Lock()
  45. defer m.Unlock()
  46. return m.toName[cid]
  47. }
  48. func (m *Map) Names() []string {
  49. m.Lock()
  50. var names []string
  51. for _, name := range m.toName {
  52. if name != "" {
  53. names = append(names, name)
  54. }
  55. }
  56. m.Unlock()
  57. return names
  58. }
  59. func (m *Map) Clear(name string) {
  60. m.Lock()
  61. cid, ok := m.toCid[name]
  62. if ok {
  63. m.toName[cid] = ""
  64. delete(m.toCid, name)
  65. }
  66. m.Unlock()
  67. }