summaryrefslogtreecommitdiff
path: root/tmp/automap.go
blob: 187960cc90650394590f1faebe7c3616fe176f4e (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package server

import (
	"strconv"
	"sort"
	"fmt"
	"io"
)

type autokey struct {
	flag bool
	n int
	v string
}

type automap map[string]interface{}

type autokeys []autokey

func (t autokey) String() string {
	return t.v
}

func (t autokeys) Len() int {
	return len(t)
}

func (t autokeys) Less(i, j int) bool {
	a := &t[i]
	b := &t[j]

	if a.flag && b.flag {
		return a.n < b.n
	}

	if !a.flag && !b.flag {
		return a.v < b.v
	}

	return b.flag
}

func (t autokeys) Swap(i, j int) {
	t[i], t[j] = t[j], t[i]
}

func (m automap) add(v interface{}) {
	for n := 1;; n++ {
		k := fmt.Sprint(n)
		if _, ok := m[k]; !ok {
			m[k] = v
			break
		}
	}
}

func (m automap) del(k string) bool {
	if _, ok := m[k]; !ok {
		return false
	}

	delete(m, k)

	return true
}

func (m automap) rename(old string, new string) bool {
	if _, ok := m[old]; !ok {
		return false
	}

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

	m[new] = m[old]

	delete(m, old)

	return true
}

func (m automap) show(w io.Writer) {
	var keys autokeys

	for k, _ := range m {
		t := autokey{v: k}

		n, err := strconv.Atoi(k)
		if err == nil {
			t.flag = true
			t.n = n
		}

		keys = append(keys, t)
	}

	sort.Sort(keys)

	for _, k := range keys {
		fmt.Fprintln(w, k, m[k.v])
	}
}