github.com/iotexproject/iotex-core@v1.14.1-rc1/state/iterator.go (about) 1 // Copyright (c) 2020 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package state 7 8 import ( 9 "github.com/pkg/errors" 10 ) 11 12 // ErrOutOfBoundary defines an error when the index in the iterator is out of boundary 13 var ErrOutOfBoundary = errors.New("index is out of boundary") 14 15 // ErrNilValue is an error when value is nil 16 var ErrNilValue = errors.New("value is nil") 17 18 // Iterator defines an interator to read a set of states 19 type Iterator interface { 20 // Size returns the size of the iterator 21 Size() int 22 // Next deserializes the next state in the iterator 23 Next(interface{}) error 24 } 25 26 type iterator struct { 27 states [][]byte 28 index int 29 } 30 31 // NewIterator returns an interator given a list of serialized states 32 func NewIterator(states [][]byte) Iterator { 33 return &iterator{index: 0, states: states} 34 } 35 36 func (it *iterator) Size() int { 37 return len(it.states) 38 } 39 40 func (it *iterator) Next(s interface{}) error { 41 i := it.index 42 if i >= len(it.states) { 43 return ErrOutOfBoundary 44 } 45 it.index = i + 1 46 if it.states[i] == nil { 47 return ErrNilValue 48 } 49 return Deserialize(s, it.states[i]) 50 }