74 lines
1.5 KiB
Rust
Raw Normal View History

2021-07-03 22:24:02 +08:00
use std::{fmt, fmt::Formatter};
use bytes::Bytes;
2021-06-24 16:32:36 +08:00
#[derive(Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize))]
pub enum Payload {
None,
Bytes(Bytes),
2021-06-24 16:32:36 +08:00
}
2021-07-03 22:24:02 +08:00
impl Payload {
pub fn to_vec(self) -> Vec<u8> {
match self {
Payload::None => vec![],
Payload::Bytes(bytes) => bytes.to_vec(),
}
}
}
impl std::fmt::Debug for Payload {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
format_payload_print(self, f)
}
}
2021-07-03 22:24:02 +08:00
impl std::fmt::Display for Payload {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
format_payload_print(self, f)
}
}
fn format_payload_print(payload: &Payload, f: &mut Formatter<'_>) -> fmt::Result {
match payload {
Payload::Bytes(bytes) => f.write_fmt(format_args!("{} bytes", bytes.len())),
Payload::None => f.write_str("Empty"),
}
2021-07-03 22:24:02 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<String> for Payload {
fn from(s: String) -> Self {
Payload::Bytes(Bytes::from(s))
}
2021-07-03 22:24:02 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<&'_ String> for Payload {
fn from(s: &String) -> Self {
Payload::Bytes(Bytes::from(s.to_owned()))
}
2021-07-03 22:24:02 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<Bytes> for Payload {
fn from(bytes: Bytes) -> Self {
Payload::Bytes(bytes)
}
2021-07-03 22:24:02 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<()> for Payload {
fn from(_: ()) -> Self {
Payload::None
}
2021-07-11 17:38:03 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<Vec<u8>> for Payload {
fn from(bytes: Vec<u8>) -> Self {
Payload::Bytes(Bytes::from(bytes))
}
2021-07-03 22:24:02 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::convert::From<&str> for Payload {
fn from(s: &str) -> Self {
s.to_string().into()
}
2021-07-03 22:24:02 +08:00
}