diff --git a/CHANGELOG.md b/CHANGELOG.md index 56a8325..6b219c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - install `rustfmt` and the Kani verifier automatically via `cargo install` - restore Kani proof best practices in `AGENTS.md` and note that proofs run via `verify.sh` - limit Kani loop unwind by default and set per-harness bounds +- `ByteBuffer::push` now accepts any `IntoBytes + Immutable` value when the + `zerocopy` feature is enabled - increase unwind for prefix/suffix overflow proofs - move weak reference and downcasting examples into module docs - expand module introduction describing use cases diff --git a/src/buffer.rs b/src/buffer.rs index 936c9a8..17ac996 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -102,7 +102,8 @@ impl ByteBuffer { self.cap = new_cap; } - /// Push a byte to the end of the buffer. + /// Push data to the end of the buffer. + #[cfg(not(feature = "zerocopy"))] pub fn push(&mut self, byte: u8) { self.reserve_more(1); unsafe { @@ -111,6 +112,20 @@ impl ByteBuffer { self.len += 1; } + /// Push data to the end of the buffer. + #[cfg(feature = "zerocopy")] + pub fn push(&mut self, value: T) + where + T: zerocopy::IntoBytes + zerocopy::Immutable, + { + let bytes = zerocopy::IntoBytes::as_bytes(&value); + self.reserve_more(bytes.len()); + unsafe { + ptr::copy_nonoverlapping(bytes.as_ptr(), self.ptr.as_ptr().add(self.len), bytes.len()); + } + self.len += bytes.len(); + } + /// Returns a raw pointer to the buffer's memory. pub fn as_ptr(&self) -> *const u8 { self.ptr.as_ptr() diff --git a/src/tests.rs b/src/tests.rs index f4d8903..2495784 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -308,9 +308,9 @@ fn test_bytebuffer_push_and_bytes() { use crate::ByteBuffer; let mut buf: ByteBuffer<8> = ByteBuffer::with_capacity(2); - buf.push(1); - buf.push(2); - buf.push(3); + buf.push(1u8); + buf.push(2u8); + buf.push(3u8); assert_eq!(buf.as_ref(), &[1, 2, 3]); let bytes: Bytes = buf.into(); @@ -322,7 +322,7 @@ fn test_bytebuffer_alignment() { use crate::ByteBuffer; let mut buf: ByteBuffer<64> = ByteBuffer::with_capacity(1); - buf.push(1); + buf.push(1u8); assert_eq!((buf.as_ptr() as usize) % 64, 0); } @@ -334,7 +334,7 @@ fn test_bytebuffer_reserve_total() { buf.reserve_total(10); assert!(buf.capacity() >= 10); for _ in 0..10 { - buf.push(1); + buf.push(1u8); } assert_eq!(buf.len(), 10); assert!(buf.capacity() >= 10);