-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathproven_tip.rs
More file actions
73 lines (62 loc) · 2.34 KB
/
Copy pathproven_tip.rs
File metadata and controls
73 lines (62 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use miden_protocol::block::BlockNumber;
use tokio::sync::watch;
/// Cloneable handle that can advance the proven chain tip.
///
/// All clones share the same underlying watch channel, so any [`ProvenTipWriter::advance()`] call is immediately
/// visible to all receivers returned by [`ProvenTipWriter::subscribe()`].
#[derive(Clone)]
pub struct ProvenTipWriter(watch::Sender<BlockNumber>);
impl ProvenTipWriter {
/// Creates a new writer initialized to `tip`, returning a companion receiver.
pub fn new(tip: BlockNumber) -> (Self, watch::Receiver<BlockNumber>) {
let (tx, rx) = watch::channel(tip);
(Self(tx), rx)
}
/// Returns the current proven chain tip.
pub fn read(&self) -> BlockNumber {
*self.0.borrow()
}
/// Advances the tip to `new_tip` if it is greater than the current value.
///
/// Notifies all subscribers only when the tip actually increases.
///
/// # Panics
///
/// Panics if `new_tip` is greater than the current tip's child.
pub fn advance(&self, new_tip: BlockNumber) {
self.0.send_if_modified(|current| {
if new_tip > *current {
assert_eq!(new_tip, current.child());
*current = new_tip;
true
} else {
false
}
});
}
/// Returns a new receiver that wakes on every proven-tip advance.
pub fn subscribe(&self) -> watch::Receiver<BlockNumber> {
self.0.subscribe()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn advance_only_increases_tip() {
let (writer, _rx) = ProvenTipWriter::new(BlockNumber::from(5u32));
assert_eq!(writer.read(), BlockNumber::from(5u32));
// Advancing to a higher value updates the tip.
writer.advance(BlockNumber::from(6u32));
assert_eq!(writer.read(), BlockNumber::from(6u32));
// Advancing to a lower value is a no-op.
writer.advance(BlockNumber::from(3u32));
assert_eq!(writer.read(), BlockNumber::from(6u32));
// Advancing to the same value is a no-op.
writer.advance(BlockNumber::from(6u32));
assert_eq!(writer.read(), BlockNumber::from(6u32));
// Advancing to a higher value again works.
writer.advance(BlockNumber::from(7u32));
assert_eq!(writer.read(), BlockNumber::from(7u32));
}
}