use bytes::Bytes;
use std::fmt;
#[derive(Clone, Eq, PartialEq)]
pub enum Message {
Text(
String,
),
Binary(
Bytes,
),
}
impl fmt::Debug for Message {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let variant = match self {
Self::Text(_) => "Text",
Self::Binary(_) => "Binary",
};
formatter
.debug_struct(variant)
.field("bytes", &self.len())
.finish()
}
}
impl Message {
pub fn text(value: impl Into<String>) -> Self {
Self::Text(value.into())
}
pub fn binary(value: impl Into<Bytes>) -> Self {
Self::Binary(value.into())
}
pub fn as_text(&self) -> Option<&str> {
match self {
Self::Text(value) => Some(value),
Self::Binary(_) => None,
}
}
pub fn as_bytes(&self) -> &[u8] {
match self {
Self::Text(value) => value.as_bytes(),
Self::Binary(value) => value.as_ref(),
}
}
pub fn into_bytes(self) -> Bytes {
match self {
Self::Text(value) => Bytes::from(value),
Self::Binary(value) => value,
}
}
pub fn len(&self) -> usize {
self.as_bytes().len()
}
pub fn is_empty(&self) -> bool {
self.as_bytes().is_empty()
}
}
impl From<String> for Message {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<&str> for Message {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<Bytes> for Message {
fn from(value: Bytes) -> Self {
Self::Binary(value)
}
}
impl From<Vec<u8>> for Message {
fn from(value: Vec<u8>) -> Self {
Self::Binary(Bytes::from(value))
}
}
impl From<&[u8]> for Message {
fn from(value: &[u8]) -> Self {
Self::Binary(Bytes::copy_from_slice(value))
}
}
#[cfg(test)]
#[path = "message_tests.rs"]
mod tests;