payload.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use bytes::Bytes;
  2. use std::{fmt, fmt::Formatter};
  3. pub enum PayloadError {}
  4. // TODO: support stream data
  5. #[derive(Clone)]
  6. #[cfg_attr(feature = "use_serde", derive(serde::Serialize))]
  7. pub enum Payload {
  8. None,
  9. Bytes(Bytes),
  10. }
  11. impl Payload {
  12. pub fn to_vec(self) -> Vec<u8> {
  13. match self {
  14. Payload::None => vec![],
  15. Payload::Bytes(bytes) => bytes.to_vec(),
  16. }
  17. }
  18. }
  19. impl std::fmt::Debug for Payload {
  20. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  21. format_payload_print(self, f)
  22. }
  23. }
  24. impl std::fmt::Display for Payload {
  25. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  26. format_payload_print(self, f)
  27. }
  28. }
  29. fn format_payload_print(payload: &Payload, f: &mut Formatter<'_>) -> fmt::Result {
  30. match payload {
  31. Payload::Bytes(bytes) => f.write_fmt(format_args!("{} bytes", bytes.len())),
  32. Payload::None => f.write_str("Empty"),
  33. }
  34. }
  35. impl std::convert::From<String> for Payload {
  36. fn from(s: String) -> Self {
  37. Payload::Bytes(Bytes::from(s))
  38. }
  39. }
  40. impl std::convert::From<&'_ String> for Payload {
  41. fn from(s: &String) -> Self {
  42. Payload::Bytes(Bytes::from(s.to_owned()))
  43. }
  44. }
  45. impl std::convert::From<Bytes> for Payload {
  46. fn from(bytes: Bytes) -> Self {
  47. Payload::Bytes(bytes)
  48. }
  49. }
  50. impl std::convert::From<()> for Payload {
  51. fn from(_: ()) -> Self {
  52. Payload::None
  53. }
  54. }
  55. impl std::convert::From<Vec<u8>> for Payload {
  56. fn from(bytes: Vec<u8>) -> Self {
  57. Payload::Bytes(Bytes::from(bytes))
  58. }
  59. }
  60. impl std::convert::From<&str> for Payload {
  61. fn from(s: &str) -> Self {
  62. s.to_string().into()
  63. }
  64. }