Created
January 18, 2024 20:23
-
-
Save Muqito/350ea1bd07ca2e59b9112ac0130be762 to your computer and use it in GitHub Desktop.
reduce heap allocation with mem::take
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ref: https://ferrous-systems.com/blog/rustls-borrow-checker-p1/ | |
#[derive(Debug)] | |
struct Reader<'a> { | |
buffer: &'a mut [u8] | |
} | |
impl<'a> Reader<'a> { | |
pub fn new(buffer: &'a mut [u8]) -> Self { | |
Self { | |
buffer, | |
} | |
} | |
fn take<'s>(&'s mut self, length: usize) -> Option<&'a mut [u8]> { | |
if self.buffer.len() < length { | |
return None; | |
} | |
let buffer = std::mem::take(&mut self.buffer); | |
let (taken, rest) = buffer.split_at_mut(length); | |
self.buffer = rest; | |
Some(taken) | |
} | |
} | |
fn main() { | |
let mut buffer = [0, 1, 2, 3, 4]; | |
let mut reader = Reader::new(&mut buffer); | |
let first = reader.take(2); | |
dbg!(&first); | |
let second = reader.take(1); | |
dbg!(second); | |
drop(first); | |
dbg!(reader); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment