2021-08-29 14:10:31 -04:00
|
|
|
package slices
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
errors "golang.org/x/xerrors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PtrSlice struct {
|
|
|
|
slice reflect.Value
|
|
|
|
current interface{}
|
|
|
|
t reflect.Type
|
|
|
|
idx int
|
|
|
|
length int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPtrSlice(s interface{}) (*PtrSlice, error) {
|
|
|
|
ps := &PtrSlice{}
|
|
|
|
ps.t = reflect.TypeOf(s)
|
|
|
|
if ps.t.Kind() != reflect.Slice {
|
|
|
|
return nil, errors.New("Attempted to create a PtrSlice from non-Slice")
|
|
|
|
}
|
|
|
|
ps.slice = reflect.ValueOf(s)
|
|
|
|
ps.length = ps.slice.Len()
|
|
|
|
ps.idx = 0
|
|
|
|
ps.current = ps.slice.Index(ps.idx).Interface()
|
|
|
|
return ps, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func MustPtrSlice(s interface{}) *PtrSlice {
|
|
|
|
ps, err := NewPtrSlice(s)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return ps
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *PtrSlice) Val() interface{} {
|
|
|
|
return ps.current
|
|
|
|
}
|
|
|
|
|
2021-08-29 14:29:48 -04:00
|
|
|
func (ps *PtrSlice) Next() {
|
|
|
|
if ps.idx < ps.length-1 {
|
|
|
|
ps.idx++
|
|
|
|
ps.current = ps.slice.Index(ps.idx).Interface()
|
|
|
|
} else if ps.idx == ps.length-1 {
|
|
|
|
ps.idx++
|
|
|
|
ps.current = nil
|
|
|
|
}
|
2021-08-29 14:10:31 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *PtrSlice) Len() int {
|
|
|
|
return ps.length
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *PtrSlice) Offset(offset int) interface{} {
|
|
|
|
return ps.slice.Index(ps.idx + offset).Interface()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *PtrSlice) Get(idx int) interface{} {
|
|
|
|
return ps.slice.Index(idx).Interface()
|
|
|
|
}
|