aboutsummaryrefslogtreecommitdiff
path: root/MicSim/components/ram.py
blob: 6a5b02e8be4308fdefafd1872b029f5429c3b298 (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
78
79
80
81
82
83
from components.ijvm import ijvm

class Ram:
	
	def __init__(self,components,size):
		self.data=dict()
		self.lastAddr=size-1
		self.c=components
	
	def loadRamFile(self,filepath):
		"""
			Load a Ram file into self.data
		"""
		data=dict()
		addr=0
		f=open(filepath,"r")
		for line in f.readlines():
			line=line.rstrip() # remove \n
			if line in ijvm:
				data[addr]=int(ijvm[line])
			else:
				try:
					value=int(line,0)
				except:
					raise ValueError("Invalide RAM entry: Address {} value {}".format(addr,line))
				if value>255:
					raise ValueError("Ram contain values that does not fit in a byte: value {} at address {}".format(value,addr)) 
				data[addr]=value
			addr+=1
		f.close()
		self.data=data
	
	def write(self):
		"""
			Write data to memory based Mic-1 architecture
		"""
		addr=self.c["MAR"]*4 # Don't forget MAR address 32bits block of memory
		if addr>self.lastAddr:
			raise ValueError("You get out of the ram by trying to set a value at address {}, max address is {}".format(addr,self.lastAddr))
		#### Split bytes and write ####
		self.data[addr+3]=self.c["MDR"] & 0xFF
		self.data[addr+2]=self.c["MDR"]>>8 & 0xFF
		self.data[addr+1]=self.c["MDR"]>>16 & 0xFF
		self.data[addr]=self.c["MDR"]>>24 & 0xFF

	
	def read(self):
		"""
			Read data from memory based Mic-1 architecture
		"""
		addr=self.c["MAR"]*4 # Don't forget MAR address 32bits block of memory
		value=None
		try:
			#### Combine bytes ####
			value=self.data[addr]<<24|(self.data[addr+1]<<16)|(self.data[addr+2]<<8)|(self.data[addr+3])
		except:
			if addr>self.lastAddr:
				raise ValueError("You get out of the ram by trying to get value at address {}, max address is {}".format(addr,self.lastAddr))
		if(value==None):
			return(0)
		return(value)
		
	def fetch(self):
		"""
			Fetch next byte from memory based Mic-1 architecture
		"""
		addr=self.c["PC"]
		value=None
		try:
			value=self.data[addr]
		except:
			if addr>self.lastAddr:
				raise ValueError("You get out of the ram by trying to get value at address {}, max address is {}".format(addr,self.lastAddr))
		if(value==None):
			return(0)
		return(value)
		
	def dump(self):
		"""
			Fetch RAM data (usefull for unit tests)
		"""
		return(self.data)