Debian Codegraph @

dstream/segment.go

raw symbols SCIP
1 package dstream
2
3 import "fmt"
4
5 type segmentedData struct {
6 xform
7
8 // Variables whose changing values define the segments
9 vars []string
10
11 // Positions of the variables in vars
12 vpos []int
13
14 stash []interface{}
15
16 // Beginning/end of the current segment
17 pos int
18
19 // true if there is no more data to read from the source; this
20 // does not necessarily mean that there is no more data to
21 // yield.
22 done bool
23 }
24
25 // Segment restructures the chunks of a Dstream so that chunk
26 // boundaries are determined by any change in the consecutive values
27 // of a specified set of variables.
28 func Segment(data Dstream, vars ...string) Dstream {
29 s := &segmentedData{
30 xform: xform{
31 source: data,
32 },
33 vars: vars,
34 }
35 s.init()
36
37 return s
38 }
39
40 func (sd *segmentedData) init() {
41
42 // Get the positions of the variables that define the
43 // segments.
44 sd.names = sd.source.Names()
45 mp := make(map[string]int)
46 for k, v := range sd.names {
47 mp[v] = k
48 }
49 var vpos []int
50 for _, v := range sd.vars {
51 vpos = append(vpos, mp[v])
52 }
53 sd.vpos = vpos
54
55 nvar := sd.source.NumVar()
56 sd.bdata = make([]interface{}, nvar)
57 sd.stash = make([]interface{}, nvar)
58
59 sd.source.Next()
60 sd.setb()
61 }
62
63 // setb sets the pointers in bdata to point to the current source data.
64 func (sd *segmentedData) setb() {
65 nvar := sd.source.NumVar()
66 for j := 0; j < nvar; j++ {
67 sd.bdata[j] = sd.source.GetPos(j)
68 }
69 }
70
71 func (sd *segmentedData) Get(na string) interface{} {
72
73 if sd.namepos == nil {
74 sd.setNamePos()
75 }
76
77 pos, ok := sd.namepos[na]
78 if !ok {
79 msg := fmt.Sprintf("Variable '%s' not found", na)
80 panic(msg)
81 }
82 return sd.GetPos(pos)
83 }
84
85 func (sd *segmentedData) Reset() {
86 sd.xform.Reset()
87 sd.pos = 0
88 sd.source.Next()
89 sd.setb()
90 sd.done = false
91 }
92
93 func (sd *segmentedData) Next() bool {
94
95 // Stash contains at most one group.
96 truncate(sd.stash)
97
98 if ilen(sd.bdata[0]) == 0 && sd.done {
99 return false
100 } else if sd.done {
101 truncate(sd.bdata)
102 }
103
104 // Cut off the previous group, and find the end of the current
105 // group.
106 sd.leftsliceb(sd.pos)
107 sd.pos = sd.findSegment(0)
108
109 // Found a complete group in the current chunk.
110 if sd.pos != -1 {
111 return true
112 }
113
114 sd.pos = 0
115 sd.setstash()
116
117 // Get a complete group in the stash, keep reading until we
118 // have somthing to return.
119 for {
120 f := sd.source.Next()
121
122 if !f {
123 sd.done = true
124
125 // No more data, whatever is left in bdata is
126 // the last segment, or we are done if adata
127 // is empty.
128 return ilen(sd.bdata[0]) > 0
129 }
130 sd.setb()
131
132 fd := sd.fixstash()
133
134 if fd {
135 return true
136 }
137 }
138 }