about summary refs log tree commit diff
path: root/pkg/lang/vm/code/code.go
blob: 94fd612a9d6e4c596c176648c8ac664773aad529 (plain)
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
package code

import (
	"bytes"
	"encoding/binary"
	"math"
	"strings"
)

type Raw []byte

type Code struct {
	code      Raw
	debugInfo DebugInfo
}

func New(code Raw, info DebugInfo) Code {
	return Code{
		code:      code,
		debugInfo: info,
	}
}

func (c *Code) Len() int {
	return len(c.code)
}

func (c *Code) Code() Raw {
	return c.code
}

func (c *Code) Debug() *DebugInfo {
	return &c.debugInfo
}

func (c *Code) GetOp(at int) (Op, int) {
	return Op(c.code[at]), 1
}

func (c *Code) GetUint(at int) (uint64, int) {
	advance := 8
	x := binary.LittleEndian.Uint64(c.code[at : at+advance])
	return x, advance
}

func (c *Code) GetInt(at int) (int64, int) {
	x, advance := c.GetUint(at)
	return int64(x), advance
}

func (c *Code) GetFloat(at int) (float64, int) {
	x, advance := c.GetUint(at)
	return math.Float64frombits(x), advance
}

func (c *Code) GetString(at int) (string, int) {
	advance := 0
	reader := bytes.NewReader(c.code[at:])
	builder := strings.Builder{}

	for {
		r, size, err := reader.ReadRune()
		advance += size

		if err != nil {
			break
		}

		if r == 0 {
			break
		}

		builder.WriteRune(r)
	}

	return builder.String(), advance
}