Skip to content

Commit e7acaa3

Browse files
authored
Merge pull request #1631 from ydb-platform/xsync-slice
added `xsync.Slice`
2 parents 55762c7 + 9a38e07 commit e7acaa3

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

internal/xsync/slice.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package xsync
2+
3+
import (
4+
"sync"
5+
)
6+
7+
type Slice[T any] struct {
8+
m sync.RWMutex
9+
s []T
10+
}
11+
12+
func (s *Slice[T]) Append(v T) {
13+
s.m.Lock()
14+
defer s.m.Unlock()
15+
16+
s.s = append(s.s, v)
17+
}
18+
19+
func (s *Slice[T]) Size() int {
20+
s.m.RLock()
21+
defer s.m.RUnlock()
22+
23+
return len(s.s)
24+
}
25+
26+
func (s *Slice[T]) Range(f func(idx int, v T) bool) {
27+
s.m.RLock()
28+
defer s.m.RUnlock()
29+
30+
for idx, v := range s.s {
31+
if !f(idx, v) {
32+
break
33+
}
34+
}
35+
}
36+
37+
func (s *Slice[T]) Remove(idx int) bool {
38+
s.m.Lock()
39+
defer s.m.Unlock()
40+
41+
if idx >= len(s.s) {
42+
return false
43+
}
44+
45+
s.s = append(s.s[:idx], s.s[idx+1:]...)
46+
47+
return true
48+
}
49+
50+
func (s *Slice[T]) Clear() (removed int) {
51+
s.m.Lock()
52+
defer s.m.Unlock()
53+
54+
if s.s == nil {
55+
return 0
56+
}
57+
58+
l := len(s.s)
59+
s.s = s.s[:0]
60+
61+
return l
62+
}

internal/xsync/slice_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package xsync
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/require"
7+
)
8+
9+
func TestSlice(t *testing.T) {
10+
var s Slice[int]
11+
require.Equal(t, 0, s.Size())
12+
require.Equal(t, 0, s.Clear())
13+
s.Append(1)
14+
require.Equal(t, 1, s.Size())
15+
s.Range(func(idx int, v int) bool {
16+
require.Equal(t, 0, idx)
17+
require.Equal(t, 1, v)
18+
19+
return true
20+
})
21+
require.False(t, s.Remove(1))
22+
s.Append(2)
23+
var rangeFuncCounter int
24+
s.Range(func(idx int, v int) bool {
25+
rangeFuncCounter++
26+
27+
return false
28+
})
29+
require.Equal(t, 1, rangeFuncCounter)
30+
require.True(t, s.Remove(1))
31+
require.Equal(t, 1, s.Clear())
32+
}

0 commit comments

Comments
 (0)