/
memory.go
56 lines (47 loc) · 1.38 KB
/
memory.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
package encodable
import (
"io"
"reflect"
"unsafe"
"github.com/stewi1014/encs/encio"
)
// NewMemory returns a new Memory encoder
func NewMemory(size int) *Memory {
return &Memory{
buff: reflect.SliceHeader{
Len: size,
Cap: size,
},
}
}
// Memory is an encoder that throws type-safety out the window (as if the rest of this library wasn't enough).
// Initialised with NewMemory(size), it reads/writes directly to the memory at the given address with no internal buffering.
// Extreme care must be taken, errors from Memory can be difficult to read, let alone helpful in debugging, and are often in the form of panics,
// or worse still, the silent destruction of the universe.
type Memory struct {
buff reflect.SliceHeader
}
// String implements Encodable
func (e *Memory) String() string {
return "Memory"
}
// Type implements Encodable
func (e *Memory) Type() reflect.Type {
return invalidType
}
// Size implemenets Encodable
func (e *Memory) Size() int {
return e.buff.Cap
}
// Encode implements Encodable
func (e *Memory) Encode(ptr unsafe.Pointer, w io.Writer) error {
checkPtr(ptr)
e.buff.Data = (uintptr)(ptr)
return encio.Write(*(*[]byte)(unsafe.Pointer(&e.buff)), w)
}
// Decode implements Decodable
func (e *Memory) Decode(ptr unsafe.Pointer, r io.Reader) error {
checkPtr(ptr)
e.buff.Data = (uintptr)(ptr)
return encio.Read(*(*[]byte)(unsafe.Pointer(&e.buff)), r)
}