-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslice.go
46 lines (38 loc) · 876 Bytes
/
slice.go
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
package fungi
import "io"
// SliceStream transforms any slice into a Stream.
func SliceStream[T any](items []T) Stream[T] {
return &slice[T]{
source: items,
}
}
// CollectSlice exhausts any given Stream, putting items into a slice. At the
// end of this operation, io.EOF is not reported as this function is expected to
// read stream until the end anyways.
func CollectSlice[T any](items Stream[T]) (collected []T, err error) {
if items == nil {
return
}
var item T
for err == nil {
if item, err = items.Next(); err == nil {
collected = append(collected, item)
}
}
if err == io.EOF {
err = nil
}
return
}
type slice[T any] struct {
source []T
}
func (s *slice[T]) Next() (item T, err error) {
if len(s.source) == 0 {
err = io.EOF
return
}
item = s.source[0] // get first item
s.source = s.source[1:] // shrink the slice
return
}