-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
62 lines (52 loc) · 931 Bytes
/
slice.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
package cmps
import (
"encoding/json"
"sync"
"golang.org/x/exp/slices"
)
type Slice[T any] struct {
// I stands for Items
I []T
rw sync.RWMutex
}
func (s *Slice[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(s.I)
}
func (s *Slice[T]) Index(t T) int {
s.rw.RLock()
defer s.rw.RUnlock()
if i, ok := Search(s.I, t); ok {
return i
}
return -1
}
func (s *Slice[T]) Search(t T) (zero T) {
s.rw.RLock()
defer s.rw.RUnlock()
if i, ok := Search(s.I, t); ok {
return s.I[i]
}
return
}
func (s *Slice[T]) Insert(t T) {
s.rw.Lock()
defer s.rw.Unlock()
s.I = Insert(s.I, t)
}
func (s *Slice[T]) Delete(t T) bool {
s.rw.Lock()
defer s.rw.Unlock()
if i, ok := Search(s.I, t); ok {
s.I = slices.Delete(s.I, i, i+1)
return true
}
return false
}
func (s *Slice[T]) Sort() {
s.rw.Lock()
defer s.rw.Unlock()
Sort(s.I)
}
func NewSlice[T any](items ...T) *Slice[T] {
return &Slice[T]{I: items}
}