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
//! Bus Adapters to translate address and error type

use crate::{BasicBusError, BusAccess, ErrorType, Instant as EmuInstant};
use core::marker::PhantomData;

/// Used to translate an address from one address space into another
pub trait FromAddress<T> {
    /// Translate the given address into an address of type `Self`
    fn from_address(address: T) -> Self;
}

/// Used to translate an address from one address space into another
pub trait IntoAddress<T> {
    /// Translate the given address into an address of type `T`
    fn into_address(self) -> T;
}

impl<T, S> IntoAddress<T> for S
where
    T: FromAddress<S>,
{
    fn into_address(self) -> T {
        T::from_address(self)
    }
}

/// An adapter that applies an address translation before accessing a wrapped bus object
///
/// This object implements the `BusAccess` trait, and takes address of type `AddressIn`,
/// applies the provided address translation function to produce an address of type `AddressOut`,
/// and then calls the equivalent trait method with that produced address, return the result
pub struct BusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressIn: Copy,
    AddressOut: Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: From<Bus::Error>,
{
    /// The underlying object implementing `BusAccess` that this object adapts
    pub inner: Bus,
    /// The translation function applied
    pub translate: fn(AddressIn) -> AddressOut,
    /// Marker for the error type
    error_out: PhantomData<ErrorOut>,
}

impl<AddressIn, AddressOut, Bus, ErrorOut> BusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressIn: Copy,
    AddressOut: Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: From<Bus::Error>,
{
    /// Construct a new instance of an adapter for the given `bus` object
    pub fn new(inner: Bus, translate: fn(AddressIn) -> AddressOut) -> Self {
        Self {
            inner,
            translate,
            error_out: PhantomData,
        }
    }
}

impl<AddressIn, AddressOut, Bus, ErrorOut> BusAccess<AddressIn>
    for BusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressIn: Copy,
    AddressOut: Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: ErrorType + From<Bus::Error>,
{
    type Instant = Bus::Instant;
    type Error = ErrorOut;

    #[inline]
    fn read(
        &mut self,
        now: Self::Instant,
        addr: AddressIn,
        data: &mut [u8],
    ) -> Result<usize, Self::Error> {
        let addr = (self.translate)(addr);
        self.inner.read(now, addr, data).map_err(|err| err.into())
    }

    #[inline]
    fn write(
        &mut self,
        now: Self::Instant,
        addr: AddressIn,
        data: &[u8],
    ) -> Result<usize, Self::Error> {
        let addr = (self.translate)(addr);
        self.inner.write(now, addr, data).map_err(|err| err.into())
    }
}

/// An adapter that uses the `FromAddress` trait to translate an address before accessing a wrapped bus object
///
/// This object implements the `BusAccess` trait, and takes address of type `AddressIn`,
/// applies `FromAddress<AddressIn>` trait to produce an address of type `AddressOut`,
/// and then calls the equivalent trait method with that produced address, return the result
pub struct AutoBusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressOut: FromAddress<AddressIn> + Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: From<Bus::Error>,
{
    /// The underlying object implementing `BusAccess` that this object adapts
    pub inner: Bus,

    address_in: PhantomData<AddressIn>,
    address_out: PhantomData<AddressOut>,
    error_out: PhantomData<ErrorOut>,
}

impl<AddressIn, AddressOut, Bus, ErrorOut> AutoBusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressOut: FromAddress<AddressIn> + Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: From<Bus::Error>,
{
    /// Construct a new instance of an adapter for the given `bus` object
    pub fn new(inner: Bus) -> Self {
        Self {
            inner,
            address_in: PhantomData,
            address_out: PhantomData,
            error_out: PhantomData,
        }
    }
}

impl<AddressIn, AddressOut, Bus, ErrorOut> BusAccess<AddressIn>
    for AutoBusAdapter<AddressIn, AddressOut, Bus, ErrorOut>
where
    AddressIn: Copy,
    AddressOut: FromAddress<AddressIn> + Copy,
    Bus: BusAccess<AddressOut>,
    ErrorOut: ErrorType + From<Bus::Error>,
{
    type Instant = Bus::Instant;
    type Error = ErrorOut;

    #[inline]
    fn read(
        &mut self,
        now: Self::Instant,
        addr: AddressIn,
        data: &mut [u8],
    ) -> Result<usize, Self::Error> {
        let addr = addr.into_address();
        self.inner.read(now, addr, data).map_err(|err| err.into())
    }

    #[inline]
    fn write(
        &mut self,
        now: Self::Instant,
        addr: AddressIn,
        data: &[u8],
    ) -> Result<usize, Self::Error> {
        let addr = addr.into_address();
        self.inner.write(now, addr, data).map_err(|err| err.into())
    }
}

