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
#![feature(asm, const_fn, no_std)]
#![no_std]
use core::marker::PhantomData;
#[cfg(any(target_arch="x86", target_arch="x86_64"))]
pub use x86::{inb, outb, inw, outw, inl, outl};
#[cfg(any(target_arch="x86", target_arch="x86_64"))]
mod x86;
pub trait InOut {
unsafe fn port_in(port: u16) -> Self;
unsafe fn port_out(port: u16, value: Self);
}
impl InOut for u8 {
unsafe fn port_in(port: u16) -> u8 { inb(port) }
unsafe fn port_out(port: u16, value: u8) { outb(value, port); }
}
impl InOut for u16 {
unsafe fn port_in(port: u16) -> u16 { inw(port) }
unsafe fn port_out(port: u16, value: u16) { outw(value, port); }
}
impl InOut for u32 {
unsafe fn port_in(port: u16) -> u32 { inl(port) }
unsafe fn port_out(port: u16, value: u32) { outl(value, port); }
}
#[derive(Debug)]
pub struct Port<T: InOut> {
port: u16,
phantom: PhantomData<T>,
}
impl<T: InOut> Port<T> {
pub const unsafe fn new(port: u16) -> Port<T> {
Port { port: port, phantom: PhantomData }
}
pub fn read(&mut self) -> T {
unsafe { T::port_in(self.port) }
}
pub fn write(&mut self, value: T) {
unsafe { T::port_out(self.port, value); }
}
}
#[derive(Debug)]
pub struct UnsafePort<T: InOut> {
port: u16,
phantom: PhantomData<T>,
}
impl<T: InOut> UnsafePort<T> {
pub const unsafe fn new(port: u16) -> UnsafePort<T> {
UnsafePort { port: port, phantom: PhantomData }
}
pub unsafe fn read(&mut self) -> T {
T::port_in(self.port)
}
pub unsafe fn write(&mut self, value: T) {
T::port_out(self.port, value);
}
}