async_pop/response/types/
message.rs1use std::{
2 borrow::Cow,
3 fmt::{self, Display, Formatter},
4 result,
5};
6
7use bytes::Bytes;
8
9use crate::error::{Error, Result};
10
11use super::DataType;
12
13#[derive(Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Clone)]
14pub struct Text {
18 inner: Bytes,
19}
20
21impl From<&str> for Text {
22 fn from(value: &str) -> Self {
23 Self::from(value.as_bytes())
24 }
25}
26
27impl Display for Text {
28 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
29 let message = self.as_str_lossy();
30
31 write!(f, "{}", message)
32 }
33}
34
35impl TryInto<String> for Text {
36 type Error = Error;
37
38 fn try_into(self) -> result::Result<String, Self::Error> {
39 self.value()
40 }
41}
42
43impl From<&[u8]> for Text {
44 fn from(value: &[u8]) -> Self {
45 Self {
46 inner: Bytes::copy_from_slice(value),
47 }
48 }
49}
50
51impl AsRef<[u8]> for Text {
52 fn as_ref(&self) -> &[u8] {
53 &self.inner
54 }
55}
56
57impl From<Bytes> for Text {
58 fn from(value: Bytes) -> Self {
59 Self { inner: value }
60 }
61}
62
63impl DataType<String> for Text {
64 fn raw(&self) -> &[u8] {
65 &self.inner
66 }
67
68 fn as_str_lossy(&self) -> Cow<'_, str> {
69 String::from_utf8_lossy(&self.inner)
70 }
71
72 fn as_str(&self) -> Result<&str> {
73 Ok(std::str::from_utf8(&self.inner)?)
74 }
75
76 fn value(&self) -> Result<String> {
77 self.as_str().map(|slice| slice.to_string())
78 }
79}