/// A dummy object that implements BusAccess, but does nothing
///
/// This object can be used instead of `Option<Bus>` when an optional bus is not provided
#[derive(Copy, Clone, Debug, Default)]
pub struct NoBus<Instant>(PhantomData<Instant>);

impl<Instant> NoBus<Instant> {
    /// Returns a new dummy bus
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<Address, Instant> BusAccess<Address> for NoBus<Instant>
where
    Address: Copy,
    Instant: EmuInstant,
{
    type Instant = Instant;
    type Error = BasicBusError;

    #[inline]
    fn read(
        &mut self,
        _now: Self::Instant,
        _addr: Address,
        _data: &mut [u8],
    ) -> Result<usize, Self::Error> {
        Ok(0)
    }

    #[inline]
    fn write(
        &mut self,
        _now: Self::Instant,
        _addr: Address,
        _data: &[u8],
    ) -> Result<usize, Self::Error> {
        Ok(0)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::ErrorType;
    use std::time::Duration;

    #[derive(Clone, Debug)]
    enum Error {}

    impl ErrorType for Error {}

    struct Memory(Vec<u8>);

    impl BusAccess<u64> for Memory {
        type Instant = Duration;
        type Error = Error;

        fn read(
            &mut self,
            _now: Duration,
            addr: u64,
            data: &mut [u8],
        ) -> Result<usize, Self::Error> {
            let addr = addr as usize;
            data.copy_from_slice(&self.0[addr..addr + data.len()]);
            Ok(data.len())
        }

        fn write(&mut self, _now: Duration, addr: u64, data: &[u8]) -> Result<usize, Self::Error> {
            let addr = addr as usize;
            self.0[addr..addr + data.len()].copy_from_slice(data);
            Ok(data.len())
        }
    }

    type Address = u8;
    impl FromAddress<Address> for u64 {
        fn from_address(address: Address) -> u64 {
            address as u64
        }
    }

    #[derive(Clone, Debug)]
    enum Error2 {
        BusError,
    }

    impl ErrorType for Error2 {}

    impl From<Error> for Error2 {
        fn from(_err: Error) -> Self {
            Error2::BusError
        }
    }

    #[test]
    fn test_adapt_address() {
        let bus = Memory(vec![0; 1024]);

        let mut adapter = BusAdapter::new(bus, |addr| addr as u64);

        let expected_value = 0x1234;
        adapter
            .write_beu16(Duration::ZERO, 0, expected_value)
            .unwrap();
        let result: Result<u16, Error> = adapter.read_beu16(Duration::ZERO, 0);
        assert_eq!(result.unwrap(), expected_value);
    }

    #[test]
    fn test_adapt_error() {
        let bus = Memory(vec![0; 1024]);

        let mut adapter = BusAdapter::new(bus, |addr| addr as u64);

        let expected_value = 0x1234;
        adapter
            .write_beu16(Duration::ZERO, 0, expected_value)
            .unwrap();
        let result: Result<u16, Error2> = adapter.read_beu16(Duration::ZERO, 0);
        assert_eq!(result.unwrap(), expected_value);
    }

    #[test]
    fn test_auto_adapt_address() {
        let bus = Memory(vec![0; 1024]);

        let mut adapter = AutoBusAdapter::new(bus);

        let expected_value = 0x1234;
        adapter
            .write_beu16(Duration::ZERO, 0, expected_value)
            .unwrap();
        let result: Result<u16, Error> = adapter.read_beu16(Duration::ZERO, 0);
        assert_eq!(result.unwrap(), expected_value);
    }

    #[test]
    fn test_auto_adapt_error() {
        let bus = Memory(vec![0; 1024]);

        let mut adapter = AutoBusAdapter::new(bus);

        let expected_value = 0x1234;
        adapter
            .write_beu16(Duration::ZERO, 0, expected_value)
            .unwrap();
        let result: Result<u16, Error2> = adapter.read_beu16(Duration::ZERO, 0);
        assert_eq!(result.unwrap(), expected_value);
    }
}