2014-03-12 05:32:26 +00:00
|
|
|
// Package cid provides a manager for mappings between node ID:s and connection ID:s.
|
2014-03-01 10:11:37 +00:00
|
|
|
package cid
|
|
|
|
|
2014-03-28 13:36:57 +00:00
|
|
|
import "sync"
|
|
|
|
|
2014-03-01 10:11:37 +00:00
|
|
|
type Map struct {
|
2014-03-28 13:36:57 +00:00
|
|
|
sync.Mutex
|
|
|
|
toCid map[string]uint
|
2014-03-01 10:11:37 +00:00
|
|
|
toName []string
|
|
|
|
}
|
|
|
|
|
2014-03-28 13:36:57 +00:00
|
|
|
var (
|
|
|
|
LocalName = "<local>"
|
|
|
|
LocalID uint = 0
|
|
|
|
)
|
|
|
|
|
2014-03-01 10:11:37 +00:00
|
|
|
func NewMap() *Map {
|
|
|
|
return &Map{
|
2014-03-28 13:36:57 +00:00
|
|
|
toCid: map[string]uint{"<local>": 0},
|
|
|
|
toName: []string{"<local>"},
|
2014-03-01 10:11:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-28 13:36:57 +00:00
|
|
|
func (m *Map) Get(name string) uint {
|
|
|
|
m.Lock()
|
|
|
|
defer m.Unlock()
|
|
|
|
|
2014-03-01 10:11:37 +00:00
|
|
|
cid, ok := m.toCid[name]
|
|
|
|
if ok {
|
|
|
|
return cid
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find a free slot to get a new ID
|
|
|
|
for i, n := range m.toName {
|
|
|
|
if n == "" {
|
|
|
|
m.toName[i] = name
|
2014-03-28 13:36:57 +00:00
|
|
|
m.toCid[name] = uint(i)
|
|
|
|
return uint(i)
|
2014-03-01 10:11:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add it to the end since we didn't find a free slot
|
|
|
|
m.toName = append(m.toName, name)
|
2014-03-28 13:36:57 +00:00
|
|
|
cid = uint(len(m.toName) - 1)
|
2014-03-01 10:11:37 +00:00
|
|
|
m.toCid[name] = cid
|
|
|
|
return cid
|
|
|
|
}
|
|
|
|
|
2014-03-28 13:36:57 +00:00
|
|
|
func (m *Map) Name(cid uint) string {
|
|
|
|
m.Lock()
|
|
|
|
defer m.Unlock()
|
|
|
|
|
|
|
|
return m.toName[cid]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Map) Names() []string {
|
|
|
|
m.Lock()
|
|
|
|
|
|
|
|
var names []string
|
|
|
|
for _, name := range m.toName {
|
|
|
|
if name != "" {
|
|
|
|
names = append(names, name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
m.Unlock()
|
|
|
|
return names
|
|
|
|
}
|
|
|
|
|
2014-03-01 10:11:37 +00:00
|
|
|
func (m *Map) Clear(name string) {
|
2014-03-28 13:36:57 +00:00
|
|
|
m.Lock()
|
2014-03-01 10:11:37 +00:00
|
|
|
cid, ok := m.toCid[name]
|
|
|
|
if ok {
|
|
|
|
m.toName[cid] = ""
|
|
|
|
delete(m.toCid, name)
|
|
|
|
}
|
2014-03-28 13:36:57 +00:00
|
|
|
m.Unlock()
|
2014-03-01 10:11:37 +00:00
|
|
|
}
|