types.rs 2.0 KB

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