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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Helper structs make both [WriteU8] and [WriteU8s] available when only one
//! is implemented.

use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};

use crate::spi;
use spi::{DcxPin, Read, WriteU8, WriteU8s};

/// A helper to add [WriteU8s] support when [WriteU8] is implemented.
///
/// Supposedly **not** very efficient. See the Performance Consideration section
/// of the module [spi].
pub struct AdapterU8<W> { w: W }

impl<W> AdapterU8<W> {
    pub fn new(w: W) -> Self { Self{w} }
}

impl<W: DcxPin> DcxPin for AdapterU8<W> {
    fn set_dcx_command_mode(&mut self) { self.w.set_dcx_command_mode(); }
    fn set_dcx_data_mode(&mut self) { self.w.set_dcx_data_mode(); }
}

impl<'a, W: Read<'a>> Read<'a> for AdapterU8<W> {
    type ReadBitsType = <W as Read<'a>>::ReadBitsType;

    fn start_reading(&'a mut self) -> Self::ReadBitsType {
        self.w.start_reading()
    }
}

impl<'a, W: WriteU8<'a>> WriteU8<'a> for AdapterU8<W> {
    type WriteU8Done = <W as WriteU8<'a>>::WriteU8Done;

    fn write_u8(&'a mut self, data: u8) -> Self::WriteU8Done {
        self.w.write_u8(data)
    }
}

impl<'a, W: 'a> WriteU8s<'a> for AdapterU8<W> where for<'w> W: WriteU8<'w> {
    type WriteU8sDone = RepeatU8<'a, W>;

    fn write_u8s(&'a mut self, data: &'a [u8]) -> Self::WriteU8sDone {
        RepeatU8{data, w: &mut self.w, current_write: None}
    }
}

/// Internal details of [AdapterU8].
pub struct RepeatU8<'a, W: for<'w> WriteU8<'w>> {
    data: &'a [u8],
    // Lifetime is also 'a. `current_write` when not `None` can actually borrow
    // `*w` in mut.
    w: *mut W,
    current_write: Option<<W as WriteU8<'a>>::WriteU8Done>,
}

impl<'a, W: 'a + for<'w> WriteU8<'w>> Future for RepeatU8<'a, W> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        // Safety: Only `Self::current_write` needs pinning. The implementation
        // below indeed never moves it, only creates and drops.
        let ru = unsafe {self.get_unchecked_mut()};
        loop {
            if ru.current_write.is_none() {
                if let Some((first, remaining)) = ru.data.split_first() {
                    // Safety: `current_write` is `None`.
                    let w: &'a mut W = unsafe {&mut *ru.w};
                    ru.current_write = Some(w.write_u8(*first));
                    ru.data = remaining;
                } else {
                    return Poll::Ready(());
                }
            }
            if let Some(ref mut done) = &mut ru.current_write {
                // Safety: Pinning a field of a pinned.
                let done = unsafe {Pin::new_unchecked(done)};
                if done.poll(cx).is_pending() {
                    return Poll::Pending;
                }
            } else {
                unsafe {core::hint::unreachable_unchecked()};
            }
            ru.current_write = None;
        }
    }
}

#[cfg(test)]
mod adapter_u8_tests {
    use mockall::Sequence;
    use mockall::predicate::eq;

    use crate::spi::ReadBits as _;
    use crate::testing_device::{block_on, MockDevice};
    use super::*;

    #[test]
    fn write_u8_as_is() {
        let mut a = AdapterU8::new(MockDevice::new());
        a.set_dcx_command_mode();
        a.w.mock().expect_write_command()
            .with(eq(0x34))
            .times(1);
        block_on(a.write_u8(0x34));
    }

    #[test]
    fn write_u8s() {
        let mut a = AdapterU8::new(MockDevice::new());
        a.set_dcx_data_mode();
        let mut seq = mockall::Sequence::new();
        a.w.mock().expect_write_data()
            .with(eq(0x34))
            .times(1)
            .in_sequence(&mut seq);
        a.w.mock().expect_write_data()
            .with(eq(0x56))
            .times(1)
            .in_sequence(&mut seq);
        a.w.mock().expect_write_data()
            .with(eq(0x12))
            .times(1)
            .in_sequence(&mut seq);
        block_on(a.write_u8s(&[0x34, 0x56, 0x12]));
    }

    #[test]
    fn read_as_is() {
        let src: u32 = 0b111010;
        let src_len: usize = 6;

        let mut a = AdapterU8::new(MockDevice::new());
        let mut seq = Sequence::new();
        a.w.mock().expect_start_reading().times(1).in_sequence(&mut seq);
        for i in (0..src_len).rev() {
            let bit = src >> i & 1 != 0;
            a.w.mock().expect_read_bit()
                .times(1)
                .in_sequence(&mut seq)
                .returning(move || bit);
        }
        a.w.mock().expect_finish_reading().times(1).in_sequence(&mut seq);

        let value = block_on(a.start_reading().read_bits(src_len));
        assert_eq!(value, src);
    }
}  // mod adapter_u8_tests

