File: iterable.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,118 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 (
	"sync"

	"github.com/anacrolix/missinggo"
)

type Iterable interface {
	Iter(Callback)
}

type iterator struct {
	it      Iterable
	ch      chan interface{}
	value   interface{}
	ok      bool
	mu      sync.Mutex
	stopped missinggo.Event
}

func NewIterator(it Iterable) (ret *iterator) {
	ret = &iterator{
		it: it,
		ch: make(chan interface{}),
	}
	go func() {
		// Have to do this in a goroutine, because the interface is synchronous.
		it.Iter(func(value interface{}) bool {
			select {
			case ret.ch <- value:
				return true
			case <-ret.stopped.LockedChan(&ret.mu):
				return false
			}
		})
		close(ret.ch)
		ret.mu.Lock()
		ret.stopped.Set()
		ret.mu.Unlock()
	}()
	return
}

func (me *iterator) Value() interface{} {
	if !me.ok {
		panic("no value")
	}
	return me.value
}

func (me *iterator) Next() bool {
	me.value, me.ok = <-me.ch
	return me.ok
}

func (me *iterator) Stop() {
	me.mu.Lock()
	me.stopped.Set()
	me.mu.Unlock()
}

func IterableAsSlice(it Iterable) (ret []interface{}) {
	it.Iter(func(value interface{}) bool {
		ret = append(ret, value)
		return true
	})
	return
}