-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontinuation.go
More file actions
110 lines (95 loc) · 2.1 KB
/
continuation.go
File metadata and controls
110 lines (95 loc) · 2.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
package bunquery
import (
"encoding/base64"
"fmt"
"github.com/vmihailenco/msgpack/v5"
)
const (
flagReverse uint8 = 1 << iota
flagInclude
)
type rawContinuation struct {
K uint32
D uint8
F uint8
V []any
}
func decodeRawContinuation(token string) (*rawContinuation, error) {
b, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return nil, err
}
c := &rawContinuation{}
if err := msgpack.Unmarshal(b, c); err != nil {
return nil, err
}
return c, nil
}
func (raw *rawContinuation) Continuation() *Continuation {
var dirs []uint8
for i := range 8 {
dirs = append(dirs, (raw.D>>i)&0x01)
}
return &Continuation{
SID: raw.K,
Directions: dirs,
Values: raw.V,
Reverse: raw.F&flagReverse != 0,
Include: raw.F&flagInclude != 0,
}
}
func (raw *rawContinuation) String() (string, error) {
if b, err := msgpack.Marshal(raw); err != nil {
return "", err
} else {
return base64.StdEncoding.EncodeToString(b), nil
}
}
type Continuation struct {
SID uint32
Directions []uint8
Values []any
Reverse bool
Include bool
}
func NewContinuation(sid uint32, directions []uint8, values []any, reverse, include bool) *Continuation {
return &Continuation{
SID: sid,
Directions: directions,
Values: values,
Reverse: reverse,
Include: include,
}
}
func (c *Continuation) raw() *rawContinuation {
d := uint8(0)
for i, dir := range c.Directions {
d |= (dir & 0x1) << i
}
p := &rawContinuation{
K: c.SID,
D: d,
V: c.Values,
}
if c.Reverse {
p.F |= flagReverse
}
if c.Include {
p.F |= flagInclude
}
return p
}
func (c *Continuation) String() (string, error) {
return c.raw().String()
}
func FormatContinuation(sid uint32, directions []uint8, values []any, reverse, include bool) (string, error) {
res := NewContinuation(sid, directions, values, reverse, include)
return res.String()
}
func ParseContinuation(token string) (*Continuation, error) {
if c, err := decodeRawContinuation(token); err != nil {
return nil, fmt.Errorf("failed to parse continue token: %w", err)
} else {
return c.Continuation(), nil
}
}