Add slices package

This commit is contained in:
Diego Fernando Carrión 2021-08-29 20:10:31 +02:00
parent 6a233fb76c
commit 05d364480a

57
slices/slices.go Normal file
View 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()
}