Skip to main content

sark_json/
scratch.rs

1use std::cell::RefCell;
2
3pub struct Scratch<T> {
4    slot: RefCell<Vec<T>>,
5}
6
7impl<T> Scratch<T> {
8    pub const fn new() -> Self {
9        Self {
10            slot: RefCell::new(Vec::new()),
11        }
12    }
13
14    pub fn take(&self) -> Vec<T> {
15        let mut slot = self.slot.borrow_mut();
16        let mut out = std::mem::take(&mut *slot);
17        out.clear();
18        out
19    }
20
21    pub fn give(&self, mut buf: Vec<T>) {
22        buf.clear();
23        let mut slot = self.slot.borrow_mut();
24        if buf.capacity() > slot.capacity() {
25            *slot = buf;
26        }
27    }
28}
29
30impl<T> Default for Scratch<T> {
31    fn default() -> Self {
32        Self::new()
33    }
34}