github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/niterator/onearr/iterator.go (about)

     1  package onearr
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/egonelbre/exp/niterator/shape"
     7  )
     8  
     9  type Index struct {
    10  	Track  uint32
    11  	Shape  uint32
    12  	Stride uint32
    13  }
    14  
    15  type Iterator struct {
    16  	*shape.AP
    17  
    18  	Track     []Index
    19  	NextIndex uint32
    20  	Done      bool
    21  }
    22  
    23  func NewIterator(ap *shape.AP) *Iterator {
    24  	track := make([]Index, len(ap.Shape))
    25  	for i := range ap.Shape {
    26  		track[i].Shape = uint32(ap.Shape[i])
    27  		track[i].Stride = uint32(ap.Stride[i])
    28  	}
    29  
    30  	return &Iterator{
    31  		AP:    ap,
    32  		Track: track,
    33  	}
    34  }
    35  
    36  func (it *Iterator) IsDone() bool {
    37  	return it.Done
    38  }
    39  
    40  func (it *Iterator) Next() (int, error) {
    41  	if it.Done {
    42  		return 0, io.EOF
    43  	}
    44  
    45  	last := len(it.Track) - 1
    46  	next := it.NextIndex
    47  	result := next
    48  
    49  	// the following 3 lines causes the compiler to perform bounds check here,
    50  	// instead of being done in the loop
    51  	track := it.Track[:last+1]
    52  	for i := last; i >= 0; i-- {
    53  		x := &track[i]
    54  		x.Track++
    55  		if x.Track == x.Shape {
    56  			if i == 0 {
    57  				it.Done = true
    58  			}
    59  			x.Track = 0
    60  			next -= (x.Shape - 1) * x.Stride
    61  			continue
    62  		}
    63  		next += x.Stride
    64  		break
    65  	}
    66  	it.NextIndex = next
    67  	return int(result), nil
    68  }