-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathbytes.go
94 lines (79 loc) · 1.96 KB
/
bytes.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
92
93
94
package js
import (
"fmt"
)
var _ Wrapper = TypedArray{}
// TypedArray represents a JavaScript typed array.
type TypedArray struct {
Value
}
// Release frees up resources allocated for the typed array.
// The typed array and its buffer must not be accessed after calling Release.
func (v TypedArray) Release() {
releaseTypedArray(v.Ref)
}
// TypedArrayOf returns a JavaScript typed array backed by the slice's underlying array.
//
// The supported types are []int8, []int16, []int32, []uint8, []uint16, []uint32, []float32 and []float64.
// Passing an unsupported value causes a panic.
//
// TypedArray.Release must be called to free up resources when the typed array will not be used any more.
func TypedArrayOf(o interface{}) TypedArray {
v := typedArrayOf(toJS(o))
return TypedArray{Value{v}}
}
var _ Wrapper = (*Memory)(nil)
type Memory struct {
v TypedArray
p []byte
}
func (m *Memory) Bytes() []byte {
return m.p
}
// CopyFrom copies binary data from JS object into Go buffer.
func (m *Memory) CopyFrom(v Wrapper) error {
var src Value
switch v := v.(type) {
case Value:
src = v
case TypedArray:
src = v.Value
default:
src = Value{v.JSValue()}
}
switch {
case src.InstanceOfClass("Uint8Array"):
m.v.Call("set", src)
return nil
case src.InstanceOfClass("Blob"):
r := New("FileReader")
cg := r.NewFuncGroup()
defer cg.Release()
done := cg.OneTimeTrigger("loadend")
errc := cg.ErrorEventChan()
r.Call("readAsArrayBuffer", src)
select {
case err := <-errc:
return err
case <-done:
}
cg.Release()
arr := New("Uint8Array", r.Get("result"))
return m.CopyFrom(arr)
default:
return fmt.Errorf("unsupported source type")
}
}
func (m *Memory) JSValue() Ref {
return m.v.JSValue()
}
func (m *Memory) Release() {
m.v.Release()
}
// MMap exposes memory of p to JS.
//
// Release must be called to free up resources when the memory will not be used any more.
func MMap(p []byte) *Memory {
v := TypedArrayOf(p)
return &Memory{p: p, v: v}
}