-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuffer.go
More file actions
388 lines (350 loc) · 9.1 KB
/
buffer.go
File metadata and controls
388 lines (350 loc) · 9.1 KB
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
package lex
import (
"io"
"github.com/zalgonoise/gio"
)
const (
bufferInitCap = 1024
bufferCapThres = 96
bufferLookbackSize = 5
)
// LexBuffer implements the Lexer interface, by accepting a gio.Reader of any type
type LexBuffer[C comparable, T any] struct {
input gio.Reader[T]
buf []T
start int
pos int
state StateFn[C, T]
items chan Item[C, T]
bufferLookbackSize int
}
var _ Lexer[uint8, any] = &LexBuffer[uint8, any]{}
func NewBuffer[C comparable, T any](
initFn StateFn[C, T],
input gio.Reader[T],
) *LexBuffer[C, T] {
if input == nil {
return nil
}
return &LexBuffer[C, T]{
input: input,
buf: make([]T, 0, bufferInitCap),
state: initFn,
items: make(chan Item[C, T], 2),
bufferLookbackSize: bufferLookbackSize,
}
}
// Size sets a custom buffer look-back size whenever an item is emited
func (l *LexBuffer[C, T]) Size(maxSize int) {
if maxSize < 0 {
l.bufferLookbackSize = 0
return
}
l.bufferLookbackSize = maxSize
}
// NextItem processes the tokens sequentially, through the corresponding StateFn
//
// As each item is processed, it is returned to the Lexer by `Emit()`, and
// finally returned to the caller.
//
// Note that multiple calls to `NextItem()` should be made when tokenizing input data;
// usually in a for-loop while the output item is not EOF.
func (l *LexBuffer[C, T]) NextItem() Item[C, T] {
var next Item[C, T]
for {
select {
case next = <-l.items:
return next
default:
if l.state != nil {
l.state = l.state(l)
continue
}
close(l.items)
return next
}
}
}
// Emit pushes the set of units identified by token `itemType` to the items channel,
// that returns it in the NextItem() method.
//
// The emitted item will be a subsection of the input data slice, from the lexer's
// starting index to the current position index.
//
// It also sets the lexer's starting index to the current position index.
func (l *LexBuffer[C, T]) Emit(itemType C) {
l.items <- Item[C, T]{
Pos: l.start,
Type: itemType,
Value: l.buf[l.start:l.pos],
}
// cutoff the buffer's head up to the current position
l.buf = l.buf[l.pos:]
l.start = 0
l.pos = 0
// look into the buffer's remaining capacity
// if below the set capacity threshold, use a new buffer
//
// saves over 200 allocs/op on `SqueezeTheBuffer` test by avoiding
// repeated calls to grow the slice
if cap(l.buf) < bufferCapThres {
if len(l.buf)-l.bufferLookbackSize < 0 {
b := make([]T, len(l.buf), bufferInitCap)
copy(b, l.buf)
l.buf = b
return
}
b := make([]T, l.bufferLookbackSize, bufferInitCap)
copy(b, l.buf[len(l.buf)-l.bufferLookbackSize:])
l.buf = b
}
}
// Ignore will set the starting point as the current position, ignoring any preceeding units
func (l *LexBuffer[C, T]) Ignore() {
l.start = l.pos
}
// Backup will rewind the index for the width of the current item
func (l *LexBuffer[C, T]) Backup() {
l.pos = l.start
}
// Width returns the size of the set of units ready to be emitted with a token
func (l *LexBuffer[C, T]) Width() int {
return l.pos - l.start
}
// Start returns the current starting-point index for when an item is emitted
func (l *LexBuffer[C, T]) Start() int {
return l.start
}
// Check passes the current token through the input `verifFn` function as a validator, returning
// its result
func (l *LexBuffer[C, T]) Check(verifFn func(item T) bool) bool {
return verifFn(l.Cur())
}
// Accept passes the current token through the input `verifFn` function as a validator, returning
// its result
//
// If the validation passes, the cursor has moved one step forward (the unit was consumed)
//
// If the validation fails, the cursor rolls back one step
func (l *LexBuffer[C, T]) Accept(verifFn func(item T) bool) bool {
if ok := verifFn(l.Next()); ok {
return true
}
l.Prev()
return false
}
// AcceptRun iterates through all following tokens, passing them through the input `verifFn`
// function as a validator
//
// Once it fails the verification, the cursor is rolledback once, leaving the caller at the unit
// that failed the verifFn
func (l *LexBuffer[C, T]) AcceptRun(verifFn func(item T) bool) {
for verifFn(l.Next()) {
}
l.Prev()
}
func (l *LexBuffer[C, T]) consume(pos int) error {
if n := pos - len(l.buf) + 1; n > 0 {
for i := 0; i < n; i++ {
var next = make([]T, 1)
n, err := l.input.Read(next)
if err != nil {
return err
}
if n == 0 {
return io.EOF
}
l.buf = append(l.buf, next[0])
}
}
return nil
}
// Cur returns the same indexed item in the slice
//
// If the position is already over the size of the input, the zero-value EOF token is returned
func (l *LexBuffer[C, T]) Cur() T {
if l.pos >= len(l.buf) {
var eof T
return eof
}
return l.buf[l.pos]
}
// Pos returns the current position in the cursor
func (l *LexBuffer[C, T]) Pos() int {
return l.pos
}
// Len returns the current size of the underlying slice
func (l *LexBuffer[C, T]) Len() int {
return len(l.buf)
}
// Next returns the current item in the slice as per the lexer's position, and
// increments the position by one.
//
// If the position is bigger or equal to the size of the input data, the position
// value is NOT incremented and the zero-value EOF token is returned
func (l *LexBuffer[C, T]) Next() T {
l.pos++
err := l.consume(l.pos)
if err != nil {
var eof T
return eof
}
return l.buf[l.pos-1]
}
// Prev returns the previous item in the slice, while also decrementing the
// lexer's position.
//
// If the new position is less than zero, the position value is NOT decremented
// and the zero-value EOF token is returned
func (l *LexBuffer[C, T]) Prev() T {
if l.pos-1 < 0 {
var eof T
return eof
}
l.pos--
for l.pos < l.start {
l.start--
}
err := l.consume(l.pos)
if err != nil {
var eof T
return eof
}
return l.buf[l.pos]
}
// Peek returns the next indexed item without advancing the cursor
//
// If the next token overflows the input's index, the zero-value EOF token is returned
func (l *LexBuffer[C, T]) Peek() T {
err := l.consume(l.pos)
if err != nil {
var eof T
return eof
}
next := l.buf[l.pos]
l.pos--
return next
}
// Head returns to the beginning of the buffer, setting both lexer's start and position
// values to zero
func (l *LexBuffer[C, T]) Head() T {
l.pos = 0
l.start = 0
return l.buf[l.pos]
}
// Tail jumps to the end of the buffer, setting both lexer's start and position values to
// the last item in the input
func (l *LexBuffer[C, T]) Tail() T {
if len(l.buf) == 0 {
var eof T
return eof
}
l.pos = len(l.buf) - 1
l.start = len(l.buf) - 1
return l.buf[l.pos]
}
// Idx jumps to the specific index `idx` in the buffer
//
// If the input index is below 0, the zero-value EOF token is returned
// If the input index is greater than the size of the input, the
// zero-value EOF token is returned
func (l *LexBuffer[C, T]) Idx(idx int) T {
if idx < 0 {
var eof T
return eof
}
if idx >= len(l.buf) {
var eof T
return eof
}
l.pos = idx
if idx < l.start {
l.start = idx
}
err := l.consume(l.pos)
if err != nil {
var eof T
return eof
}
return l.buf[l.pos]
}
// Offset advances or rewinds `amount` steps in the buffer, be it a positive or negative
// input.
//
// If the result offset is below 0, the zero-value EOF token is returned
// If the result offset is greater than the size of the slice, the
// zero-value EOF token is returned
func (l *LexBuffer[C, T]) Offset(amount int) T {
if l.pos+amount < 0 {
var eof T
return eof
}
if l.pos+amount >= len(l.buf) {
var eof T
return eof
}
l.pos += amount
if l.pos-l.start < 0 {
l.start += amount
}
err := l.consume(l.pos)
if err != nil {
var eof T
return eof
}
return l.buf[l.pos]
}
// PeekIdx returns the next indexed item without advancing the cursor,
// with the index `idx`
//
// If the input index is below 0, the zero-value EOF token is returned
// If the input index is greater than the size of the input, the
// zero-value EOF token is returned
func (l *LexBuffer[C, T]) PeekIdx(idx int) T {
if idx >= len(l.buf) {
var eof T
return eof
}
if idx < 0 {
var eof T
return eof
}
err := l.consume(idx)
if err != nil {
var eof T
return eof
}
return l.buf[idx]
}
// PeekOffset returns the next indexed item without advancing the cursor,
// with offset `amount`
//
// If the result offset is below 0, the zero-value EOF token is returned
// If the result offset is greater than the size of the slice, the
// zero-value EOF token is returned
func (l *LexBuffer[C, T]) PeekOffset(amount int) T {
if l.pos+amount >= len(l.buf) || l.pos+amount < 0 {
var eof T
return eof
}
err := l.consume((l.pos + amount))
if err != nil {
var eof T
return eof
}
return l.buf[l.pos+amount]
}
// Extract returns a slice from index `start` to index `end`
//
// If the input start index is below 0, the starting point will be set to zero
// If the input end index is greater than the size of the input, the
// ending point will be set to the size of the input.
func (l *LexBuffer[C, T]) Extract(start, end int) []T {
if start < 0 {
start = 0
}
if end > len(l.buf) {
end = len(l.buf)
}
return l.buf[start:end]
}