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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use std::ops::{RangeToInclusive, RangeInclusive, RangeFull, RangeFrom, RangeTo, IndexMut, Index, Range};
use self::super::{PortHandlerInstallError, PortHandler};
use self::super::super::PortsReadWrittenIterator;
use std::hash::{self, Hash};
use std::num::NonZeroU16;
use std::cmp::Ordering;
use std::fmt;
const PORTS_LEN: usize = 0xFF + 1;
pub struct Ports {
cache: Box<[u8; PORTS_LEN]>,
read: Box<[u64; PORTS_LEN / 64]>,
written: Box<[u64; PORTS_LEN / 64]>,
handlers: Vec<Option<Box<dyn PortHandler + 'static>>>,
handler_mappings: Box<[Option<NonZeroU16>; PORTS_LEN]>,
}
impl Ports {
pub fn new() -> Ports {
Ports {
cache: Box::new([0; PORTS_LEN]),
read: Box::new([0; PORTS_LEN / 64]),
written: Box::new([0; PORTS_LEN / 64]),
handlers: vec![],
handler_mappings: Box::new([None; PORTS_LEN]),
}
}
pub fn install_handler<H: PortHandler + 'static>(&mut self, handler: H, ports: &[u8]) -> Result<usize, (H, PortHandlerInstallError)> {
if self.handlers.len() == 0xFFFF {
return Err((handler, PortHandlerInstallError::TooManyHandlers));
}
let port_count = handler.port_count().get();
if ports.len() != port_count as usize {
return Err((handler, PortHandlerInstallError::WrongPortCount(ports.len(), port_count)));
}
if let Some(taken_ports) = self.verify_ports_free(ports) {
return Err((handler, PortHandlerInstallError::PortsTaken(taken_ports)));
}
Ok(self.install_handler_impl(Box::new(handler), ports))
}
fn verify_ports_free(&self, ports: &[u8]) -> Option<Vec<u8>> {
let mut taken_ports = vec![];
for &port in ports {
if self.handler_mappings[port as usize].is_some() {
taken_ports.push(port);
}
}
if !taken_ports.is_empty() {
Some(taken_ports)
} else {
None
}
}
fn install_handler_impl(&mut self, handler: Box<dyn PortHandler + 'static>, ports: &[u8]) -> usize {
self.handlers.push(Some(handler));
let handler_idx = self.handlers.len() - 1;
self.handlers[handler_idx].as_mut().unwrap().init(ports);
for &port in ports {
self.handler_mappings[port as usize] = NonZeroU16::new(handler_idx as u16 + 1);
}
handler_idx
}
pub fn get_handler(&self, idx: usize) -> Option<&(dyn PortHandler + 'static)> {
self.handlers.get(idx).and_then(|h| h.as_ref()).map(|h| h.as_ref())
}
pub fn get_handler_mut(&mut self, idx: usize) -> Option<&mut (dyn PortHandler + 'static)> {
self.handlers.get_mut(idx).and_then(|h| h.as_mut()).map(|h| h.as_mut())
}
pub fn uninstall_handler(&mut self, idx: usize) -> Option<Box<dyn PortHandler + 'static>> {
if idx >= self.handlers.len() {
return None;
}
let mut handler = self.handlers[idx].take()?;
handler.uninit();
let mut ports_left = handler.port_count().get();
let mapping = NonZeroU16::new(idx as u16 + 1);
for m in &mut self.handler_mappings[..] {
if *m == mapping {
*m = None;
ports_left -= 1;
if ports_left == 0 {
break;
}
}
}
Some(handler)
}
pub fn read(&mut self, port: u8) -> u8 {
let index = port as usize;
let idx = index / 64;
let bit = index % 64;
self.read[idx] |= 1 << bit;
if let Some(handler_idx) = self.handler_mappings[index] {
let new_val = self.handlers[handler_idx.get() as usize - 1].as_mut().unwrap().handle_read(port);
self.cache[index] = new_val;
}
self.cache[index]
}
pub fn write(&mut self, port: u8, byte: u8) {
let index = port as usize;
let idx = index / 64;
let bit = index % 64;
self.written[idx] |= 1 << bit;
if let Some(handler_idx) = self.handler_mappings[index] {
self.handlers[handler_idx.get() as usize - 1].as_mut().unwrap().handle_write(port, byte);
}
self.cache[index] = byte;
}
pub fn iter_rw(&self) -> PortsReadWrittenIterator {
PortsReadWrittenIterator::new(&self.cache[..], &self.read[..], &self.written[..])
}
pub fn reset_rw(&mut self) {
for r in &mut self.read[..] {
*r = 0;
}
for w in &mut self.written[..] {
*w = 0;
}
}
}
impl Default for Ports {
fn default() -> Ports {
Ports::new()
}
}
impl Drop for Ports {
fn drop(&mut self) {
for mut handler in self.handlers.drain(..).flatten() {
handler.uninit();
}
}
}
impl Index<Range<u8>> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: Range<u8>) -> &Self::Output {
self.cache.index(Range {
start: index.start as usize,
end: index.end as usize,
})
}
}
impl IndexMut<Range<u8>> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: Range<u8>) -> &mut Self::Output {
self.cache.index_mut(Range {
start: index.start as usize,
end: index.end as usize,
})
}
}
impl Index<RangeFrom<u8>> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: RangeFrom<u8>) -> &Self::Output {
self.cache.index(RangeFrom { start: index.start as usize })
}
}
impl IndexMut<RangeFrom<u8>> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: RangeFrom<u8>) -> &mut Self::Output {
self.cache.index_mut(RangeFrom { start: index.start as usize })
}
}
impl Index<RangeFull> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: RangeFull) -> &Self::Output {
self.cache.index(index)
}
}
impl IndexMut<RangeFull> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: RangeFull) -> &mut Self::Output {
self.cache.index_mut(index)
}
}
impl Index<RangeInclusive<u8>> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: RangeInclusive<u8>) -> &Self::Output {
let (start, end) = index.into_inner();
self.cache.index(RangeInclusive::new(start as usize, end as usize))
}
}
impl IndexMut<RangeInclusive<u8>> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: RangeInclusive<u8>) -> &mut Self::Output {
let (start, end) = index.into_inner();
self.cache.index_mut(RangeInclusive::new(start as usize, end as usize))
}
}
impl Index<RangeTo<u8>> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: RangeTo<u8>) -> &Self::Output {
self.cache.index(RangeTo { end: index.end as usize })
}
}
impl IndexMut<RangeTo<u8>> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: RangeTo<u8>) -> &mut Self::Output {
self.cache.index_mut(RangeTo { end: index.end as usize })
}
}
impl Index<RangeToInclusive<u8>> for Ports {
type Output = [u8];
#[inline(always)]
fn index(&self, index: RangeToInclusive<u8>) -> &Self::Output {
self.cache.index(RangeToInclusive { end: index.end as usize })
}
}
impl IndexMut<RangeToInclusive<u8>> for Ports {
#[inline(always)]
fn index_mut(&mut self, index: RangeToInclusive<u8>) -> &mut Self::Output {
self.cache.index_mut(RangeToInclusive { end: index.end as usize })
}
}
impl fmt::Debug for Ports {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ports")
.field("cache", &&self.cache[..])
.field("read", &&self.read[..])
.field("written", &&self.written[..])
.finish()
}
}
impl Hash for Ports {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&self[..], state)
}
}
impl PartialEq<[u8]> for Ports {
#[inline]
fn eq(&self, other: &[u8]) -> bool {
&self.cache[..] == other
}
}
impl PartialEq<Ports> for Ports {
#[inline]
fn eq(&self, other: &Ports) -> bool {
self.cache[..] == other.cache[..] && self.read[..] == other.read[..] && self.written[..] == other.written[..]
}
}
impl Eq for Ports {}
impl PartialOrd for Ports {
#[inline]
fn partial_cmp(&self, other: &Ports) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Ports {
#[inline]
fn cmp(&self, other: &Ports) -> Ordering {
Ord::cmp(&self.cache[..], &other.cache[..])
.then(Ord::cmp(&self.read[..], &other.read[..]))
.then(Ord::cmp(&self.written[..], &other.written[..]))
}
}