-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.go
More file actions
243 lines (206 loc) · 5.54 KB
/
binary.go
File metadata and controls
243 lines (206 loc) · 5.54 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
package binary
import (
"bytes"
"io"
"reflect"
"sync"
. "github.com/tinywasm/fmt"
)
var (
global *instance
once sync.Once
)
// namedHandler allows types to provide a stable name for schema caching.
// This helps avoid reflect.ValueOf() calls on every encode/decode.
type namedHandler interface {
HandlerName() string
}
func getInstance() *instance {
once.Do(func() {
global = newInstance()
})
return global
}
// Encode encodes input to output.
// input: struct or pointer to struct
// output: *[]byte or io.Writer
func Encode(input, output any) error {
inst := getInstance()
switch out := output.(type) {
case *[]byte:
var buffer bytes.Buffer
buffer.Grow(64)
if err := inst.encodeTo(input, &buffer); err == nil {
*out = buffer.Bytes()
return nil
} else {
return err
}
case io.Writer:
return inst.encodeTo(input, out)
default:
return Err("Encode", "output", "must be *[]byte or io.Writer")
}
}
// Decode decodes input to output.
// input: []byte or io.Reader
// output: pointer to struct
func Decode(input, output any) error {
inst := getInstance()
switch in := input.(type) {
case []byte:
return inst.decode(in, output)
case io.Reader:
return inst.decodeFrom(in, output)
default:
return Err("Decode", "input", "must be []byte or io.Reader")
}
}
// SetLog sets a custom logging function for debug/testing.
// Pass nil to disable logging.
func SetLog(fn func(msg ...any)) {
getInstance().log = fn
}
// instance represents a binary encoder/decoder with isolated state.
type instance struct {
// log is an optional custom logging function
log func(msg ...any)
// schemas is a slice-based cache for TinyGo compatibility (no maps allowed)
schemas []schemaEntry
// encoders is a private pool for encoder instances
encoders *sync.Pool
// decoders is a private pool for decoder instances
decoders *sync.Pool
// Mutex to protect schemas slice
mu sync.RWMutex
}
// schemaEntry represents a cached schema with its type and codec
type schemaEntry struct {
Type reflect.Type
codec codec
Name string // Optional handler name
}
func newInstance(args ...any) *instance {
var logFunc func(msg ...any) // Default: no logging
for _, arg := range args {
if log, ok := arg.(func(msg ...any)); ok {
logFunc = log
}
}
tb := &instance{log: logFunc}
tb.schemas = make([]schemaEntry, 0, 100) // Pre-allocate reasonable size
tb.encoders = &sync.Pool{
New: func() any {
return &encoder{
tb: tb,
}
},
}
tb.decoders = &sync.Pool{
New: func() any {
return &decoder{
tb: tb,
}
},
}
return tb
}
// EncodeTo encodes the payload into a specific destination using this instance.
func (tb *instance) encodeTo(data any, dst io.Writer) error {
// Get the encoder from the pool, reset it
e := tb.encoders.Get().(*encoder)
e.reset(dst, tb)
// Encode and set the buffer if successful
err := e.encode(data)
// Put the encoder back when we're finished
tb.encoders.Put(e)
return err
}
// Decode decodes the payload from the binary format using this instance.
func (tb *instance) decode(data []byte, target any) error {
// Get the decoder from the pool, reset it
d := tb.decoders.Get().(*decoder)
d.reset(data, tb)
// Decode and free the decoder
err := d.decode(target)
tb.decoders.Put(d)
return err
}
func (tb *instance) decodeFrom(r io.Reader, target any) error {
// Get the decoder from the pool, reset it
d := tb.decoders.Get().(*decoder)
if d.reader == nil {
d.reader = newReader(r)
} else {
// If it's a slice reader, we need to replace it with a stream reader
if _, ok := d.reader.(*sliceReader); ok {
d.reader = newReader(r)
} else {
// It's already a stream reader, but we can't easily reset its inner reader
// because streamReader has a private field.
// Let's just create a new reader for now or check if we can reset it.
d.reader = newReader(r)
}
}
d.tb = tb
// Decode and free the decoder
err := d.decode(target)
tb.decoders.Put(d)
return err
}
// findSchema performs a linear search in the slice-based cache for TinyGo compatibility
func (tb *instance) findSchema(t reflect.Type) (codec, bool) {
tb.mu.RLock()
defer tb.mu.RUnlock()
for _, entry := range tb.schemas {
if entry.Type == t {
return entry.codec, true
}
}
return nil, false
}
// findSchemaByName performs a linear search in the schemas cache by handler name
func (tb *instance) findSchemaByName(name string) (codec, reflect.Type, bool) {
tb.mu.RLock()
defer tb.mu.RUnlock()
for _, entry := range tb.schemas {
if entry.Name == name {
return entry.codec, entry.Type, true
}
}
return nil, nil, false
}
// addSchema adds a new schema to the slice-based cache
func (tb *instance) addSchema(t reflect.Type, codec codec, name string) {
tb.mu.Lock()
defer tb.mu.Unlock()
// Simple cache size limit (optional, for memory control)
if len(tb.schemas) >= 1000 { // Reasonable default limit
// Simple eviction: remove oldest (first) entry
tb.schemas = tb.schemas[1:]
}
tb.schemas = append(tb.schemas, schemaEntry{
Type: t,
codec: codec,
Name: name,
})
}
// scanToCache scans the type and caches it in the instance using slice-based cache
func (tb *instance) scanToCache(t reflect.Type, name string) (codec, error) {
if t == nil {
return nil, Err("scanToCache", "type", "nil")
}
// Double check if we already have this schema cached by type
// (Though callers usually check first, it's safer here)
if c, found := tb.findSchema(t); found {
return c, nil
}
// Scan for the first time
c, err := scan(t)
if err != nil {
return nil, err
}
// Cache the schema
tb.addSchema(t, c, name)
return c, nil
}