From a92e777f38fda6d4d055339d0d300119065e8e37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?xgroleau=F0=9F=90=A2?= Date: Wed, 25 Jan 2023 17:59:05 -0500 Subject: [PATCH] Added support for Bytes --- Cargo.toml | 5 +++++ src/bytes.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 ++ 3 files changed, 65 insertions(+) create mode 100644 src/bytes.rs diff --git a/Cargo.toml b/Cargo.toml index 292bc35175..b13c8267da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,3 +71,8 @@ rustc_version = "0.4.0" [package.metadata.docs.rs] all-features = true + +[dependencies.bytes] +version = "1" +optional = true +default-features = false diff --git a/src/bytes.rs b/src/bytes.rs new file mode 100644 index 0000000000..437903a164 --- /dev/null +++ b/src/bytes.rs @@ -0,0 +1,58 @@ +//! Bytes implementations for heapless types + +use crate::Vec; +use bytes::buf::UninitSlice; +use bytes::BufMut; + +unsafe impl BufMut for Vec { + #[inline] + fn remaining_mut(&self) -> usize { + N - self.len() + } + + #[inline] + unsafe fn advance_mut(&mut self, cnt: usize) { + let len = self.len(); + let pos = len + cnt; + if pos >= N { + panic!("Advance out of range"); + } + self.set_len(pos); + } + + #[inline] + fn chunk_mut(&mut self) -> &mut UninitSlice { + let len = self.len(); + let ptr = self.as_mut_ptr(); + unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, N)[len..] } + } +} + +#[cfg(test)] +mod tests { + use crate::Vec; + use bytes::BufMut; + + #[test] + #[should_panic] + fn advance_out_of_bound() { + let mut vec: Vec = Vec::new(); + unsafe { vec.advance_mut(9) }; + } + + #[test] + fn remaining_mut() { + let mut vec: Vec = Vec::new(); + assert_eq!(vec.remaining_mut(), 8); + vec.push(42).unwrap(); + assert_eq!(vec.remaining_mut(), 7); + } + + #[test] + fn chunk_mut() { + let mut vec: Vec = Vec::new(); + assert_eq!(vec.chunk_mut().len(), 8); + unsafe { vec.advance_mut(1) }; + assert_eq!(vec.chunk_mut().len(), 7); + } +} diff --git a/src/lib.rs b/src/lib.rs index b6ca41ff9e..67fe63946e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,6 +110,8 @@ mod de; mod ser; pub mod binary_heap; +#[cfg(feature = "bytes")] +mod bytes; #[cfg(feature = "defmt-impl")] mod defmt; #[cfg(all(has_cas, feature = "cas"))]