Skip to content

Commit

Permalink
Median returns None in case of empty lists
Browse files Browse the repository at this point in the history
  • Loading branch information
keyvank committed Sep 6, 2023
1 parent 5f1e6a2 commit 6409624
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/node/heartbeat/sync_clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ pub async fn sync_clock<K: KvStore, B: Blockchain<K>>(
.unzip();
if !timestamps.is_empty() {
// Set timestamp_offset according to median timestamp of the network
let median_timestamp = utils::median(&timestamps);
let median_timestamp_offset = utils::median(&timestamp_offsets);
let median_timestamp = utils::median(&timestamps).expect("Timestamp list not empty!");
let median_timestamp_offset =
utils::median(&timestamp_offsets).expect("Timestamp list not empty!");
ctx.timestamp_offset = median_timestamp as i32 - utils::local_timestamp() as i32;
ctx.timestamp_offset -= median_timestamp_offset;
}
Expand Down
8 changes: 6 additions & 2 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ pub fn local_timestamp() -> u32 {
.as_secs() as u32
}

pub fn median<T: Clone + std::cmp::Ord>(inps: &[T]) -> T {
pub fn median<T: Clone + std::cmp::Ord>(inps: &[T]) -> Option<T> {
let mut sorted = inps.to_vec();
sorted.sort();
sorted[sorted.len() / 2].clone()
if sorted.len() > 0 {
Some(sorted[sorted.len() / 2].clone())
} else {
None
}
}

0 comments on commit 6409624

Please sign in to comment.