Skip to content

Commit 79e06c6

Browse files
committed
implement buf_try_get_impl with try_get_array
1 parent f54e65e commit 79e06c6

File tree

1 file changed

+4
-27
lines changed

1 file changed

+4
-27
lines changed

src/buf/buf_impl.rs

+4-27
Original file line numberDiff line numberDiff line change
@@ -12,33 +12,9 @@ use alloc::boxed::Box;
1212

1313
macro_rules! buf_try_get_impl {
1414
($this:ident, $typ:tt::$conv:tt) => {{
15-
const SIZE: usize = core::mem::size_of::<$typ>();
16-
17-
if $this.remaining() < SIZE {
18-
return Err(TryGetError {
19-
requested: SIZE,
20-
available: $this.remaining(),
21-
});
22-
}
23-
24-
// try to convert directly from the bytes
25-
// this Option<ret> trick is to avoid keeping a borrow on self
26-
// when advance() is called (mut borrow) and to call bytes() only once
27-
let ret = $this
28-
.chunk()
29-
.get(..SIZE)
30-
.map(|src| unsafe { $typ::$conv(*(src as *const _ as *const [_; SIZE])) });
31-
32-
if let Some(ret) = ret {
33-
// if the direct conversion was possible, advance and return
34-
$this.advance(SIZE);
35-
return Ok(ret);
36-
} else {
37-
// if not we copy the bytes in a temp buffer then convert
38-
let mut buf = [0; SIZE];
39-
$this.copy_to_slice(&mut buf); // (do the advance)
40-
return Ok($typ::$conv(buf));
41-
}
15+
// add indirection so self doesnot need to bee sized
16+
let mut this = $this;
17+
(&mut this).try_get_array().map($typ::$conv)
4218
}};
4319
(le => $this:ident, $typ:tt, $len_to_read:expr) => {{
4420
const SIZE: usize = core::mem::size_of::<$typ>();
@@ -1226,6 +1202,7 @@ pub trait Buf {
12261202
/// assert_eq!(3, buf.remaining());
12271203
/// ```
12281204
///
1205+
#[inline] // inline for better performance of buf_try_get_impl methods
12291206
fn try_get_array<const N: usize>(&mut self) -> Result<[u8; N], TryGetError>
12301207
where
12311208
Self: Sized,

0 commit comments

Comments
 (0)