From 5d547130f05dc1410cfc2707f213fd216c3920db Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 20 Apr 2020 01:25:41 -0700 Subject: [PATCH] Calculate distance between u64 without overflow (#9592) (#9599) automerge --- core/src/broadcast_stage.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/core/src/broadcast_stage.rs b/core/src/broadcast_stage.rs index 46095c2150..bd841db703 100644 --- a/core/src/broadcast_stage.rs +++ b/core/src/broadcast_stage.rs @@ -412,11 +412,19 @@ pub fn broadcast_shreds( Ok(()) } +fn distance(a: u64, b: u64) -> u64 { + if a > b { + a - b + } else { + b - a + } +} + fn num_live_peers(peers: &[ContactInfo]) -> i64 { let mut num_live_peers = 1i64; peers.iter().for_each(|p| { // A peer is considered live if they generated their contact info recently - if timestamp() - p.wallclock <= CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS { + if distance(timestamp(), p.wallclock) <= CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS { num_live_peers += 1; } }); @@ -506,6 +514,17 @@ pub mod test { assert_eq!(num_expected_coding_shreds, coding_index); } + #[test] + fn test_num_live_peers() { + let mut ci = ContactInfo::default(); + ci.wallclock = std::u64::MAX; + assert_eq!(num_live_peers(&[ci.clone()]), 1); + ci.wallclock = timestamp() - 1; + assert_eq!(num_live_peers(&[ci.clone()]), 2); + ci.wallclock = timestamp() - CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS - 1; + assert_eq!(num_live_peers(&[ci]), 1); + } + #[test] fn test_duplicate_retransmit_signal() { // Setup