summaryrefslogtreecommitdiff
path: root/pkg/server/automap.go
blob: f38f758577ecbea5171d3d8ef2c41cb976bbaf5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package server

import (
	"errors"
	"fmt"
)

type automap map[string]interface{}

var errExists = errors.New("already exists")
var errNotFound = errors.New("no such entry")

func (m automap) next() string {
	for n := 1; ; n++ {
		k := fmt.Sprintf("%d", n)
		if _, ok := m[k]; !ok {
			return k
		}
	}
}

func (m automap) add(v interface{}) string {
	k := m.next()
	m[k] = v
	return k
}

func (m automap) rename(old string, new string) (interface{}, error) {
	if _, ok := m[old]; !ok {
		return nil, errNotFound
	}

	if _, ok := m[new]; ok {
		return nil, errExists
	}

	v := m[old]
	m[new] = v

	delete(m, old)
	return v, nil
}