-
Notifications
You must be signed in to change notification settings - Fork 0
/
assign2.go
145 lines (110 loc) · 2.33 KB
/
assign2.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package jq
import (
"fmt"
"nikand.dev/go/cbor"
)
type (
Assign struct {
L FilterPath
R Filter
Relative bool
rnext bool
base NodePath
path NodePath
arr []Off
}
assignState struct {
off Off
st, i, end int
}
)
func NewAssign(l FilterPath, r Filter) *Assign { return &Assign{L: l, R: r} }
func NewUpdateAssign(l FilterPath, r Filter) *Assign { return &Assign{L: l, R: r, Relative: true} }
func (f *Assign) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
if !next {
f.rnext = false
f.base = f.base[:0]
f.path = f.path[:0]
}
var val Off
for !f.Relative {
val, more, err = f.R.ApplyTo(b, off, next)
if err != nil {
return off, false, err
}
if !more && val == None {
return None, false, nil
}
if val == None {
next = more
continue
}
break
}
var lnext bool
for {
var field Off
// log.Printf("staring assign loop %v %x [%x] %v", next, f.path, at, lnext)
field, f.path, lnext, err = f.L.ApplyToGetPath(b, off, f.path[:0], lnext)
if err != nil {
return off, false, err
}
if field == None {
if !lnext {
break
}
continue
}
if f.Relative {
res, more, err = f.R.ApplyTo(b, field, next)
if err != nil {
return off, false, err
}
} else {
res = val
}
for i := range f.base {
if i == len(f.path) {
break
}
f.path[i].Off = f.base[i].Off
if f.base[i].Index != f.path[i].Index {
break
}
}
f.base = append(f.base[:0], f.path...)
// log.Printf("assign %v#%v %v = %v %v", f.base, field, lnext, res, f.rnext)
br := b.Reader()
bw := b.Writer()
for at := len(f.base) - 1; at >= 0; at-- {
tag := br.Tag(f.base[at].Off)
val := csel(tag == cbor.Map, 1, 0)
index := f.base[at].Index
index = csel(tag == cbor.Map, index*2, index)
f.arr = br.ArrayMap(f.base[at].Off, f.arr[:0])
if res != None {
// if f.arr[index+val] == res {
// continue
// }
f.arr[index+val] = res
} else {
copy(f.arr[index:], f.arr[index+1+val:])
f.arr = f.arr[:len(f.arr)-1-val]
}
res = bw.ArrayMap(tag, f.arr)
f.base[at].Off = res
}
// log.Printf("assigg %v#%v", f.base, field)
if !lnext {
break
}
}
return res, more, nil
}
func (f *Assign) String() string {
op := "="
if f.Relative {
op = "|="
}
return fmt.Sprintf("%v %s %v", f.L, op, f.R)
}