-
Notifications
You must be signed in to change notification settings - Fork 623
/
tokenizer.go
53 lines (45 loc) 路 962 Bytes
/
tokenizer.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
package server
import (
"bytes"
"encoding/binary"
"log/slog"
)
type Header struct {
Magic uint8
DataLength uint32
}
type Tokenizer struct {
header Header
headerLength int
headerValid bool
}
func (x *Tokenizer) Split(data []byte, _ bool) (advance int, token []byte, err error) {
if x.headerLength == 0 {
x.headerLength = binary.Size(x.header)
}
advance = 0
if !x.headerValid {
if len(data) < x.headerLength {
return
}
buf := bytes.NewReader(data)
err := binary.Read(buf, binary.LittleEndian, &x.header)
if err != nil {
slog.Error("can't read token", "err", err)
return 0, nil, err
}
if x.header.Magic != uint8('W') {
slog.Error("Invalid magic byte in header")
}
x.headerValid = true
advance += x.headerLength
data = data[advance:]
}
if len(data) < int(x.header.DataLength) {
return
}
advance += int(x.header.DataLength)
token = data[:x.header.DataLength]
x.headerValid = false
return
}