refactor: 迁移 concurrent.Slice 至 listings.SyncSlice

This commit is contained in:
kercylan98 2024-01-12 12:29:13 +08:00
parent e3475c6c07
commit e28a5a259f
4 changed files with 62 additions and 81 deletions

View File

@ -129,7 +129,7 @@ func (slf *PrioritySlice[V]) RangePriority(action func(index int, priority int)
})
}
// Slice 返回切片
// SyncSlice 返回切片
func (slf *PrioritySlice[V]) Slice() []V {
var vs []V
for _, item := range slf.items {

View File

@ -0,0 +1,61 @@
package listings
import (
"github.com/kercylan98/minotaur/utils/collection"
"sync"
)
// NewSyncSlice 创建一个 SyncSlice
func NewSyncSlice[V any](length, cap int) *SyncSlice[V] {
s := &SyncSlice[V]{}
if length > 0 || cap > 0 {
s.data = make([]V, length, cap)
}
return s
}
// SyncSlice 是基于 sync.RWMutex 实现的线程安全的 slice
type SyncSlice[V any] struct {
rw sync.RWMutex
data []V
}
func (slf *SyncSlice[V]) Get(index int) V {
slf.rw.RLock()
defer slf.rw.RUnlock()
return slf.data[index]
}
func (slf *SyncSlice[V]) GetWithRange(start, end int) []V {
return slf.data[start:end]
}
func (slf *SyncSlice[V]) Set(index int, value V) {
slf.rw.Lock()
slf.data[index] = value
slf.rw.Unlock()
}
func (slf *SyncSlice[V]) Append(values ...V) {
slf.rw.Lock()
slf.data = append(slf.data, values...)
slf.rw.Unlock()
}
func (slf *SyncSlice[V]) Release() {
slf.rw.Lock()
slf.data = nil
slf.rw.Unlock()
}
func (slf *SyncSlice[V]) Clear() {
slf.rw.Lock()
slf.data = slf.data[:0]
slf.rw.Unlock()
}
func (slf *SyncSlice[V]) GetData() []V {
slf.rw.Lock()
defer slf.rw.Unlock()
return collection.CloneSlice(slf.data)
}

View File

@ -1,59 +0,0 @@
package concurrent
import (
"github.com/kercylan98/minotaur/utils/collection"
"sync"
)
func NewSlice[T any](options ...SliceOption[T]) *Slice[T] {
s := &Slice[T]{}
for _, option := range options {
option(s)
}
return s
}
type Slice[T any] struct {
rw sync.RWMutex
data []T
}
func (slf *Slice[T]) Get(index int) T {
slf.rw.RLock()
defer slf.rw.RUnlock()
return slf.data[index]
}
func (slf *Slice[T]) GetWithRange(start, end int) []T {
return slf.data[start:end]
}
func (slf *Slice[T]) Set(index int, value T) {
slf.rw.Lock()
slf.data[index] = value
slf.rw.Unlock()
}
func (slf *Slice[T]) Append(values ...T) {
slf.rw.Lock()
slf.data = append(slf.data, values...)
slf.rw.Unlock()
}
func (slf *Slice[T]) Release() {
slf.rw.Lock()
slf.data = nil
slf.rw.Unlock()
}
func (slf *Slice[T]) Clear() {
slf.rw.Lock()
slf.data = slf.data[:0]
slf.rw.Unlock()
}
func (slf *Slice[T]) GetData() []T {
slf.rw.Lock()
defer slf.rw.Unlock()
return collection.CloneSlice(slf.data)
}

View File

@ -1,21 +0,0 @@
package concurrent
type SliceOption[T any] func(slice *Slice[T])
func WithSliceLen[T any](len int) SliceOption[T] {
return func(slice *Slice[T]) {
slice.data = make([]T, len)
}
}
func WithSliceCap[T any](cap int) SliceOption[T] {
return func(slice *Slice[T]) {
slice.data = make([]T, 0, cap)
}
}
func WithSliceLenCap[T any](len, cap int) SliceOption[T] {
return func(slice *Slice[T]) {
slice.data = make([]T, len, cap)
}
}