event.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use std::{cmp::Ordering, io};
  2. use darkfi::{
  3. net,
  4. util::serial::{Decodable, Encodable},
  5. Result,
  6. };
  7. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
  8. pub struct Event {
  9. // the msg in the event
  10. pub value: Vec<u8>,
  11. // the counter for lamport clock
  12. pub counter: u64,
  13. // It might be necessary to attach the node's name to the timestamp
  14. // so that it is possible to differentiate between events
  15. pub name: String,
  16. }
  17. impl Encodable for Event {
  18. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  19. let mut len = 0;
  20. len += self.value.encode(&mut s)?;
  21. len += self.counter.encode(&mut s)?;
  22. len += self.name.encode(&mut s)?;
  23. Ok(len)
  24. }
  25. }
  26. impl Decodable for Event {
  27. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  28. Ok(Self {
  29. value: Decodable::decode(&mut d)?,
  30. counter: Decodable::decode(&mut d)?,
  31. name: Decodable::decode(&mut d)?,
  32. })
  33. }
  34. }
  35. impl Event {
  36. pub fn new(value: Vec<u8>, counter: u64, name: String) -> Self {
  37. Self { value, counter, name }
  38. }
  39. }
  40. impl Ord for Event {
  41. fn cmp(&self, other: &Self) -> Ordering {
  42. let ord = self.counter.cmp(&other.counter);
  43. if ord == Ordering::Equal {
  44. return self.name.cmp(&other.name)
  45. }
  46. ord
  47. }
  48. }
  49. impl net::Message for Event {
  50. fn name() -> &'static str {
  51. "event"
  52. }
  53. }