//! Implementation of `embedded_hal::blocking::spi::Transfer` for `linux_embedded_hal::spidev`.

use std::io;

use embedded_hal::blocking::spi::Transfer;
use linux_embedded_hal::spidev::Spidev;
use linux_embedded_hal::spidev::SpidevTransfer;

/// Wrapper around `linux_embedded_hal::spidev::Spidev` which provides `Transfer`.
pub struct EmbeddedHalSpidev {
    spi: Spidev,
}

impl From<Spidev> for EmbeddedHalSpidev {
    fn from(s: Spidev) -> EmbeddedHalSpidev {
        EmbeddedHalSpidev { spi: s }
    }
}

impl Transfer<u8> for EmbeddedHalSpidev {
    type Error = io::Error;
    fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> {
        let words_copy = words.to_vec();
        let mut transfer = SpidevTransfer::read_write(&words_copy, words);
        self.spi.transfer(&mut transfer)?;
        Ok(words)
    }
}
