forked from skx/go.vm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
86 lines (72 loc) · 2.23 KB
/
register.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
// Package cpu contains a number of registers, here we implement them.
package cpu
import (
"fmt"
)
// Object is the interface for something we store in a register.
//
// This is done to allow future expansion, and also for neatness.
type Object interface {
Type() string
}
// IntegerObject is an object holding an integer-value.
type IntegerObject struct {
Value int
}
// Type returns `int` for IntegerObjects.
func (i *IntegerObject) Type() string { return "int" }
// StringObject is an object holding a string-value.
type StringObject struct {
Value string
}
// Type returns `string` for StringObjects.
func (i *StringObject) Type() string { return "string" }
// Register holds the contents of a single register, as an object.
//
// This means it can hold either an IntegerObject, or a StringObject.
type Register struct {
o Object
}
// NewRegister is the constructor for a register.
func NewRegister() *Register {
r := &Register{}
r.SetInt(0)
return (r)
}
// GetInt retrieves the integer content of the given register.
// If the register does not contain an integer that is a fatal error.
func (r *Register) GetInt() (int, error) {
switch arg := r.o.(type) {
case *IntegerObject:
return arg.Value, nil
}
return 0, fmt.Errorf("attempting to call GetInt on a register holding a non-integer value: %v", r.o)
}
// SetInt stores the given integer in the register.
// Note that a register may only contain integers in the range 0x0000-0xffff
func (r *Register) SetInt(v int) {
if v <= 0 {
r.o = &IntegerObject{Value: 0}
} else if v >= 0xffff {
r.o = &IntegerObject{Value: 0xffff}
} else {
r.o = &IntegerObject{Value: v}
}
}
// GetString retrieves the string content of the given register.
// If the register does not contain a string that is a fatal error.
func (r *Register) GetString() (string, error) {
switch arg := r.o.(type) {
case *StringObject:
return arg.Value, nil
}
return "", fmt.Errorf("attempting to call GetString on a register holding a non-string value: %v", r.o)
}
// SetString stores the supplied string in the register.
func (r *Register) SetString(v string) {
r.o = &StringObject{Value: v}
}
// Type returns the type of a registers contents `int` vs. `string`.
func (r *Register) Type() string {
return (r.o.Type())
}