Skip to content

Commit 5ce8ccd

Browse files
committed
Implement bytes::Buf for Vec.
1 parent 1ea9009 commit 5ce8ccd

File tree

1 file changed

+54
-5
lines changed

1 file changed

+54
-5
lines changed

src/bytes.rs

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,34 @@
11
//! Bytes implementations for heapless types
22
33
use crate::Vec;
4-
use bytes::buf::UninitSlice;
5-
use bytes::BufMut;
4+
use bytes::{buf::UninitSlice, Buf, BufMut};
5+
6+
unsafe impl<const N: usize> Buf for Vec<u8, N> {
7+
#[inline]
8+
fn remaining(&self) -> usize {
9+
self.len()
10+
}
11+
12+
#[inline]
13+
fn chunk(&mut self) -> &[u8] {
14+
self.as_slice()
15+
}
16+
17+
#[inline]
18+
unsafe fn advance(&mut self, cnt: usize) {
19+
assert!(
20+
cnt <= self.remaining(),
21+
"cannot advance past `remaining`: {:?} <= {:?}",
22+
cnt,
23+
self.remaining(),
24+
);
25+
unsafe {
26+
// SAFETY: We've checked that `cnt` <= `self.remaining()` and we know that
27+
// `self.remaining()` <= `self.cap`.
28+
self.advance_unchecked(cnt);
29+
}
30+
}
31+
}
632

733
unsafe impl<const N: usize> BufMut for Vec<u8, N> {
834
#[inline]
@@ -35,21 +61,44 @@ mod tests {
3561

3662
#[test]
3763
#[should_panic]
38-
fn advance_out_of_bound() {
64+
fn buf_advance_out_of_bounds() {
65+
let mut vec: Vec<u8, 8> = Vec::new();
66+
vec.advance(9)
67+
}
68+
69+
#[test]
70+
fn buf_remaining() {
71+
let mut vec: Vec<u8, 8> = Vec::new();
72+
assert_eq!(vec.remaining(), 8);
73+
vec.push(42).unwrap();
74+
assert_eq!(vec.remaining(), 7);
75+
}
76+
77+
#[test]
78+
fn buf_chunk() {
79+
let mut vec: Vec<u8, 8> = Vec::new();
80+
assert_eq!(vec.chunk().len(), 8);
81+
unsafe { vec.advance_mut(1) };
82+
assert_eq!(vec.chunk().len(), 7);
83+
}
84+
85+
#[test]
86+
#[should_panic]
87+
fn buf_mut_advance_mut_out_of_bounds() {
3988
let mut vec: Vec<u8, 8> = Vec::new();
4089
unsafe { vec.advance_mut(9) };
4190
}
4291

4392
#[test]
44-
fn remaining_mut() {
93+
fn buf_mut_remaining_mut() {
4594
let mut vec: Vec<u8, 8> = Vec::new();
4695
assert_eq!(vec.remaining_mut(), 8);
4796
vec.push(42).unwrap();
4897
assert_eq!(vec.remaining_mut(), 7);
4998
}
5099

51100
#[test]
52-
fn chunk_mut() {
101+
fn buf_mut_chunk_mut() {
53102
let mut vec: Vec<u8, 8> = Vec::new();
54103
assert_eq!(vec.chunk_mut().len(), 8);
55104
unsafe { vec.advance_mut(1) };

0 commit comments

Comments
 (0)