-
Notifications
You must be signed in to change notification settings - Fork 16
/
custom.go
91 lines (70 loc) · 2.14 KB
/
custom.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
// Copyright (c) 2016 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package section
import (
"io"
"gate.computer/wag/binary"
"gate.computer/wag/internal/loader"
"gate.computer/wag/internal/section"
)
// Unwrapped may be returned by custom section content loaders.
var Unwrapped error = section.Unwrapped
// Reader is suitable for reading sections.
type Reader = binary.Reader
// Loader is suitable for use with section loading functions.
type Loader = loader.Loader
// NewLoader creates a WebAssembly section loader.
func NewLoader(r Reader) Loader {
return loader.New(r, 0)
}
type CustomContentLoader func(sectionName string, r Reader, payloadSize uint32) error
type customLoaderMux struct {
loaders map[string]CustomContentLoader
}
func CustomLoader(loaders map[string]CustomContentLoader) func(Reader, uint32) error {
mux := customLoaderMux{loaders: loaders}
return mux.load
}
func (mux customLoaderMux) load(r Reader, length uint32) error {
nameLen, n, err := binary.Varuint32(r)
if err != nil {
return err
}
length -= uint32(n)
nameData := make([]byte, nameLen)
if _, err := io.ReadFull(r, nameData); err != nil {
return err
}
name := loader.String(nameData, "custom section name")
length -= nameLen
if f := mux.loaders[name]; f != nil {
return f(name, r, length)
}
_, err = io.CopyN(io.Discard, r, int64(length))
return err
}
type CustomMapping ByteRange
// Loader of arbitrary custom section. Remembers position, discards content.
func (target *CustomMapping) Loader(sectionMap *Map) CustomContentLoader {
return func(_ string, r Reader, length uint32) (err error) {
*target = CustomMapping(sectionMap.Sections[Custom]) // The latest one.
_, err = io.CopyN(io.Discard, r, int64(length))
return
}
}
type CustomSections struct {
Sections map[string][]byte
}
func (cs *CustomSections) Load(name string, r Reader, length uint32) (err error) {
data := make([]byte, length)
_, err = io.ReadFull(r, data)
if err != nil {
return
}
if cs.Sections == nil {
cs.Sections = make(map[string][]byte)
}
cs.Sections[name] = data
return
}