types.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use byteorder::{BigEndian, WriteBytesExt};
  2. use protobuf::Message;
  3. use std::io::Write;
  4. use crate::protocol;
  5. #[derive(Debug, PartialEq, Eq)]
  6. pub enum MercuryMethod {
  7. GET,
  8. SUB,
  9. UNSUB,
  10. SEND,
  11. }
  12. #[derive(Debug)]
  13. pub struct MercuryRequest {
  14. pub method: MercuryMethod,
  15. pub uri: String,
  16. pub content_type: Option<String>,
  17. pub payload: Vec<Vec<u8>>,
  18. }
  19. #[derive(Debug, Clone)]
  20. pub struct MercuryResponse {
  21. pub uri: String,
  22. pub status_code: i32,
  23. pub payload: Vec<Vec<u8>>,
  24. }
  25. #[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)]
  26. pub struct MercuryError;
  27. impl ToString for MercuryMethod {
  28. fn to_string(&self) -> String {
  29. match *self {
  30. MercuryMethod::GET => "GET",
  31. MercuryMethod::SUB => "SUB",
  32. MercuryMethod::UNSUB => "UNSUB",
  33. MercuryMethod::SEND => "SEND",
  34. }
  35. .to_owned()
  36. }
  37. }
  38. impl MercuryMethod {
  39. pub fn command(&self) -> u8 {
  40. match *self {
  41. MercuryMethod::GET | MercuryMethod::SEND => 0xb2,
  42. MercuryMethod::SUB => 0xb3,
  43. MercuryMethod::UNSUB => 0xb4,
  44. }
  45. }
  46. }
  47. impl MercuryRequest {
  48. pub fn encode(&self, seq: &[u8]) -> Vec<u8> {
  49. let mut packet = Vec::new();
  50. packet.write_u16::<BigEndian>(seq.len() as u16).unwrap();
  51. packet.write_all(seq).unwrap();
  52. packet.write_u8(1).unwrap(); // Flags: FINAL
  53. packet
  54. .write_u16::<BigEndian>(1 + self.payload.len() as u16)
  55. .unwrap(); // Part count
  56. let mut header = protocol::mercury::Header::new();
  57. header.set_uri(self.uri.clone());
  58. header.set_method(self.method.to_string());
  59. if let Some(ref content_type) = self.content_type {
  60. header.set_content_type(content_type.clone());
  61. }
  62. packet
  63. .write_u16::<BigEndian>(header.compute_size() as u16)
  64. .unwrap();
  65. header.write_to_writer(&mut packet).unwrap();
  66. for p in &self.payload {
  67. packet.write_u16::<BigEndian>(p.len() as u16).unwrap();
  68. packet.write(p).unwrap();
  69. }
  70. packet
  71. }
  72. }