-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilter.go
110 lines (91 loc) · 1.99 KB
/
filter.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package sun
import (
"fmt"
"go.starlark.net/starlark"
)
type filterFunc = func(x starlark.Value) (starlark.Value, error)
type filterIter struct {
function filterFunc
iterator starlark.Iterator
}
func (f filterIter) Next(p *starlark.Value) bool {
var x starlark.Value
for {
if !f.iterator.Next(&x) {
return false
}
v, err := f.function(x)
if err != nil {
return false
}
if v.Truth() {
*p = x
return true
}
}
}
func (f filterIter) Done() {
f.iterator.Done()
}
type filterObject struct {
function filterFunc
functionFreeze starlark.Value
iterable starlark.Iterable
}
func (f filterObject) String() string {
return "<filter object>"
}
func (f filterObject) Type() string {
return "filter"
}
func (f filterObject) Freeze() {
f.functionFreeze.Freeze()
f.iterable.Freeze()
}
func (f filterObject) Truth() starlark.Bool {
return starlark.True
}
func (f filterObject) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: filter")
}
func (f filterObject) Iterate() starlark.Iterator {
return filterIter{
function: f.function,
iterator: f.iterable.Iterate(),
}
}
func filter(
thread *starlark.Thread,
b *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
var (
function filterFunc
iterable starlark.Iterable
)
if err := wantArgs(b.Name(), args, kwargs, 2); err != nil {
return nil, err
}
switch fn := args[0].(type) {
case starlark.Callable:
function = func(x starlark.Value) (starlark.Value, error) {
return starlark.Call(thread, fn, starlark.Tuple{x}, nil)
}
case starlark.NoneType:
function = func(x starlark.Value) (starlark.Value, error) {
return x.Truth(), nil
}
default:
return nil, fmt.Errorf("got %s, want callable", fn.Type())
}
iterable, ok := args[1].(starlark.Iterable)
if !ok {
return nil, fmt.Errorf("got %s, want iterable", args[1].Type())
}
return &filterObject{
function: function,
functionFreeze: args[0],
iterable: iterable,
}, nil
}