-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
585 lines (533 loc) · 12.8 KB
/
ctx.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package dyntpl
import (
"bytes"
"io"
"time"
"github.com/koykov/bytealg"
"github.com/koykov/bytebuf"
"github.com/koykov/byteconv"
"github.com/koykov/inspector"
)
// Ctx is a context object. Contains list of variables available to inspect.
// In addition, has buffers to help develop new helpers without allocations.
type Ctx struct {
// List of context variables and list len.
vars []ctxVar
ln int
// Check square brackets flag.
chQB bool
// Check json quote/escape/encode flags.
chJQ, chHE, chUE, noesc bool
// Internal buffers.
buf []byte
bufS []string
bufI int
bufX any
bufA []any
bufLC []int64
bufMO bytebuf.Chain
bufCB bytebuf.Chain
// Range loop helper.
rl *RangeLoop
// Deferred functions pool.
dfr []func() error
// List of variables taken from ipools and registered to return back.
ipv []ipoolVar
ipvl int
// Break depth.
brkD int
// List of internal byte writers to process include expressions.
w []bytes.Buffer
wl int
// List of internal KV pairs.
kv []KV
kvl int
// External buffers to use in modifier and condition helpers.
BufAcc bytebuf.Accumulative
// todo remove as unused later
// DEPRECATED: use BufAcc instead.
Buf, Buf1, Buf2 bytebuf.Chain
BufB bool
BufI int64
BufU uint64
BufF float64
BufT time.Time
BufX any
Err error
}
// Context variable object.
type ctxVar struct {
key string
val any
// Byte buffer need for special cases when value is a byte slice.
buf []byte
// Special case: var is counter.
cntrF bool
cntr int
ins inspector.Inspector
}
// KV represents key-value pair.
type KV struct {
K []byte
V any
}
var (
// Byte constants.
qbL = []byte("[")
qbR = []byte("]")
dot = []byte(".")
)
// NewCtx makes new context object.
func NewCtx() *Ctx {
ctx := Ctx{
vars: make([]ctxVar, 0),
bufS: make([]string, 0),
Buf: make(bytebuf.Chain, 0),
Buf1: make(bytebuf.Chain, 0),
Buf2: make(bytebuf.Chain, 0),
buf: make([]byte, 0),
bufA: make([]any, 0),
}
return &ctx
}
// Set the variable to context.
// Inspector ins should be corresponded to variable val.
func (ctx *Ctx) Set(key string, val any, ins inspector.Inspector) *Ctx {
for i := 0; i < ctx.ln; i++ {
if ctx.vars[i].key == key {
// Update existing variable.
ctx.vars[i].val = val
ctx.vars[i].ins = ins
return ctx
}
}
// Add new variable.
if ctx.ln < len(ctx.vars) {
// Use existing item in variable list.
ctx.vars[ctx.ln].key = key
ctx.vars[ctx.ln].val = val
ctx.vars[ctx.ln].ins = ins
} else {
// Extend the variable list with new one.
ctx.vars = append(ctx.vars, ctxVar{
key: key,
val: val,
ins: ins,
})
}
// Increase variables count.
ctx.ln++
return ctx
}
// SetStatic sets static variable to context.
func (ctx *Ctx) SetStatic(key string, val any) *Ctx {
ins, err := inspector.GetInspector("static")
if err != nil {
ctx.Err = err
return ctx
}
ctx.Set(key, val, ins)
return ctx
}
// SetBytes sets bytes as static variable.
//
// See Ctx.Set().
// This is a special case to improve speed.
func (ctx *Ctx) SetBytes(key string, val []byte) *Ctx {
ins, err := inspector.GetInspector("static")
if err != nil {
ctx.Err = err
return ctx
}
for i := 0; i < ctx.ln; i++ {
if ctx.vars[i].key == key {
ctx.vars[i].buf = append(ctx.vars[i].buf[:0], val...)
ctx.vars[i].ins = ins
return ctx
}
}
if ctx.ln < len(ctx.vars) {
ctx.vars[ctx.ln].key = key
ctx.vars[ctx.ln].buf = append(ctx.vars[ctx.ln].buf[:0], val...)
ctx.vars[ctx.ln].ins = ins
} else {
v := ctxVar{
key: key,
ins: ins,
}
v.buf = append(v.buf, val...)
ctx.vars = append(ctx.vars, v)
}
ctx.ln++
return ctx
}
// SetString sets string as static variable.
func (ctx *Ctx) SetString(key, val string) *Ctx {
ctx.SetBytes(key, byteconv.S2B(val))
return ctx
}
// SetCounter sets int counter as static variable.
//
// See Ctx.Set().
// This is a special case to support counters.
func (ctx *Ctx) SetCounter(key string, val int) *Ctx {
ins, err := inspector.GetInspector("static")
if err != nil {
ctx.Err = err
return ctx
}
for i := 0; i < ctx.ln; i++ {
if ctx.vars[i].key == key {
ctx.vars[i].cntrF = true
ctx.vars[i].cntr = val
ctx.vars[i].ins = ins
ctx.vars[i].val = nil
ctx.vars[i].buf = ctx.vars[i].buf[:0]
return ctx
}
}
if ctx.ln < len(ctx.vars) {
ctx.vars[ctx.ln].key = key
ctx.vars[ctx.ln].cntrF = true
ctx.vars[ctx.ln].cntr = val
ctx.vars[ctx.ln].ins = ins
ctx.vars[ctx.ln].val = nil
ctx.vars[ctx.ln].buf = ctx.vars[ctx.ln].buf[:0]
} else {
v := ctxVar{
key: key,
cntrF: true,
cntr: val,
ins: ins,
}
ctx.vars = append(ctx.vars, v)
}
ctx.ln++
return ctx
}
// Get arbitrary value from the context by path.
//
// See Ctx.get().
// Path syntax: <ctxVrName>[.<Field>[.<NestedField0>[....<NestedFieldN>]]]
// Examples:
// * user.Bio.Birthday
// * staticVar
func (ctx *Ctx) Get(path string) any {
return ctx.get(byteconv.S2B(path))
}
// GetCounter gets int counter value.
func (ctx *Ctx) GetCounter(key string) int {
rawC := ctx.Get(key)
if rawC == nil {
return 0
}
if i, ok := rawC.(*int); ok {
return *i
}
return 0
}
// BufModOut buffers mod output bytes.
func (ctx *Ctx) BufModOut(buf *any, p []byte) {
ctx.bufMO.Reset().Write(p)
*buf = &ctx.bufMO
}
// BufModStrOut buffers mod output string.
func (ctx *Ctx) BufModStrOut(buf *any, s string) {
ctx.bufMO.Reset().WriteString(s)
*buf = &ctx.bufMO
}
// Defer registers new deferred function.
//
// Function will call after finishing template.
// todo: find a way how to avoid closure allocation.
func (ctx *Ctx) Defer(fn func() error) {
ctx.dfr = append(ctx.dfr, fn)
}
// AcquireFrom receives new variable from given pool and register it to return batch after finish template processing.
func (ctx *Ctx) AcquireFrom(pool string) (any, error) {
v, err := ipoolRegistry.acquire(pool)
if err != nil {
return nil, err
}
if ctx.ipvl < len(ctx.ipv) {
ctx.ipv[ctx.ipvl].key = pool
ctx.ipv[ctx.ipvl].val = v
} else {
ctx.ipv = append(ctx.ipv, ipoolVar{key: pool, val: v})
}
ctx.ipvl++
return v, nil
}
// Reset the context.
//
// Made to use together with pools.
func (ctx *Ctx) Reset() {
for i := 0; i < ctx.ln; i++ {
ctx.vars[i].cntrF = false
ctx.vars[i].val = nil
ctx.vars[i].buf = ctx.vars[i].buf[:0]
}
ctx.ln = 0
for i := 0; i < ctx.wl; i++ {
ctx.w[i].Reset()
}
ctx.wl = 0
ctx.kvl = 0
ctx.Err = nil
ctx.bufX = nil
ctx.BufX = nil
ctx.chQB, ctx.chJQ, ctx.chHE, ctx.chUE = false, false, false, false
ctx.bufS = ctx.bufS[:0]
ctx.bufCB.Reset()
ctx.BufAcc.Reset()
ctx.bufMO.Reset()
ctx.Buf.Reset()
ctx.Buf1.Reset()
ctx.Buf2.Reset()
ctx.buf = ctx.buf[:0]
ctx.bufA = ctx.bufA[:0]
ctx.bufLC = ctx.bufLC[:0]
ctx.brkD = 0
if ctx.rl != nil {
ctx.rl.Reset()
}
ctx.dfr = ctx.dfr[:0]
for i := 0; i < ctx.ipvl; i++ {
_ = ipoolRegistry.release(ctx.ipv[i].key, ctx.ipv[i].val)
ctx.ipv[i].key, ctx.ipv[i].val = "", nil
}
ctx.ipvl = 0
ctx.BufB, ctx.BufI, ctx.BufU, ctx.BufF, ctx.BufX = false, 0, 0, 0, nil
ctx.BufT = time.Time{}
}
// Internal getter.
//
// See Ctx.Get().
func (ctx *Ctx) get(path []byte) any {
// Reset error to avoid catching errors from previous nodes.
ctx.Err = nil
// Special case: check square brackets on counter loops.
// See Ctx.replaceQB().
if ctx.chQB {
path = ctx.replaceQB(path)
}
// Split path to separate words using dot as separator.
// So, path user.Bio.Birthday will convert to []string{"user", "Bio", "Birthday"}
ctx.bufS = ctx.bufS[:0]
ctx.bufS = bytealg.AppendSplitString(ctx.bufS, byteconv.B2S(path), ".", -1)
if len(ctx.bufS) == 0 {
return nil
}
// Look for first path chunk in vars.
for i := 0; i < ctx.ln; i++ {
v := &ctx.vars[i]
if v.key == ctx.bufS[0] {
// Var found.
if v.val == nil && len(v.buf) > 0 {
// Special case: var is a byte slice.
ctx.bufCB.Reset().Write(v.buf)
ctx.bufX = &ctx.bufCB
return ctx.bufX
}
if v.val == nil && v.cntrF {
// Special case: var is a counter.
ctx.bufI = v.cntr
ctx.bufX = &ctx.bufI
return ctx.bufX
}
// Inspect variable using inspector object.
// Give search path as list of split path minus first key, e.g. []string{"Bio", "Birthday"}
ctx.bufX = nil
ctx.Err = v.ins.GetTo(v.val, &ctx.bufX, ctx.bufS[1:]...)
if ctx.Err != nil {
return nil
}
return ctx.bufX
}
}
return nil
}
// Compare method.
func (ctx *Ctx) cmp(path []byte, cond op, right []byte) bool {
// Split path.
ctx.bufS = ctx.bufS[:0]
ctx.bufS = bytealg.AppendSplitString(ctx.bufS, byteconv.B2S(path), ".", -1)
if len(ctx.bufS) == 0 {
return false
}
for i := 0; i < ctx.ln; i++ {
v := &ctx.vars[i]
if v.key == ctx.bufS[0] {
// Compare var with right value using inspector.
if v.cntrF {
ctx.Err = v.ins.Compare(v.cntr, inspector.Op(cond), byteconv.B2S(right), &ctx.BufB, ctx.bufS[1:]...)
} else {
ctx.Err = v.ins.Compare(v.val, inspector.Op(cond), byteconv.B2S(right), &ctx.BufB, ctx.bufS[1:]...)
}
if ctx.Err != nil {
return false
}
return ctx.BufB
}
}
return false
}
func (ctx *Ctx) cmpLC(lc lc, path []byte, cond op, right []byte) bool {
ctx.Err = nil
if ctx.chQB {
path = ctx.replaceQB(path)
}
ctx.bufS = ctx.bufS[:0]
ctx.bufS = bytealg.AppendSplitString(ctx.bufS, byteconv.B2S(path), ".", -1)
if len(ctx.bufS) == 0 {
return false
}
for i := 0; i < ctx.ln; i++ {
v := &ctx.vars[i]
if v.key == ctx.bufS[0] {
switch lc {
case lcLen:
ctx.Err = v.ins.Length(v.val, &ctx.bufI, ctx.bufS[1:]...)
case lcCap:
ctx.Err = v.ins.Capacity(v.val, &ctx.bufI, ctx.bufS[1:]...)
default:
return false
}
if ctx.Err != nil {
return false
}
si := inspector.StaticInspector{}
ctx.BufB = false
ctx.Err = si.Compare(ctx.bufI, inspector.Op(cond), byteconv.B2S(right), &ctx.BufB)
return ctx.BufB
}
}
return false
}
// Range loop method to evaluate expressions like:
// {% for k, v := range user.History %}...{% endfor %}
func (ctx *Ctx) rloop(path []byte, node *node, tpl *Tpl, w io.Writer) {
ctx.bufS = ctx.bufS[:0]
ctx.bufS = bytealg.AppendSplitString(ctx.bufS, byteconv.B2S(path), ".", -1)
if len(ctx.bufS) == 0 {
return
}
for i := 0; i < ctx.ln; i++ {
v := &ctx.vars[i]
if v.key == ctx.bufS[0] {
// Look for free-range loop object in single-ordered list, see RangeLoop.
var rl *RangeLoop
if ctx.rl == nil {
// No range loops, create new one.
ctx.rl = NewRangeLoop(node, tpl, ctx, w)
rl = ctx.rl
} else {
// Move forward over the list while new RL will found.
crl := ctx.rl
for {
if crl.stat == rlFree {
// Found it.
rl = crl
break
}
if crl.stat != rlFree {
// RL is in use, need to go deeper.
if crl.next != nil {
crl = crl.next
continue
} else {
// End of the list, create new free RL and exit from the loop.
crl.next = NewRangeLoop(node, tpl, ctx, w)
rl = crl.next
break
}
}
}
// Prepare RL object.
rl.cntr = 0
rl.node = node
rl.tpl = tpl
rl.ctx = ctx
rl.w = w
}
// Mark RL as inuse and loop over var using inspector.
rl.stat = rlInuse
ctx.Err = v.ins.Loop(v.val, rl, &ctx.buf, ctx.bufS[1:]...)
// Check for-else condition.
if rl.c == 0 && len(node.child) > 1 && node.child[1].typ == typeCondFalse {
child := node.child[1].child
for j := 0; j < len(child); j++ {
ch := &child[j]
if ctx.Err = rl.tpl.writeNode(w, ch, ctx); ctx.Err != nil {
break
}
}
}
// Mark RL as free to use.
rl.stat = rlFree
return
}
}
}
// Replaces square brackets with variable to concrete values, example:
// user.History[i] -> user.History.0, user.History.1, ...
// , since inspector doesn't support variadic paths.
func (ctx *Ctx) replaceQB(path []byte) []byte {
qbLi := bytes.Index(path, qbL)
qbRi := bytes.Index(path, qbR)
if qbLi != -1 && qbRi != -1 && qbLi < qbRi && qbRi < len(path) {
ctx.BufAcc.StakeOut()
ctx.BufAcc.Write(path[0:qbLi]).Write(dot)
ctx.chQB = false
ctx.bufX = ctx.get(path[qbLi+1 : qbRi])
if ctx.bufX != nil {
if err := ctx.BufAcc.WriteX(ctx.bufX).Error(); err != nil {
ctx.Err = err
ctx.chQB = true
return nil
}
}
ctx.chQB = true
ctx.BufAcc.Write(path[qbRi+1:])
path = ctx.BufAcc.StakedBytes()
}
return path
}
// Get new or existing byte writer.
//
// Made to write output of including sub-templates.
func (ctx *Ctx) getW() *bytes.Buffer {
var b *bytes.Buffer
if ctx.wl < len(ctx.w) {
b = &ctx.w[ctx.wl]
ctx.wl++
} else {
ctx.w = append(ctx.w, bytes.Buffer{})
b = &ctx.w[len(ctx.w)-1]
ctx.wl++
}
return b
}
// Get new or existing KV pair.
func (ctx *Ctx) getKV() *KV {
var kv *KV
if ctx.kvl < len(ctx.kv) {
kv = &ctx.kv[ctx.kvl]
ctx.kvl++
} else {
ctx.kv = append(ctx.kv, KV{})
kv = &ctx.kv[len(ctx.kv)-1]
ctx.kvl++
}
return kv
}
func (ctx *Ctx) defer_() (err error) {
if len(ctx.dfr) > 0 {
for i := 0; i < len(ctx.dfr); i++ {
if err = ctx.dfr[i](); err != nil {
break
}
}
}
return
}