我正在实现 SPI 驱动程序。
现在我有以下驱动程序代码(MRE 化):
use tokio::{join, sync::mpsc};
async fn spi_transmit(write_buf: &[u32], read_buf: &mut [u32]) {
assert_eq!(read_buf.len(), write_buf.len());
let (write_fifo, mut read_fifo) = mpsc::channel(2);
let write_task = async {
// Simulate an SPI bus that respondes with the sent data + 20,
// just for demo purposes
for val in write_buf {
write_fifo.send(*val + 20).await.unwrap();
}
};
let read_task = async {
for val in read_buf {
*val = read_fifo.recv().await.unwrap();
}
};
join!(write_task, read_task);
}
#[tokio::main]
async fn main() {
let buf_out = [1, 2, 3, 4];
let mut buf_in = [0, 0, 0, 0];
spi_transmit(&buf_out, &mut buf_in).await;
println!("{:?}", buf_in);
}
[21, 22, 23, 24]
中央 API 是async fn spi_transmit(write_buf: &[u32], read_buf: &mut [u32])
.
现在我需要实现一个async fn spi_transmit_in_place(read_write_buf: &mut [u32])
从同一个缓冲区发送和接收的缓冲区,该缓冲区最终包含读取的数据。
我知道对缓冲区的读写访问永远不会重叠,总是先读取一个字节,然后在稍后的非重叠时间写入它。
有了这些知识,如果我这样实现它是否被认为是合理的,或者这被认为是未定义的行为?
async fn spi_transmit_in_place(read_write_buf: &mut [u32]) {
let write_buf = unsafe {
let data = read_write_buf.as_ptr();
let len = read_write_buf.len();
std::slice::from_raw_parts(data, len)
};
spi_transmit(write_buf, read_write_buf).await
}
#[tokio::main]
async fn main() {
let mut buf = [1, 2, 3, 4];
spi_transmit_in_place(&mut buf).await;
println!("{:?}", buf);
}
[21, 22, 23, 24]
它有效,但miri 不高兴。
spi_transmit
如果这是未定义的行为,这是否意味着我必须使用原始指针重新实现?或者我还能怎样解决这个问题?