From 64096246ef5689f797bfc54e568c4e55e345617a Mon Sep 17 00:00:00 2001 From: Keyvan Kambakhsh Date: Wed, 6 Sep 2023 20:18:06 +0330 Subject: [PATCH] Median returns None in case of empty lists --- src/node/heartbeat/sync_clock.rs | 5 +++-- src/utils/mod.rs | 8 ++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/node/heartbeat/sync_clock.rs b/src/node/heartbeat/sync_clock.rs index a202978d..a58a20b5 100644 --- a/src/node/heartbeat/sync_clock.rs +++ b/src/node/heartbeat/sync_clock.rs @@ -53,8 +53,9 @@ pub async fn sync_clock>( .unzip(); if !timestamps.is_empty() { // Set timestamp_offset according to median timestamp of the network - let median_timestamp = utils::median(×tamps); - let median_timestamp_offset = utils::median(×tamp_offsets); + let median_timestamp = utils::median(×tamps).expect("Timestamp list not empty!"); + let median_timestamp_offset = + utils::median(×tamp_offsets).expect("Timestamp list not empty!"); ctx.timestamp_offset = median_timestamp as i32 - utils::local_timestamp() as i32; ctx.timestamp_offset -= median_timestamp_offset; } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 834b834b..0642c109 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -7,8 +7,12 @@ pub fn local_timestamp() -> u32 { .as_secs() as u32 } -pub fn median(inps: &[T]) -> T { +pub fn median(inps: &[T]) -> Option { 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 + } }