ps_buffer/methods/
concat.rs

1use crate::{Buffer, BufferError};
2
3impl Buffer {
4    /// Returns a new [`Buffer`] which is the result of concatenating all the slices in the list together.
5    ///
6    /// If the list has no items, then a new zero-length [`Buffer`] is returned.
7    ///
8    /// # Errors
9    /// - [`BufferError::AllocationError`] is returned if allocation fails.
10    pub fn concat(list: &[&[u8]]) -> Result<Self, BufferError> {
11        let mut length = 0;
12
13        for item in list {
14            length += item.len();
15        }
16
17        let mut buffer = Self::with_capacity(length)?;
18
19        for item in list {
20            buffer.extend_from_slice(item)?;
21        }
22
23        Ok(buffer)
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use crate::{Buffer, BufferError};
30
31    #[test]
32    fn try_concat() -> Result<(), BufferError> {
33        let buffer = Buffer::concat(&[b"Hello,", b" ", b"world", b"!"])?;
34
35        assert_eq!(&buffer.slice(..), b"Hello, world!");
36
37        Ok(())
38    }
39}