blob: 02b20a76234a431dcde70cc89c6f393aa119ae19 (
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
namespace Q1.core.Components;
using Q1.core.Arch;
public class Bus : IAddressable
{
private Chip? _chip;
private readonly List<IAddressable> _devices;
public u16 AddressableStart { get; }
public u16 AddressableEnd { get; }
public Bus(u16 addressableStart, u16 addressableEnd)
{
this.AddressableStart = addressableStart;
this.AddressableEnd = addressableEnd;
this._devices = new();
}
public void SendInterrupt(u16 code)
{
if (this._chip == null)
throw new InvalidOperationException("Chip is not attached to bus");
this._chip.Interrupt(code);
}
public void AttachChip(Chip chip)
{
if (this._chip != null)
throw new InvalidOperationException("Bus already has a chip attached.");
this._chip = chip;
chip.Bus = this;
}
public void MountDevice(IAddressable device)
{
if (device.AddressableStart >= device.AddressableEnd)
throw new ArgumentException("Addressable range is invalid.", nameof(device));
int index = 0;
while (index < this._devices.Count && this._devices[index].AddressableStart < device.AddressableStart)
index++;
if (index > 0)
{
IAddressable prev = this._devices[index - 1];
if (device.AddressableStart < prev.AddressableEnd)
throw new InvalidOperationException("Address range overlaps with previous device.");
}
if (index < this._devices.Count)
{
IAddressable next = this._devices[index];
if (device.AddressableEnd > next.AddressableStart)
throw new InvalidOperationException("Address range overlaps with next device.");
}
this._devices.Insert(index, device);
}
private IAddressable? GetDevice(u16 address)
{
foreach (IAddressable device in this._devices)
{
if (address < device.AddressableStart)
break;
if (address < device.AddressableEnd)
return device;
}
return null;
}
public u8 Read(u16 address)
{
IAddressable? device = this.GetDevice(address);
if (device == null)
return 0;
return device.Read((u16) (address - device.AddressableStart));
}
public void Write(u16 address, u8 value)
{
IAddressable? device = this.GetDevice(address);
if (device == null)
return;
device.Write((u16) (address - device.AddressableStart), value);
}
public void Clock()
{
foreach (IAddressable addressable in this._devices)
addressable.Clock();
}
}
|