From 9fc9581611eb3846a2a8afd04fd5b68847c8e3e1 Mon Sep 17 00:00:00 2001 From: kaidokert Date: Sun, 29 Dec 2024 17:43:18 -0800 Subject: [PATCH] Add Read from mutable slices Signed-off-by: kaidokert --- ciborium-io/src/lib.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ciborium-io/src/lib.rs b/ciborium-io/src/lib.rs index f5f1f23..94c3126 100644 --- a/ciborium-io/src/lib.rs +++ b/ciborium-io/src/lib.rs @@ -152,6 +152,19 @@ impl Write for &mut [u8] { } } +#[cfg(not(feature = "std"))] +impl Read for &mut [u8] { + type Error = EndOfFile; + + #[inline] + fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { + let mut immutable : &[u8] = self; + immutable.read_exact(data)?; + *self = &mut core::mem::take(self)[data.len()..]; + Ok(()) + } +} + #[cfg(all(not(feature = "std"), feature = "alloc"))] impl Write for alloc::vec::Vec { type Error = core::convert::Infallible; @@ -205,6 +218,20 @@ mod test { reader.read_exact(&mut buffer[..]).unwrap_err(); } + #[test] + fn read_mut_two() { + let mut reader = &mut [1u8; 2][..]; + let mut buffer = [0u8; 1]; + + reader.read_exact(&mut buffer[..]).unwrap(); + assert_eq!(buffer[0], 1); + + reader.read_exact(&mut buffer[..]).unwrap(); + assert_eq!(buffer[0], 1); + + reader.read_exact(&mut buffer[..]).unwrap_err(); + } + #[test] #[cfg(feature = "std")] fn read_std() {