proc_heim/process/
message.rs1#[cfg(any(feature = "json", feature = "message-pack"))]
2use super::{
3 serde::{SerdeError, SerdeUtil},
4 MessageFormat,
5};
6use std::string::FromUtf8Error;
7
8#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct Message {
14 pub(crate) bytes: Vec<u8>,
15}
16
17impl From<Vec<u8>> for Message {
18 fn from(value: Vec<u8>) -> Self {
19 Self { bytes: value }
20 }
21}
22
23impl From<&[u8]> for Message {
24 fn from(value: &[u8]) -> Self {
25 Self {
26 bytes: value.to_vec(),
27 }
28 }
29}
30
31impl From<String> for Message {
32 fn from(value: String) -> Self {
33 Self {
34 bytes: value.into(),
35 }
36 }
37}
38
39impl From<&str> for Message {
40 fn from(value: &str) -> Self {
41 Self {
42 bytes: value.into(),
43 }
44 }
45}
46
47impl<const N: usize> From<&[u8; N]> for Message {
48 fn from(value: &[u8; N]) -> Self {
49 Self {
50 bytes: value.to_vec(),
51 }
52 }
53}
54
55impl TryFrom<Message> for String {
56 type Error = FromUtf8Error;
57
58 fn try_from(value: Message) -> Result<Self, Self::Error> {
59 String::from_utf8(value.bytes)
60 }
61}
62
63impl AsRef<Vec<u8>> for Message {
64 fn as_ref(&self) -> &Vec<u8> {
65 &self.bytes
66 }
67}
68
69impl From<Message> for Vec<u8> {
70 fn from(value: Message) -> Self {
71 value.bytes
72 }
73}
74
75impl Message {
76 pub fn from_bytes<T>(bytes: T) -> Self
78 where
79 T: Into<Vec<u8>>,
80 {
81 Self {
82 bytes: bytes.into(),
83 }
84 }
85
86 pub fn from_string<S>(value: S) -> Self
88 where
89 S: Into<String>,
90 {
91 Self {
92 bytes: value.into().into(),
93 }
94 }
95
96 pub fn into_bytes(self) -> Vec<u8> {
98 self.bytes
99 }
100
101 pub fn try_into_string(self) -> Result<String, FromUtf8Error> {
103 String::from_utf8(self.bytes)
104 }
105
106 #[cfg(any(feature = "json", feature = "message-pack"))]
108 pub fn deserialize<T>(&self, format: &MessageFormat) -> Result<T, SerdeError>
109 where
110 T: for<'de> serde::Deserialize<'de>,
111 {
112 SerdeUtil::deserialize(&self.bytes, format)
113 }
114
115 #[cfg(any(feature = "json", feature = "message-pack"))]
117 pub fn from_serializable<S>(data: &S, format: &MessageFormat) -> Result<Message, SerdeError>
118 where
119 S: serde::Serialize,
120 {
121 let bytes = SerdeUtil::serialize(data, format)?;
122 Ok(Self { bytes })
123 }
124}