Make TestingSlotClock thread-safe

This commit is contained in:
Paul Hauner 2019-01-25 11:25:09 +11:00
parent 271a4cf8a7
commit 5f953f76d8
No known key found for this signature in database
GPG Key ID: D362883A9218FCC6

View File

@ -1,11 +1,12 @@
use super::SlotClock;
use std::sync::RwLock;
#[derive(Debug, PartialEq)]
pub enum Error {}
/// Determines the present slot based upon the present system time.
pub struct TestingSlotClock {
slot: u64,
slot: RwLock<u64>,
}
impl TestingSlotClock {
@ -13,11 +14,13 @@ impl TestingSlotClock {
///
/// Returns an Error if `slot_duration_seconds == 0`.
pub fn new(slot: u64) -> TestingSlotClock {
TestingSlotClock { slot }
TestingSlotClock {
slot: RwLock::new(slot),
}
}
pub fn set_slot(&mut self, slot: u64) {
self.slot = slot;
pub fn set_slot(&self, slot: u64) {
*self.slot.write().expect("TestingSlotClock poisoned.") = slot;
}
}
@ -25,7 +28,8 @@ impl SlotClock for TestingSlotClock {
type Error = Error;
fn present_slot(&self) -> Result<Option<u64>, Error> {
Ok(Some(self.slot))
let slot = *self.slot.read().expect("TestingSlotClock poisoned.");
Ok(Some(slot))
}
}
@ -35,7 +39,7 @@ mod tests {
#[test]
fn test_slot_now() {
let mut clock = TestingSlotClock::new(10);
let clock = TestingSlotClock::new(10);
assert_eq!(clock.present_slot(), Ok(Some(10)));
clock.set_slot(123);
assert_eq!(clock.present_slot(), Ok(Some(123)));