Skip to content

Commit a105876

Browse files
committed
io-async: add impls for slices.
1 parent d6f6419 commit a105876

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed

embedded-io-async/src/impls/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
mod slice_mut;
2+
mod slice_ref;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use crate::Write;
2+
use core::mem;
3+
4+
/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
5+
/// its data.
6+
///
7+
/// Note that writing updates the slice to point to the yet unwritten part.
8+
/// The slice will be empty when it has been completely overwritten.
9+
///
10+
/// If the number of bytes to be written exceeds the size of the slice, write operations will
11+
/// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
12+
/// kind `ErrorKind::WriteZero`.
13+
impl Write for &mut [u8] {
14+
#[inline]
15+
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
16+
let amt = core::cmp::min(buf.len(), self.len());
17+
let (a, b) = mem::take(self).split_at_mut(amt);
18+
a.copy_from_slice(&buf[..amt]);
19+
*self = b;
20+
Ok(amt)
21+
}
22+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use crate::{BufRead, Read};
2+
3+
/// Read is implemented for `&[u8]` by copying from the slice.
4+
///
5+
/// Note that reading updates the slice to point to the yet unread part.
6+
/// The slice will be empty when EOF is reached.
7+
impl Read for &[u8] {
8+
#[inline]
9+
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
10+
let amt = core::cmp::min(buf.len(), self.len());
11+
let (a, b) = self.split_at(amt);
12+
13+
// First check if the amount of bytes we want to read is small:
14+
// `copy_from_slice` will generally expand to a call to `memcpy`, and
15+
// for a single byte the overhead is significant.
16+
if amt == 1 {
17+
buf[0] = a[0];
18+
} else {
19+
buf[..amt].copy_from_slice(a);
20+
}
21+
22+
*self = b;
23+
Ok(amt)
24+
}
25+
}
26+
27+
impl BufRead for &[u8] {
28+
#[inline]
29+
async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
30+
Ok(*self)
31+
}
32+
33+
#[inline]
34+
fn consume(&mut self, amt: usize) {
35+
*self = &self[amt..];
36+
}
37+
}

embedded-io-async/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
#![warn(missing_docs)]
55
#![doc = include_str!("../README.md")]
66

7+
mod impls;
8+
79
pub use embedded_io::{Error, ErrorKind, Io, ReadExactError, SeekFrom, WriteAllError};
810

911
/// Async reader.

0 commit comments

Comments
 (0)