Debian Codegraph @

lib/iterator/index.go

raw
1 package iterator
2
3 // IndexProvider implements a subset of the Iterator interface
4 type IndexProvider interface {
5 StartIndex() int
6 EndIndex() int
7 }
8
9 // FixBounds will force the index i to either its lower- or upper-bound value
10 // if out-of-bound
11 func FixBounds(i, lower, upper int) int {
12 switch {
13 case i > upper:
14 i = upper
15 case i < lower:
16 i = lower
17 }
18 return i
19 }
20
21 // WrapBounds will wrap the index i around its upper- or lower-bound if
22 // out-of-bound
23 func WrapBounds(i, lower, upper int) int {
24 if upper <= 0 {
25 return lower
26 }
27 switch {
28 case i > upper:
29 i = lower + (i-upper-1)%upper
30 case i < lower:
31 i = upper - (lower-i-1)%upper
32 }
33 return i
34 }
35
36 type BoundsCheckFunc func(int, int, int) int
37
38 // MoveIndex moves the index variable idx forward by delta steps and ensures
39 // that the boundary policy as defined by the CheckBoundsFunc is enforced.
40 //
41 // If CheckBoundsFunc is nil, fix boundary checks are performed.
42 func MoveIndex(idx, delta int, indexer IndexProvider, cb BoundsCheckFunc) int {
43 lower, upper := indexer.StartIndex(), indexer.EndIndex()
44 sign := 1
45 if upper < lower {
46 lower, upper = upper, lower
47 sign = -1
48 }
49 result := idx + sign*delta
50 if cb == nil {
51 return FixBounds(result, lower, upper)
52 }
53 return cb(result, lower, upper)
54 }