From bd68ebb0474167d436d5fe58cd96289dee419b88 Mon Sep 17 00:00:00 2001 From: hunter-bera <133678627+hunter-bera@users.noreply.github.com> Date: Wed, 3 Jul 2024 17:15:53 -0400 Subject: [PATCH] add rwlist --- tools/rwstore/rwlist.go | 42 +++++++++++++++++++++++++++++++ tools/{rwmap => rwstore}/rwmap.go | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 tools/rwstore/rwlist.go rename tools/{rwmap => rwstore}/rwmap.go (98%) diff --git a/tools/rwstore/rwlist.go b/tools/rwstore/rwlist.go new file mode 100644 index 0000000..4df3cef --- /dev/null +++ b/tools/rwstore/rwlist.go @@ -0,0 +1,42 @@ +package rwstore + +import "sync" + +type RWList[V any] struct { + a []V + sync.RWMutex +} + +func NewRWList[V any]() *RWList[V] { + return &RWList[V]{ + a: make([]V, 0), + } +} + +func (rw *RWList[V]) Get(index int) (V, bool) { + rw.RLock() + defer rw.RUnlock() + if index < 0 || index >= len(rw.a) { + var zero V + return zero, false + } + return rw.a[index], true +} + +func (rw *RWList[V]) Replace(newList []V) { + rw.Lock() + rw.a = newList + rw.Unlock() +} + +func (rw *RWList[V]) Append(value V) { + rw.Lock() + rw.a = append(rw.a, value) + rw.Unlock() +} + +func (rw *RWList[V]) Copy() []V { + rw.RLock() + defer rw.RUnlock() + return append([]V(nil), rw.a...) +} diff --git a/tools/rwmap/rwmap.go b/tools/rwstore/rwmap.go similarity index 98% rename from tools/rwmap/rwmap.go rename to tools/rwstore/rwmap.go index 3ddce67..4544b11 100644 --- a/tools/rwmap/rwmap.go +++ b/tools/rwstore/rwmap.go @@ -1,4 +1,4 @@ -package rwmap +package rwstore import ( "sync"