From 05d364480a3f4b8cc7e08b74e7d7b7f63ef0f5da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Fernando=20Carri=C3=B3n?= Date: Sun, 29 Aug 2021 20:10:31 +0200 Subject: [PATCH] Add slices package --- slices/slices.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 slices/slices.go diff --git a/slices/slices.go b/slices/slices.go new file mode 100644 index 0000000..7fa4bdf --- /dev/null +++ b/slices/slices.go @@ -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() +}