File: iterator.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 872 kB
  • sloc: makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,261 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package iter

import "github.com/anacrolix/missinggo/slices"

type Iterator interface {
	// Advances to the next value. Returns false if there are no more values.
	// Must be called before the first value.
	Next() bool
	// Returns the current value. Should panic when the iterator is in an
	// invalid state.
	Value() interface{}
	// Ceases iteration prematurely. This should occur implicitly if Next
	// returns false.
	Stop()
}

func ToFunc(it Iterator) Func {
	return func(cb Callback) {
		defer it.Stop()
		for it.Next() {
			if !cb(it.Value()) {
				break
			}
		}
	}
}

type sliceIterator struct {
	slice []interface{}
	value interface{}
	ok    bool
}

func (me *sliceIterator) Next() bool {
	if len(me.slice) == 0 {
		return false
	}
	me.value = me.slice[0]
	me.slice = me.slice[1:]
	me.ok = true
	return true
}

func (me *sliceIterator) Value() interface{} {
	if !me.ok {
		panic("no value; call Next")
	}
	return me.value
}

func (me *sliceIterator) Stop() {}

func Slice(a []interface{}) Iterator {
	return &sliceIterator{
		slice: a,
	}
}

func StringIterator(a string) Iterator {
	return Slice(slices.ToEmptyInterface(a))
}

func ToSlice(f Func) (ret []interface{}) {
	f(func(v interface{}) bool {
		ret = append(ret, v)
		return true
	})
	return
}