Skip to content

Commit

Permalink
fix: use intermediate u64 to calculate average (#3432)
Browse files Browse the repository at this point in the history
Description
---
Calculates `AverageLatency` using `u64` intermediate state.

Motivation and Context
---
If the samples are large enough the average sum can overflow. Using `u64` makes this event less likely.

How Has This Been Tested?
---
Manually. Function only.
  • Loading branch information
therustmonk authored Oct 7, 2021
1 parent 423dbe1 commit ff6bc38
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions base_layer/p2p/src/services/liveness/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::proto::liveness::MetadataKey;
use chrono::{NaiveDateTime, Utc};
use std::{
collections::{hash_map::RandomState, HashMap},
convert::TryInto,
time::Duration,
};
use tari_comms::peer_manager::NodeId;
Expand Down Expand Up @@ -224,12 +225,14 @@ impl AverageLatency {

/// Calculate the average of the recorded samples
pub fn calc_average(&self) -> u32 {
let samples = &self.samples;
if samples.is_empty() {
return 0;
}

samples.iter().fold(0, |sum, x| sum + *x) / samples.len() as u32
self.samples
.iter()
.map(|x| u64::from(*x))
.fold(0, u64::saturating_add)
.checked_div(self.samples.len() as u64)
.unwrap_or_default()
.try_into()
.unwrap_or(u32::MAX)
}
}

Expand Down

0 comments on commit ff6bc38

Please sign in to comment.