File: multichoose.go

package info (click to toggle)
golang-github-cqroot-multichoose 0.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 84 kB
  • sloc: makefile: 5
file content (63 lines) | stat: -rw-r--r-- 1,130 bytes parent folder | download
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
package multichoose

type MultiChoose struct {
	selected []uint64
	length   int
	limit    int
}

func (mc *MultiChoose) getSelected(index int) bool {
	if index < 0 || index > mc.length {
		return false
	}
	i := uint64(index) >> 6
	j := uint64(index) & 0x3F
	return (mc.selected[i] & (1 << j)) != 0
}

func (mc *MultiChoose) setSelected(index int, value bool) {
	if index < 0 || index > mc.length {
		return
	}
	i := uint64(index) >> 6
	j := uint64(index) & 0x3F
	if value {
		mc.selected[i] |= (1 << j)
	} else {
		mc.selected[i] &^= (1 << j)
	}
}

func New(length int) *MultiChoose {
	return &MultiChoose{
		selected: make([]uint64, (length>>6)+1),
		length:   length,
		limit:    -1,
	}
}

func (mc MultiChoose) Count() int {
	count := 0
	for i := 0; i <= mc.length; i++ {
		if mc.getSelected(i) {
			count++
		}
	}
	return count
}

func (mc *MultiChoose) Select(index int) {
	if mc.limit >= 0 && mc.Count() >= mc.limit {
		return
	}

	mc.setSelected(index, true)
}

func (mc *MultiChoose) Deselect(index int) {
	mc.setSelected(index, false)
}

func (mc MultiChoose) IsSelected(index int) bool {
	return mc.getSelected(index)
}