Skip to content

Commit

Permalink
refactor: 迁移 concurrent.Slice 至 listings.SyncSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
kercylan98 committed Jan 12, 2024
1 parent e3475c6 commit e28a5a2
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 81 deletions.
2 changes: 1 addition & 1 deletion utils/collection/listings/priority_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
61 changes: 61 additions & 0 deletions utils/collection/listings/sync_slice.go
Original file line number Diff line number Diff line change
@@ -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)
}
59 changes: 0 additions & 59 deletions utils/concurrent/slice.go

This file was deleted.

21 changes: 0 additions & 21 deletions utils/concurrent/slice_option.go

This file was deleted.

0 comments on commit e28a5a2

Please sign in to comment.