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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use core::fmt;
use core::ops::{Bound, Range, RangeBounds};
use std::rc::Rc;
use std::io::{self, Read};
mod extension;
#[cfg(feature = "snapshot")] pub mod arrays;
#[cfg(feature = "snapshot")] pub mod serde;
pub use extension::*;
pub const MEM16K_SIZE : usize = 0x4000;
pub const MEM32K_SIZE : usize = 2 * MEM16K_SIZE;
pub const MEM48K_SIZE : usize = 3 * MEM16K_SIZE;
pub const MEM64K_SIZE : usize = 4 * MEM16K_SIZE;
pub const MEM128K_SIZE: usize = 8 * MEM16K_SIZE;
pub const MEM8K_SIZE : usize = MEM16K_SIZE / 2;
pub const SCREEN_SIZE: u16 = 0x1B00;
pub type ScreenArray = [u8;SCREEN_SIZE as usize];
pub type ExRom = Rc<[u8]>;
#[non_exhaustive]
#[derive(Debug)]
pub enum ZxMemoryError {
InvalidPageIndex,
InvalidBankIndex,
UnsupportedAddressRange,
UnsupportedExRomPaging,
InvalidExRomSize,
Io(io::Error)
}
impl std::error::Error for ZxMemoryError {}
impl fmt::Display for ZxMemoryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", match self {
ZxMemoryError::InvalidPageIndex => "Memory page index is out of range",
ZxMemoryError::InvalidBankIndex => "Memory bank index is out of range",
ZxMemoryError::UnsupportedAddressRange => "Address range is not supported",
ZxMemoryError::UnsupportedExRomPaging => "EX-ROM mapping is not supported",
ZxMemoryError::InvalidExRomSize => "EX-ROM size is smaller than the memory page size",
ZxMemoryError::Io(err) => return err.fmt(f)
})
}
}
impl From<ZxMemoryError> for io::Error {
fn from(err: ZxMemoryError) -> Self {
match err {
ZxMemoryError::Io(err) => err,
e => io::Error::new(io::ErrorKind::InvalidInput, e)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MemoryKind {
Rom,
Ram
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemPageOffset {
pub kind: MemoryKind,
pub index: u8,
pub offset: u16
}
#[derive(Debug, PartialEq, Eq)]
pub enum PageMutSlice<'a> {
Rom(&'a mut [u8]),
Ram(&'a mut [u8])
}
impl<'a> PageMutSlice<'a> {
pub fn as_mut_slice(&mut self) -> &mut [u8] {
match self {
PageMutSlice::Rom(slice)|PageMutSlice::Ram(slice) => slice
}
}
pub fn into_mut_slice(self) -> &'a mut[u8] {
match self {
PageMutSlice::Rom(slice)|PageMutSlice::Ram(slice) => slice
}
}
pub fn is_rom(&self) -> bool {
matches!(self, PageMutSlice::Rom(..))
}
pub fn as_mut_rom(&mut self) -> Option<&mut [u8]> {
match self {
PageMutSlice::Rom(slice) => Some(slice),
_ => None
}
}
pub fn into_mut_rom(self) -> Option<&'a mut [u8]> {
match self {
PageMutSlice::Rom(slice) => Some(slice),
_ => None
}
}
pub fn is_ram(&self) -> bool {
matches!(self, PageMutSlice::Ram(..))
}
pub fn as_mut_ram(&mut self) -> Option<&mut [u8]> {
match self {
PageMutSlice::Ram(slice) => Some(slice),
_ => None
}
}
pub fn into_mut_ram(self) -> Option<&'a mut [u8]> {
match self {
PageMutSlice::Ram(slice) => Some(slice),
_ => None
}
}
}
pub type Result<T> = core::result::Result<T, ZxMemoryError>;
pub trait ZxMemory {
const PAGE_SIZE: usize = 0x4000;
const ROM_SIZE: usize;
const RAMTOP: u16;
const PAGES_MAX: u8;
const SCR_BANKS_MAX: usize;
const ROM_BANKS_MAX: usize;
const RAM_BANKS_MAX: usize;
fn reset(&mut self);
fn read(&self, addr: u16) -> u8;
fn read16(&self, addr: u16) -> u16;
fn read_screen(&self, screen_bank: usize, addr: u16) -> u8;
fn write(&mut self, addr: u16, val: u8);
fn write16(&mut self, addr: u16, val: u16);
fn mem_ref(&self) -> &[u8];
fn mem_mut(&mut self) -> &mut[u8];
fn screen_ref(&self, screen_bank: usize) -> Result<&ScreenArray>;
fn screen_mut(&mut self, screen_bank: usize) -> Result<&mut ScreenArray>;
fn page_kind(&self, page: u8) -> Result<MemoryKind>;
fn page_bank(&self, page: u8) -> Result<(MemoryKind, usize)>;
fn page_ref(&self, page: u8) -> Result<&[u8]>;
fn page_mut(&mut self, page: u8) -> Result<&mut[u8]>;
fn rom_bank_ref(&self, rom_bank: usize) -> Result<&[u8]>;
fn rom_bank_mut(&mut self, rom_bank: usize) -> Result<&mut[u8]>;
fn ram_bank_ref(&self, ram_bank: usize) -> Result<&[u8]>;
fn ram_bank_mut(&mut self, ram_bank: usize) -> Result<&mut[u8]>;
fn map_rom_bank(&mut self, rom_bank: usize, page: u8) -> Result<()>;
fn map_exrom(&mut self, _exrom_bank: ExRom, _page: u8) -> Result<()> {
Err(ZxMemoryError::UnsupportedExRomPaging)
}
fn unmap_exrom(&mut self, _exrom_bank: &ExRom) { }
fn is_exrom_at(&self, _page: u8) -> bool { false }
fn has_mapped_exrom(&self, _exrom_bank: &ExRom) -> bool { false }
fn map_ram_bank(&mut self, ram_bank: usize, page: u8) -> Result<()>;
fn page_index_at(&self, address: u16) -> Result<MemPageOffset> {
let index = (address / Self::PAGE_SIZE as u16) as u8;
let offset = address % Self::PAGE_SIZE as u16;
let kind = self.page_kind(index)?;
Ok(MemPageOffset {kind, index, offset})
}
fn rom_ref(&self) -> &[u8] {
&self.mem_ref()[0..Self::ROM_SIZE]
}
fn rom_mut(&mut self) -> &mut [u8] {
&mut self.mem_mut()[0..Self::ROM_SIZE]
}
fn ram_ref(&self) -> &[u8] {
&self.mem_ref()[Self::ROM_SIZE..]
}
fn ram_mut(&mut self) -> &mut [u8] {
&mut self.mem_mut()[Self::ROM_SIZE..]
}
fn load_into_rom<R: Read>(&mut self, mut rd: R) -> Result<()> {
let slice = self.rom_mut();
rd.read_exact(slice).map_err(ZxMemoryError::Io)
}
fn load_into_rom_bank<R: Read>(&mut self, rom_bank: usize, mut rd: R) -> Result<()> {
let slice = self.rom_bank_mut(rom_bank)?;
rd.read_exact(slice).map_err(ZxMemoryError::Io)
}
fn iter_pages<A: RangeBounds<u16>>(
&self,
address_range: A,
) -> Result<MemPageRefIter<'_, Self>> {
let range = normalize_address_range(address_range, 0, Self::RAMTOP)
.map_err(|_| ZxMemoryError::UnsupportedAddressRange)?;
let cursor = range.start;
let end = range.end;
Ok(MemPageRefIter { mem: self, cursor, end })
}
fn for_each_page_mut<A: RangeBounds<u16>, F>(
&mut self,
address_range: A,
mut f: F
) -> Result<()>
where for<'a> F: FnMut(PageMutSlice<'a>) -> Result<()>
{
let range = normalize_address_range(address_range, 0, Self::RAMTOP)
.map_err(|_| ZxMemoryError::UnsupportedAddressRange)?;
let cursor = range.start;
let end = range.end;
let iter = MemPageMutIter { mem: self, cursor, end };
for page in iter {
f(page)?
}
Ok(())
}
fn load_into_mem<A: RangeBounds<u16>, R: Read>(&mut self, address_range: A, mut rd: R) -> Result<()> {
self.for_each_page_mut(address_range, |page| {
match page {
PageMutSlice::Rom(slice)|PageMutSlice::Ram(slice) => {
rd.read_exact(slice).map_err(ZxMemoryError::Io)
}
}
})
}
fn fill_mem<R, F>(&mut self, address_range: R, mut f: F) -> Result<()>
where R: RangeBounds<u16>, F: FnMut() -> u8
{
self.for_each_page_mut(address_range, |page| {
for p in page.into_mut_slice().iter_mut() {
*p = f()
}
Ok(())
})
}
}
pub struct MemPageRefIter<'a, Z: ?Sized> {
mem: &'a Z,
cursor: usize,
end: usize
}
impl<'a, Z: ZxMemory + ?Sized> Iterator for MemPageRefIter<'a, Z> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let cursor = self.cursor;
let end = self.end;
if cursor < end {
let MemPageOffset { index, offset, .. } = self.mem.page_index_at(cursor as u16).unwrap();
let offset = offset as usize;
let page = self.mem.page_ref(index).unwrap();
let read_len = end - cursor;
let read_end = page.len().min(offset + read_len);
let read_page = &page[offset..read_end];
self.cursor += read_page.len();
Some(read_page)
}
else {
None
}
}
}
struct MemPageMutIter<'a, Z: ?Sized> {
mem: &'a mut Z,
cursor: usize,
end: usize
}
impl<'a, Z: ZxMemory + ?Sized> Iterator for MemPageMutIter<'a, Z> {
type Item = PageMutSlice<'a>;
fn next(&mut self) -> Option<Self::Item> {
let cursor = self.cursor;
let end = self.end;
if cursor < end {
let MemPageOffset { kind, index, offset } = self.mem.page_index_at(cursor as u16).unwrap();
let offset = offset as usize;
let page = self.mem.page_mut(index).unwrap();
let page = unsafe { core::mem::transmute::<&mut[u8], &'a mut[u8]>(page) };
let read_len = end - cursor;
let read_end = page.len().min(offset + read_len);
let read_page = &mut page[offset..read_end];
self.cursor += read_page.len();
match kind {
MemoryKind::Rom => {
Some(PageMutSlice::Rom(read_page))
},
MemoryKind::Ram => {
Some(PageMutSlice::Ram(read_page))
}
}
}
else {
None
}
}
}
enum AddressRangeError {
StartBoundTooLow,
EndBoundTooHigh
}
fn normalize_address_range<R: RangeBounds<u16>>(
range: R,
min_inclusive: u16,
max_inclusive: u16
) -> core::result::Result<Range<usize>, AddressRangeError>
{
let start = match range.start_bound() {
Bound::Included(start) => if *start < min_inclusive {
return Err(AddressRangeError::StartBoundTooLow)
} else { *start as usize },
Bound::Excluded(start) => if *start < min_inclusive.saturating_sub(1) {
return Err(AddressRangeError::StartBoundTooLow)
} else { *start as usize + 1 },
Bound::Unbounded => min_inclusive as usize
};
let end = match range.end_bound() {
Bound::Included(end) => if *end > max_inclusive {
return Err(AddressRangeError::EndBoundTooHigh)
} else { *end as usize + 1},
Bound::Excluded(end) => if *end > max_inclusive.saturating_add(1) {
return Err(AddressRangeError::EndBoundTooHigh)
} else { *end as usize },
Bound::Unbounded => max_inclusive as usize + 1
};
Ok(start..end)
}