Skip to content

Commit 2b36e04

Browse files
committed
feat(utils): add slot_starting_at / slot_ending_at fns to the calculator
These functions can calculate the slot that begins or ends at a given timestamp, as LONG as it's a slot boundary. Else, the ywill return `None`.
1 parent 88b3eeb commit 2b36e04

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/utils/calc.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,28 @@ impl SlotCalculator {
244244
pub fn current_point_within_slot(&self) -> Option<u64> {
245245
self.point_within_slot(chrono::Utc::now().timestamp() as u64)
246246
}
247+
248+
/// Calculates the slot that starts at the given timestamp.
249+
/// If given a timestamp that is NOT a slot boundary, it will return
250+
/// `None`.
251+
pub const fn slot_starting_at(&self, timestamp: u64) -> Option<usize> {
252+
if timestamp % self.slot_duration != 0 {
253+
return None;
254+
}
255+
self.slot_containing(timestamp)
256+
}
257+
258+
/// Calculates the slot that ends at the given timestamp.
259+
/// If given a timestamp that is NOT a slot boundary, it will return
260+
/// `None`.
261+
pub fn slot_ending_at(&self, timestamp: u64) -> Option<usize> {
262+
if timestamp % self.slot_duration != 0 {
263+
return None;
264+
}
265+
self.slot_containing(timestamp)
266+
.and_then(|slot| slot.checked_sub(1))
267+
.and_then(|slot| if slot == 0 { None } else { Some(slot) })
268+
}
247269
}
248270

249271
#[cfg(test)]
@@ -265,10 +287,16 @@ mod tests {
265287
assert_eq!(calculator.slot_containing(1), None);
266288
assert_eq!(calculator.slot_containing(11), None);
267289

290+
assert_eq!(calculator.slot_ending_at(12), None);
291+
assert_eq!(calculator.slot_starting_at(12), Some(1));
268292
assert_eq!(calculator.slot_containing(12), Some(1));
269293
assert_eq!(calculator.slot_containing(13), Some(1));
294+
assert_eq!(calculator.slot_starting_at(13), None);
270295
assert_eq!(calculator.slot_containing(23), Some(1));
296+
assert_eq!(calculator.slot_ending_at(23), None);
271297

298+
assert_eq!(calculator.slot_ending_at(24), Some(1));
299+
assert_eq!(calculator.slot_starting_at(24), Some(2));
272300
assert_eq!(calculator.slot_containing(24), Some(2));
273301
assert_eq!(calculator.slot_containing(25), Some(2));
274302
assert_eq!(calculator.slot_containing(35), Some(2));

0 commit comments

Comments
 (0)