forked from peco/peco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection.go
90 lines (74 loc) · 1.75 KB
/
selection.go
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
package peco
import (
"math/big"
"sync"
)
// Selection stores the line numbers that were selected by the user.
// The contents of the Selection is always sorted from smallest to
// largest line number
type Selection struct {
selection *big.Int // bitmask
flipped uint64
mutex sync.Locker
}
// NewSelection creates a new empty Selection
func NewSelection() *Selection {
return &Selection{&big.Int{}, 0, newMutex()}
}
// Invert inverts the selection - if items 2 and 3 are selected out of
// 10 items, then items 1 and items 4 to 10 are selected after call
// to this method
func (s *Selection) Invert(pad int) {
dst := (&big.Int{}).Set(s.selection)
for i := 0; i < pad; i++ {
b := dst.Bit(i)
if b == 1 {
b = 0
} else {
b = 1
}
dst.SetBit(dst, i, b)
if b == 1 {
s.flipped++
}
}
s.selection = dst
}
// Has returns true if line `v` is in the selection
func (s Selection) Has(v int) bool {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.selection.Bit(v) == 1
}
// Add adds a new line number to the selection. If the line already
// exists in the selection, it is silently ignored
func (s *Selection) Add(v int) {
if s.Has(v) {
return
}
s.mutex.Lock()
defer s.mutex.Unlock()
s.flipped++
s.selection = s.selection.SetBit(s.selection, v, 1)
}
// Remove removes the specified line number from the selection
func (s *Selection) Remove(v int) {
if ! s.Has(v) {
return
}
s.mutex.Lock()
defer s.mutex.Unlock()
s.flipped--
s.selection = s.selection.SetBit(s.selection, v, 0)
}
// Clear empties the selection
func (s *Selection) Clear() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.flipped = 0
s.selection = &big.Int{}
}
// Len returns the number of elements in the selection.
func (s Selection) Len() uint64 {
return s.flipped
}