ps_buffer/methods/
realloc.rs

1use ps_alloc::{alloc, free};
2
3use crate::{Buffer, BufferError};
4
5impl Buffer {
6    /// # Errors
7    /// - `AllocationError` is returned if allocation fails.
8    /// - `DeallocationError` is returned if deallocation fails.
9    pub fn realloc(&mut self, size: usize) -> Result<&mut Self, BufferError> {
10        let old_ptr = self.ptr;
11        let new_ptr = alloc(size)?;
12
13        self.ptr = new_ptr;
14        self.capacity = size;
15        self.length = self.length.min(self.capacity);
16
17        if !old_ptr.is_null() {
18            unsafe {
19                std::ptr::copy_nonoverlapping(old_ptr, new_ptr, self.len());
20            }
21
22            free(old_ptr)?;
23        }
24
25        Ok(self)
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use crate::{Buffer, BufferError};
32
33    #[test]
34    fn reallocation() -> Result<(), BufferError> {
35        let mut buffer = Buffer::default();
36
37        buffer.realloc(128)?;
38        buffer.set_len(128)?;
39
40        for i in buffer.as_mut() {
41            *i = std::ptr::addr_of!(i) as u8;
42        }
43
44        let copy = Buffer::from_slice(&buffer)?;
45
46        buffer.realloc(512)?;
47
48        assert_eq!(buffer[0..128], *copy);
49
50        buffer.realloc(64)?;
51
52        assert_eq!(buffer[0..64], copy[0..64]);
53
54        Ok(())
55    }
56}