github.com/mymmsc/gox@v1.3.33/util/singlylinkedlist/iterator.go (about) 1 // Copyright (c) 2015, Emir Pasic. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package singlylinkedlist 6 7 import "github.com/mymmsc/gox/util" 8 9 func assertIteratorImplementation() { 10 var _ util.IteratorWithIndex = (*Iterator)(nil) 11 } 12 13 // Iterator holding the iterator's state 14 type Iterator struct { 15 list *List 16 index int 17 element *element 18 } 19 20 // Iterator returns a stateful iterator whose values can be fetched by an index. 21 func (list *List) Iterator() Iterator { 22 return Iterator{list: list, index: -1, element: nil} 23 } 24 25 // Next moves the iterator to the next element and returns true if there was a next element in the container. 26 // If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). 27 // If Next() was called for the first time, then it will point the iterator to the first element if it exists. 28 // Modifies the state of the iterator. 29 func (iterator *Iterator) Next() bool { 30 if iterator.index < iterator.list.size { 31 iterator.index++ 32 } 33 if !iterator.list.withinRange(iterator.index) { 34 iterator.element = nil 35 return false 36 } 37 if iterator.index == 0 { 38 iterator.element = iterator.list.first 39 } else { 40 iterator.element = iterator.element.next 41 } 42 return true 43 } 44 45 // Value returns the current element's value. 46 // Does not modify the state of the iterator. 47 func (iterator *Iterator) Value() interface{} { 48 return iterator.element.value 49 } 50 51 // Index returns the current element's index. 52 // Does not modify the state of the iterator. 53 func (iterator *Iterator) Index() int { 54 return iterator.index 55 } 56 57 // Begin resets the iterator to its initial state (one-before-first) 58 // Call Next() to fetch the first element if any. 59 func (iterator *Iterator) Begin() { 60 iterator.index = -1 61 iterator.element = nil 62 } 63 64 // First moves the iterator to the first element and returns true if there was a first element in the container. 65 // If First() returns true, then first element's index and value can be retrieved by Index() and Value(). 66 // Modifies the state of the iterator. 67 func (iterator *Iterator) First() bool { 68 iterator.Begin() 69 return iterator.Next() 70 }