github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/cols/synccol/iterator.go (about)

     1  package synccol
     2  
     3  import (
     4  	"github.com/djordje200179/extendedlibrary/datastructures/cols"
     5  	"sync"
     6  )
     7  
     8  // Iterator is a wrapper around a cols.Iterator that provides thread-safe
     9  // access to the underlying collection.
    10  type Iterator[T any] struct {
    11  	colIt cols.Iterator[T]
    12  
    13  	mutex *sync.RWMutex
    14  }
    15  
    16  // Valid returns true if the iterator is currently pointing to a valid element.
    17  func (it Iterator[T]) Valid() bool {
    18  	return it.colIt.Valid()
    19  }
    20  
    21  // Move moves the iterator to the next element.
    22  func (it Iterator[T]) Move() {
    23  	it.colIt.Move()
    24  }
    25  
    26  // GetRef returns a reference to the current element.
    27  func (it Iterator[T]) GetRef() *T {
    28  	it.mutex.RLock()
    29  	defer it.mutex.RUnlock()
    30  
    31  	return it.colIt.GetRef()
    32  }
    33  
    34  // Get returns the current element.
    35  func (it Iterator[T]) Get() T {
    36  	it.mutex.RLock()
    37  	defer it.mutex.RUnlock()
    38  
    39  	return it.colIt.Get()
    40  }
    41  
    42  // Set sets the current element.
    43  func (it Iterator[T]) Set(value T) {
    44  	it.mutex.Lock()
    45  	defer it.mutex.Unlock()
    46  
    47  	it.colIt.Set(value)
    48  }
    49  
    50  // InsertBefore inserts the specified element before the current element.
    51  func (it Iterator[T]) InsertBefore(value T) {
    52  	it.mutex.Lock()
    53  	defer it.mutex.Unlock()
    54  
    55  	it.colIt.InsertBefore(value)
    56  }
    57  
    58  // InsertAfter inserts the specified element after the current element.
    59  func (it Iterator[T]) InsertAfter(value T) {
    60  	it.mutex.Lock()
    61  	defer it.mutex.Unlock()
    62  
    63  	it.colIt.InsertAfter(value)
    64  }
    65  
    66  // Remove removes the current element.
    67  func (it Iterator[T]) Remove() {
    68  	it.mutex.Lock()
    69  	defer it.mutex.Unlock()
    70  
    71  	it.colIt.Remove()
    72  }
    73  
    74  // Index returns the current index.
    75  func (it Iterator[T]) Index() int {
    76  	return it.colIt.Index()
    77  }