Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Bytes #340

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
58 changes: 58 additions & 0 deletions src/bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//! Bytes implementations for heapless types

use crate::Vec;
use bytes::buf::UninitSlice;
use bytes::BufMut;

unsafe impl<const N: usize> BufMut for Vec<u8, N> {
#[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<u8, 8> = Vec::new();
unsafe { vec.advance_mut(9) };
}

#[test]
fn remaining_mut() {
let mut vec: Vec<u8, 8> = 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<u8, 8> = Vec::new();
assert_eq!(vec.chunk_mut().len(), 8);
unsafe { vec.advance_mut(1) };
assert_eq!(vec.chunk_mut().len(), 7);
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand Down