participant.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use std::{collections::BTreeMap, io};
  2. use crate::{
  3. impl_vec, net,
  4. util::serial::{Decodable, Encodable, SerialDecodable, SerialEncodable, VarInt},
  5. Result,
  6. };
  7. /// This struct represents a tuple of the form (node_id, epoch_joined, last_epoch_voted).
  8. #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  9. pub struct Participant {
  10. /// Node id
  11. pub id: u64,
  12. /// Epoch node joined the network
  13. pub joined: u64,
  14. /// Last epoch node voted
  15. pub voted: Option<u64>,
  16. }
  17. impl Participant {
  18. pub fn new(id: u64, joined: u64) -> Participant {
  19. Participant { id, joined, voted: None }
  20. }
  21. }
  22. impl net::Message for Participant {
  23. fn name() -> &'static str {
  24. "participant"
  25. }
  26. }
  27. impl Encodable for BTreeMap<u64, Participant> {
  28. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  29. let mut len = 0;
  30. len += VarInt(self.len() as u64).encode(&mut s)?;
  31. for c in self.iter() {
  32. len += c.1.encode(&mut s)?;
  33. }
  34. Ok(len)
  35. }
  36. }
  37. impl Decodable for BTreeMap<u64, Participant> {
  38. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  39. let len = VarInt::decode(&mut d)?.0;
  40. let mut ret = BTreeMap::new();
  41. for _ in 0..len {
  42. let participant: Participant = Decodable::decode(&mut d)?;
  43. ret.insert(participant.id, participant);
  44. }
  45. Ok(ret)
  46. }
  47. }
  48. impl_vec!(Participant);