Add slices package
This commit is contained in:
parent
6a233fb76c
commit
05d364480a
57
slices/slices.go
Normal file
57
slices/slices.go
Normal file
@ -0,0 +1,57 @@
|
||||
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
|
||||
}
|
||||
|
||||
func (ps *PtrSlice) Incr() {
|
||||
ps.idx++
|
||||
ps.current = ps.slice.Index(ps.idx).Interface()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
Loading…
Reference in New Issue
Block a user