-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
95 lines (81 loc) · 2.3 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
87
88
89
90
91
92
93
94
95
// Package cpu contains a number of registers, here we implement them.
package cpu
import (
"fmt"
"os"
)
// 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 {
switch arg := r.o.(type) {
case *IntegerObject:
return arg.Value
default:
fmt.Printf("BUG: Attempting to call GetInt on a register holding a non-integer value: %v\n", r.o)
os.Exit(3)
}
// Not reached
return 0
}
// 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 {
switch arg := r.o.(type) {
case *StringObject:
return arg.Value
default:
fmt.Printf("BUG: Attempting to call GetString on a register holding a non-string value: %v\n", r.o)
os.Exit(3)
}
// Not reached
return ""
}
// 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())
}