prosper/mem.go

43 lines
1.1 KiB
Go
Raw Normal View History

2021-02-14 02:09:56 +00:00
package main
import "fmt"
// Memory provides an addressable map of integer cells
type Memory struct {
intern map[int]int
nextFree int
}
// Read takes a starting address and a count of cells to read after it;
// (0, 2) reads the first two cells out of memory, for example.
func (m *Memory) Read(addr int, count int) []int {
r := []int{}
for i := 0; i < count; i++ {
r = append(r, m.intern[addr+i])
}
return r
}
// Write inserts the given values into memory, overwriting any existing contents,
// starting at the provided memory address and incrementing upward.
func (m *Memory) Write(addr int, values []int) error {
if addr < 0 {
return fmt.Errorf("addr out of range")
}
for i := range values {
m.intern[addr+i] = values[i]
}
// we've written past our marker, note that
if m.nextFree < addr+len(values) {
m.nextFree = addr + len(values)
}
return nil
}
// NextFreeAddress provides the furthest "out" address, beyond which is uninitialized memory.
// Old memory is never "reclaimed", even if the program manually 0s it out.
// If you want to build your own GC, knock yourself out.
func (m *Memory) NextFreeAddress() int {
return m.nextFree
}