94 lines
1.4 KiB
Go
94 lines
1.4 KiB
Go
package ptr
|
|
|
|
// slice-based implementation
|
|
|
|
type sliceseq[V any] []V
|
|
|
|
type sptr[V any] struct {
|
|
seq *sliceseq[V]
|
|
offset int
|
|
}
|
|
|
|
func newSliceSeq[V any]() *sliceseq[V] {
|
|
return &sliceseq[V]{}
|
|
}
|
|
|
|
func NewSlice[V any]() *sptr[V] {
|
|
return &sptr[V]{
|
|
seq: newSliceSeq[V](),
|
|
offset: -1,
|
|
}
|
|
}
|
|
|
|
// Ptr methods
|
|
|
|
func (p *sptr[V]) Append(v V) Ptr[V] {
|
|
*p.seq = append(*p.seq, v)
|
|
p.offset = len(*p.seq) - 1
|
|
return p
|
|
}
|
|
|
|
func (p *sptr[V]) Insert(v V, pos int) Ptr[V] {
|
|
lidx := len(*p.seq) - 1
|
|
if lidx < pos {
|
|
return p.Append(v)
|
|
}
|
|
*p.seq = append(*p.seq, (*p.seq)[lidx])
|
|
for i := lidx; i > pos; i -= 1 {
|
|
(*p.seq)[i] = (*p.seq)[i-1]
|
|
}
|
|
(*p.seq)[pos] = v
|
|
p.offset = pos
|
|
return p
|
|
}
|
|
|
|
func (p *sptr[V]) Next() Ptr[V] {
|
|
if p.offset < len(*p.seq)-1 {
|
|
p.offset += 1
|
|
return p
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *sptr[V]) Value() V {
|
|
return (*p.seq)[p.offset]
|
|
}
|
|
|
|
func (p *sptr[V]) Set(v V) Ptr[V] {
|
|
(*p.seq)[p.offset] = v
|
|
return p
|
|
}
|
|
|
|
func (p *sptr[V]) Size() int {
|
|
return len(*p.seq)
|
|
}
|
|
|
|
func (p *sptr[V]) Started() bool {
|
|
return p.offset >= 0
|
|
}
|
|
|
|
func (p *sptr[V]) Seek(i int) Ptr[V] {
|
|
p.offset = i
|
|
return p
|
|
}
|
|
|
|
func (p *sptr[V]) Reset() Ptr[V] {
|
|
p.offset = -1
|
|
return p
|
|
}
|
|
|
|
func (p *sptr[V]) Clone() Ptr[V] {
|
|
return &sptr[V]{
|
|
seq: p.seq,
|
|
offset: p.offset,
|
|
}
|
|
}
|
|
|
|
func (p *sptr[V]) New() Ptr[V] {
|
|
return New[V](p)
|
|
}
|
|
|
|
func (p *sptr[V]) Copy() Ptr[V] {
|
|
np := NewSlice[V]()
|
|
return Copy[V](p, np)
|
|
}
|