Skip to content

Commit

Permalink
better to index conversion docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Dav1dde committed Dec 17, 2024
1 parent d8ea0fb commit 3f4c91c
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions relay-metrics/src/aggregator/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,15 +340,16 @@ impl Inner {
}
} % u64::from(self.num_partitions);

// Calculate the slot of the bucket based on it's time and shift it by its assigned partition.
let slot = time_slot * u64::from(self.num_partitions) + assigned_partition;

let slots_len = self.slots.len() as u64;
let index = (slot + slots_len).wrapping_sub(self.head % slots_len) % slots_len;
// Transform the slot to an offset/index into the ring-buffer, by calculating:
// `(slot - self.head).rem_euclid(self.slots.len())`.
let index = sub_rem_euclid(slot, self.head, self.slots.len() as u64);

let slot = self
.slots
.get_mut(index as usize)
.expect("index should always be a valid partition");
.expect("index should always be a valid slot index");

debug_assert_eq!(
u64::from(slot.partition_key),
Expand Down Expand Up @@ -522,6 +523,23 @@ impl RelativeRange {
}
}

/// Calculates `(a - b).rem_euclid(mod)` for `u64` values.
///
/// Since `a - b` can be negative, you naively need to temporarily change the number space from
/// unsigned to signed and after the modulo back to unsigned.
///
/// This function instead operates purely with unsigned arithmetic and makes sure the subtraction
/// is always positive.
fn sub_rem_euclid(a: u64, b: u64, m: u64) -> u64 {
(
// Shift a by `m`: `[m, inf)`.
(a + m)
-
// Modulo b: `[0, m)`.
(b % m)
) % m
}

fn build_hasher() -> RandomState {
// A fixed, consistent seed across all instances of Relay.
const K0: u64 = 0x06459b7d5da84ed8;
Expand Down

0 comments on commit 3f4c91c

Please sign in to comment.