gitee.com/quant1x/gox@v1.21.2/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 (
     8  	"gitee.com/quant1x/gox/util/internal"
     9  )
    10  
    11  func assertIteratorImplementation() {
    12  	var _ internal.IteratorWithIndex = (*Iterator)(nil)
    13  }
    14  
    15  // Iterator holding the iterator's state
    16  type Iterator struct {
    17  	list    *List
    18  	index   int
    19  	element *element
    20  }
    21  
    22  // Iterator returns a stateful iterator whose values can be fetched by an index.
    23  func (list *List) Iterator() Iterator {
    24  	return Iterator{list: list, index: -1, element: nil}
    25  }
    26  
    27  // Next moves the iterator to the next element and returns true if there was a next element in the container.
    28  // If Next() returns true, then next element's index and value can be retrieved by Index() and Value().
    29  // If Next() was called for the first time, then it will point the iterator to the first element if it exists.
    30  // Modifies the state of the iterator.
    31  func (iterator *Iterator) Next() bool {
    32  	if iterator.index < iterator.list.size {
    33  		iterator.index++
    34  	}
    35  	if !iterator.list.withinRange(iterator.index) {
    36  		iterator.element = nil
    37  		return false
    38  	}
    39  	if iterator.index == 0 {
    40  		iterator.element = iterator.list.first
    41  	} else {
    42  		iterator.element = iterator.element.next
    43  	}
    44  	return true
    45  }
    46  
    47  // Value returns the current element's value.
    48  // Does not modify the state of the iterator.
    49  func (iterator *Iterator) Value() interface{} {
    50  	return iterator.element.value
    51  }
    52  
    53  // Index returns the current element's index.
    54  // Does not modify the state of the iterator.
    55  func (iterator *Iterator) Index() int {
    56  	return iterator.index
    57  }
    58  
    59  // Begin resets the iterator to its initial state (one-before-first)
    60  // Call Next() to fetch the first element if any.
    61  func (iterator *Iterator) Begin() {
    62  	iterator.index = -1
    63  	iterator.element = nil
    64  }
    65  
    66  // First moves the iterator to the first element and returns true if there was a first element in the container.
    67  // If First() returns true, then first element's index and value can be retrieved by Index() and Value().
    68  // Modifies the state of the iterator.
    69  func (iterator *Iterator) First() bool {
    70  	iterator.Begin()
    71  	return iterator.Next()
    72  }