/// A helper to add [WriteU8] support when [WriteU8s] is implemented.
///
/// There is a slightly overhead on using an array to represent an element,
/// especially when the compiler fails to inline the functions. The user
/// should decide on their own whether they need to implement [WriteU8] and
/// [WriteU8s] individually.
pub struct AdapterU8s<W> { w: W, buf: u8 }

impl<W> AdapterU8s<W> {
    pub fn new(w: W) -> Self { Self{w, buf: 0} }
}

impl<W: DcxPin> DcxPin for AdapterU8s<W> {
    fn set_dcx_command_mode(&mut self) { self.w.set_dcx_command_mode(); }
    fn set_dcx_data_mode(&mut self) { self.w.set_dcx_data_mode(); }
}

impl<'a, W: Read<'a>> Read<'a> for AdapterU8s<W> {
    type ReadBitsType = <W as Read<'a>>::ReadBitsType;

    fn start_reading(&'a mut self) -> Self::ReadBitsType {
        self.w.start_reading()
    }
}

impl<'a, W: WriteU8s<'a>> WriteU8s<'a> for AdapterU8s<W> {
    type WriteU8sDone = <W as WriteU8s<'a>>::WriteU8sDone;

    fn write_u8s(&'a mut self, data: &'a [u8]) -> Self::WriteU8sDone {
        self.w.write_u8s(data)
    }
}

impl<'a, W: WriteU8s<'a>> WriteU8<'a> for AdapterU8s<W> {
    type WriteU8Done = <W as WriteU8s<'a>>::WriteU8sDone;

    fn write_u8(&'a mut self, data: u8) -> Self::WriteU8Done {
        self.buf = data;
        self.w.write_u8s(core::slice::from_ref(&self.buf))
    }
}

#[cfg(test)]
mod adapter_u8s_tests {
    use predicates::prelude::*;
    use mockall::Sequence;
    use std::{boxed::Box, format, vec::Vec};  // TODO: Remove after mockall 0.9.2+.

    use crate::spi::ReadBits as _;
    use crate::testing_device::{block_on, MockDevice};
    use super::*;

    #[mockall::automock]
    trait BatchIO {
        fn write(&mut self, data: &[u8]);
    }

    #[derive(Default)]
    struct MockBatchDevice { mock: MockBatchIO }

    impl<'a> WriteU8s<'a> for MockBatchDevice {
        type WriteU8sDone = Pin<Box<dyn Future<Output=()> + 'a>>;

        fn write_u8s(&'a mut self, data: &'a [u8]) -> Self::WriteU8sDone {
            Box::pin(async move { self.mock.write(data); })
        }
    }

    fn create_batch_mock() -> AdapterU8s<MockBatchDevice> {
        AdapterU8s::new(Default::default())
    }

    #[test]
    fn write_u8s_as_is() {
        let mut a = create_batch_mock();
        let eq = predicate::function(|array| {
            array == &[0x35, 0x46, 0x12, 0xFF]
        });
        a.w.mock.expect_write()
            .with(eq)
            .times(1);
        block_on(a.write_u8s(&[0x35, 0x46, 0x12, 0xFF]));
    }

    #[test]
    fn write_u8() {
        let mut a = create_batch_mock();
        let eq = predicate::function(|array| { array == &[0x37] });
        a.w.mock.expect_write()
            .with(eq)
            .times(1);
        block_on(a.write_u8(0x37));
    }

    #[test]
    fn dcx_modes() {
        let mut a = AdapterU8::new(MockDevice::new());
        let mut seq = Sequence::new();
        a.w.mock().expect_write_data()
            .with(predicate::eq(9))
            .times(1)
            .in_sequence(&mut seq);
        a.w.mock().expect_write_command()
            .with(predicate::eq(8))
            .times(1)
            .in_sequence(&mut seq);
        a.w.mock().expect_write_data()
            .with(predicate::eq(7))
            .times(1)
            .in_sequence(&mut seq);
        a.w.mock().expect_write_command()
            .with(predicate::eq(6))
            .times(1)
            .in_sequence(&mut seq);
        a.set_dcx_data_mode();
        block_on(a.write_u8(9));
        a.set_dcx_command_mode();
        block_on(a.write_u8(8));
        a.set_dcx_data_mode();
        block_on(a.write_u8(7));
        a.set_dcx_command_mode();
        block_on(a.write_u8(6));
    }

    #[test]
    fn read_as_is() {
        let src: u32 = 0b111010;
        let src_len: usize = 6;

        let mut a = AdapterU8::new(MockDevice::new());
        let mut seq = Sequence::new();
        a.w.mock().expect_start_reading().times(1).in_sequence(&mut seq);
        for i in (0..src_len).rev() {
            let bit = src >> i & 1 != 0;
            a.w.mock().expect_read_bit()
                .times(1)
                .in_sequence(&mut seq)
                .returning(move || bit);
        }
        a.w.mock().expect_finish_reading().times(1).in_sequence(&mut seq);

        let value = block_on(a.start_reading().read_bits(src_len));
        assert_eq!(value, src);
    }
}  // mod adapter_u8s_tests