-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentry_reader.go
82 lines (73 loc) · 1.74 KB
/
entry_reader.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
package startf
import (
"fmt"
"io"
"github.com/qri-io/dataset"
"github.com/qri-io/dataset/dsio"
"github.com/qri-io/starlib/util"
"go.starlark.net/starlark"
)
// EntryReader implements the dsio.EntryReader interface for starlark.Iterable's
type EntryReader struct {
i int
st *dataset.Structure
iter starlark.Iterator
data starlark.Value
}
// NewEntryReader creates a new Entry Reader
func NewEntryReader(st *dataset.Structure, iter starlark.Iterable) *EntryReader {
return &EntryReader{
st: st,
data: iter.(starlark.Value),
iter: iter.Iterate(),
}
}
// Structure gives this reader's structure
func (r *EntryReader) Structure() *dataset.Structure {
return r.st
}
// ReadEntry reads one entry from the reader
func (r *EntryReader) ReadEntry() (e dsio.Entry, err error) {
// Read next element (key for object, value for array).
var next starlark.Value
if !r.iter.Next(&next) {
r.iter.Done()
return e, io.EOF
}
// Handle array entry.
tlt, err := dsio.GetTopLevelType(r.st)
if err != nil {
return
}
if tlt == "array" {
e.Index = r.i
r.i++
e.Value, err = util.Unmarshal(next)
if err != nil {
fmt.Printf("reading error: %s\n", err.Error())
}
return
}
// Handle object entry. Assume key is a string.
var ok bool
e.Key, ok = starlark.AsString(next)
if !ok {
fmt.Printf("key error: %s\n", next)
}
// Lookup the corresponding value for the key.
dict := r.data.(*starlark.Dict)
value, ok, err := dict.Get(next)
if err != nil {
fmt.Printf("reading error: %s\n", err.Error())
}
e.Value, err = util.Unmarshal(value)
if err != nil {
fmt.Printf("reading error: %s\n", err.Error())
}
return
}
// Close finalizes the reader
func (r *EntryReader) Close() error {
// TODO (b5): consume & close iterator
return nil
}