CPU/Memory.py

58 lines
1.3 KiB
Python
Raw Normal View History

2024-04-29 16:00:03 +08:00
from error import *
class Memory:
def __init__(self, size):
self.data = [0] * size
self.size = size
self.name = "内存"
def init(self):
self.data = [0] * self.size
def __getitem__(self, key: int):
if key > self.size:
raise AddressError
return self.data[key]
def write(self, index: int, val: int):
if index > self.size:
raise AddressError()
self.data[index] = val
2024-04-29 22:03:14 +08:00
def write_batch(self, start ,dt:list[int]):
if start + len(dt) > self.size:
raise OutOfMemory('内存用尽')
for i in dt:
self.write(start, i)
start += 1
2024-04-29 16:00:03 +08:00
def __len__(self):
return self.size
def __str__(self):
return str(self.data)
def __setitem__(self, k, v):
if isinstance(k, slice):
if not k.start:
start = 0
else:
start = k.start
if not k.stop:
stop = self.size - 1
else:
stop = k.stop
if start > self.size or stop > self.size:
raise AddressError
self.data[start:stop] = v
return
if k > self.size:
raise AddressError
self.data[k] = v
return