Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. use std::string::String;
  2.  
  3. trait Protocol {
  4. type Handler:?Sized;
  5. }
  6.  
  7. // Generic payload for a message.
  8. trait Payload<P: Protocol> {
  9. fn accept(&self, msg: &Message<P>, handler: &P::Handler);
  10. }
  11.  
  12. // Generic message as e.g. created by reading from a stream.
  13. // This can be used by the library code since it is not dependent on any
  14. // protocol or payload type.
  15. struct Message<P: Protocol> {
  16. common_field: i32,
  17. payload: Box<dyn Payload<P>>,
  18. }
  19.  
  20. // Adaptor function to allow visiting messages directly even if the actual
  21. // visitor pattern is implemented over payloads.
  22. fn accept<P: Protocol>(msg: &Message<P>, handler: &P::Handler) {
  23. msg.payload.accept(msg, handler)
  24. }
  25.  
  26.  
  27. // Example protocol.
  28. struct S1Protocol;
  29. impl Protocol for S1Protocol {
  30. type Handler = S1Handler;
  31. }
  32.  
  33. // Protocol-specific handler for handling masseges with a particular types.
  34. // This de-facto describes avalable message types handled by the protocol.
  35. trait S1Handler {
  36. fn visit_authorize(&self, msg: &Message<S1Protocol>, payload: &Authorize);
  37. fn visit_subscribe(&self, msg: &Message<S1Protocol>, payload: &Subscribe);
  38. }
  39.  
  40.  
  41. // Example message type
  42. struct Authorize {
  43. name: String,
  44. }
  45. impl Payload<S1Protocol> for Authorize {
  46. fn accept(&self, message: &Message<S1Protocol>, handler: &<S1Protocol as Protocol>::Handler) {
  47. handler.visit_authorize(message, self)
  48. }
  49. }
  50.  
  51. // Example message type
  52. struct Subscribe;
  53. impl Payload<S1Protocol> for Subscribe {
  54. fn accept(&self, message: &Message<S1Protocol>, handler: &<S1Protocol as Protocol>::Handler) {
  55. handler.visit_subscribe(message, self)
  56. }
  57. }
  58.  
  59. // Example of possible handler. This just prints a message.
  60. struct PrintHandler;
  61. impl S1Handler for PrintHandler {
  62. fn visit_authorize(&self, msg: &Message<S1Protocol>, payload: &Authorize) {
  63. println!("Authorize: {} {}", msg.common_field, payload.name);
  64. }
  65.  
  66. fn visit_subscribe(&self, msg: &Message<S1Protocol>, _payload: &Subscribe) {
  67. println!("Subscribe: {}", msg.common_field);
  68. }
  69. }
  70.  
  71.  
  72. fn main() {
  73. let m1 = Message::<S1Protocol> {
  74. common_field: 1,
  75. payload: Box::new(
  76. Authorize {name: "name".to_string()}
  77. ),
  78. };
  79.  
  80. let m2 = Message::<S1Protocol> {
  81. common_field: 2,
  82. payload: Box::new(
  83. Subscribe{}
  84. ),
  85. };
  86.  
  87. let h = PrintHandler{};
  88. accept(&m1, &h);
  89. accept(&m2, &h);
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement