1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::{
    borrow::Cow,
    fmt::{self, Display, Formatter},
    result,
};

use bytes::Bytes;

use crate::error::{Error, Result};

use super::DataType;

#[derive(Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Clone)]
/// Represents a Pop3 string data type.
///
/// Get its real value by calling `value()` from the [DataType] trait
pub struct Text {
    inner: Bytes,
}

impl From<&str> for Text {
    fn from(value: &str) -> Self {
        Self::from(value.as_bytes())
    }
}

impl Display for Text {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let message = self.as_str_lossy();

        write!(f, "{}", message)
    }
}

impl TryInto<String> for Text {
    type Error = Error;

    fn try_into(self) -> result::Result<String, Self::Error> {
        self.value()
    }
}

impl From<&[u8]> for Text {
    fn from(value: &[u8]) -> Self {
        Self {
            inner: Bytes::copy_from_slice(value),
        }
    }
}

impl AsRef<[u8]> for Text {
    fn as_ref(&self) -> &[u8] {
        &self.inner
    }
}

impl From<Bytes> for Text {
    fn from(value: Bytes) -> Self {
        Self { inner: value }
    }
}

impl DataType<String> for Text {
    fn raw(&self) -> &[u8] {
        &self.inner
    }

    fn as_str_lossy(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.inner)
    }

    fn as_str(&self) -> Result<&str> {
        Ok(std::str::from_utf8(&self.inner)?)
    }

    fn value(&self) -> Result<String> {
        self.as_str().map(|slice| slice.to_string())
    }
}