ps_ecc/
cow.rs

1use std::ops::Deref;
2
3use ps_buffer::{Buffer, BufferError};
4
5#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
6pub enum Cow<'lt> {
7    Borrowed(&'lt [u8]),
8    Owned(Buffer),
9}
10
11impl<'lt> Cow<'lt> {
12    /// This method turns this [`Cow`] into a [`Buffer`].
13    /// - In the case of [`Cow::Borrowed`], a new [`Buffer`] is allocated.
14    /// - In the case of [`Cow::Owned`], the existing [`Buffer`] is returned.
15    /// # Errors
16    /// [`BufferError`] is returned if an allocation error occurs.
17    pub fn try_into_buffer(self) -> Result<Buffer, BufferError> {
18        match self {
19            Cow::Borrowed(value) => Buffer::from_slice(value),
20            Cow::Owned(value) => Ok(value),
21        }
22    }
23}
24
25impl<'lt> Deref for Cow<'lt> {
26    type Target = [u8];
27
28    fn deref(&self) -> &Self::Target {
29        match self {
30            Self::Borrowed(value) => value,
31            Self::Owned(value) => value,
32        }
33    }
34}
35
36impl<'lt> From<&'lt [u8]> for Cow<'lt> {
37    fn from(value: &'lt [u8]) -> Self {
38        Self::Borrowed(value)
39    }
40}
41
42impl<'lt> From<Buffer> for Cow<'lt> {
43    fn from(value: Buffer) -> Self {
44        Self::Owned(value)
45    }
46}