66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
package ds
|
|
|
|
type ListRing[T any, L List[*T]] struct {
|
|
list L
|
|
current int
|
|
}
|
|
|
|
var _ Ring[int] = &ListRing[int, List[*int]]{}
|
|
|
|
func NewListRing[T any, L List[*T]](list L, size int) *ListRing[T, L] {
|
|
preAllocList[*T, List[*T]](list, nil, size)
|
|
return &ListRing[T, L]{
|
|
list: list,
|
|
current: 0,
|
|
}
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Next() Ring[T] {
|
|
return &ListRing[T, L]{
|
|
list: r.list,
|
|
current: modAbs(r.current+1, r.list.Size()),
|
|
}
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Prev() Ring[T] {
|
|
return &ListRing[T, L]{
|
|
list: r.list,
|
|
current: modAbs(r.current-1, r.list.Size()),
|
|
}
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Set(v T) {
|
|
r.list.Set(r.current, &v)
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Has() bool {
|
|
return r.list.Get(r.current) != nil
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Get() (T, bool) {
|
|
if !r.Has() {
|
|
return *new(T), false
|
|
}
|
|
return *r.list.Get(r.current), true
|
|
}
|
|
|
|
func (r *ListRing[T, L]) GetOrDefault(defaultValue T) T {
|
|
value, ok := r.Get()
|
|
if !ok {
|
|
return defaultValue
|
|
}
|
|
return value
|
|
}
|
|
|
|
func (r *ListRing[T, L]) Each(f func(value *T)) {
|
|
var t Ring[T] = r
|
|
for i := 0; i < r.list.Size(); i++ {
|
|
if value, ok := t.Get(); ok {
|
|
f(&value)
|
|
} else {
|
|
f(nil)
|
|
}
|
|
t = t.Next()
|
|
}
|
|
}
|