use std::collections::VecDeque;
use std::sync::{Arc, Mutex, Weak};
pub const DEFAULT_BUDGET_BYTES: usize = 128 * 1024 * 1024;
pub const REMOTE_DEFAULT_BUDGET_BYTES: usize = 32 * 1024 * 1024;
pub const MAX_BUDGET_MB: usize = 4096;
pub fn configured_budget_bytes(setting_mb: Option<usize>, remote: bool) -> usize {
match setting_mb {
None if remote => REMOTE_DEFAULT_BUDGET_BYTES,
None => DEFAULT_BUDGET_BYTES,
Some(mb) => mb.min(MAX_BUDGET_MB).saturating_mul(1024 * 1024),
}
}
pub const KEYFRAME_INTERVAL_BYTES: usize = 256 * 1024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frame {
pub at_ms: u64,
seq: u64,
pub data: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Keyframe {
pub at_ms: u64,
seq: u64,
pub screen: Vec<String>,
cost: usize,
}
fn keyframe_cost(screen: &[String]) -> usize {
screen
.iter()
.map(|row| row.len() + std::mem::size_of::<String>())
.sum()
}
const FRAME_OVERHEAD: usize = 2 * std::mem::size_of::<Frame>();
const MIN_ALLOCATION: usize = 32;
fn allocation_cost(len: usize) -> usize {
(len + 16).next_multiple_of(16).max(MIN_ALLOCATION)
}
fn largest_payload(room: usize) -> Option<usize> {
(room >= MIN_ALLOCATION).then(|| room / 16 * 16 - 16)
}
fn frame_cost(payload: usize) -> usize {
allocation_cost(payload) + FRAME_OVERHEAD
}
#[derive(Debug)]
pub struct RewindBuffer {
frames: VecDeque<Frame>,
keyframes: VecDeque<Keyframe>,
bytes: usize,
capacity: usize,
since_keyframe: usize,
next_seq: u64,
}
impl RewindBuffer {
pub fn new(capacity: usize) -> Self {
Self {
frames: VecDeque::new(),
keyframes: VecDeque::new(),
bytes: 0,
capacity,
since_keyframe: 0,
next_seq: 0,
}
}
pub fn push(&mut self, at_ms: u64, data: &[u8]) -> bool {
if self.capacity == 0 {
return false;
}
if data.is_empty() {
return false;
}
let Some(room) = self
.capacity
.checked_sub(FRAME_OVERHEAD)
.and_then(largest_payload)
.filter(|&r| r > 0)
else {
return false;
};
let data = if data.len() > room {
&data[data.len() - room..]
} else {
data
};
self.bytes += frame_cost(data.len());
let seq = self.take_seq();
self.frames.push_back(Frame {
at_ms,
seq,
data: data.to_vec(),
});
self.evict();
self.since_keyframe += data.len();
if self.since_keyframe >= KEYFRAME_INTERVAL_BYTES {
self.since_keyframe -= KEYFRAME_INTERVAL_BYTES;
return true;
}
false
}
pub fn push_keyframe(&mut self, at_ms: u64, screen: Vec<String>) {
let cost = keyframe_cost(&screen);
if self.capacity == 0 || cost > self.capacity {
return;
}
let seq = self.take_seq();
self.bytes += cost;
self.keyframes.push_back(Keyframe {
at_ms,
seq,
screen,
cost,
});
self.evict();
}
pub fn set_capacity(&mut self, capacity: usize) {
self.capacity = capacity;
if capacity == 0 {
self.frames = VecDeque::new();
self.keyframes = VecDeque::new();
self.bytes = 0;
self.since_keyframe = 0;
return;
}
self.evict();
self.shrink_slots();
self.keyframes.shrink_to(self.keyframes.len() * 2);
}
fn shrink_slots(&mut self) {
if self.frames.capacity() > 2 * self.frames.len() {
self.frames.shrink_to(self.frames.len());
}
}
pub fn capacity(&self) -> usize {
self.capacity
}
fn take_seq(&mut self) -> u64 {
let s = self.next_seq;
self.next_seq += 1;
s
}
fn evict(&mut self) {
while self.bytes > self.capacity {
if self.frames.len() > 1 {
if let Some(f) = self.frames.pop_front() {
self.bytes -= frame_cost(f.data.len());
}
self.drop_orphan_keyframes();
} else if self.pop_keyframe_front() {
} else if let Some(f) = self.frames.pop_front() {
self.bytes -= frame_cost(f.data.len());
} else {
self.bytes = 0;
break;
}
}
self.drop_orphan_keyframes();
self.shrink_slots();
}
fn pop_keyframe_front(&mut self) -> bool {
match self.keyframes.pop_front() {
Some(k) => {
self.bytes -= k.cost;
true
}
None => false,
}
}
fn drop_orphan_keyframes(&mut self) {
let Some(oldest_seq) = self.frames.front().map(|f| f.seq) else {
while self.keyframes.len() > 1 {
self.pop_keyframe_front();
}
return;
};
while self.keyframes.len() > 1 && self.keyframes[1].seq < oldest_seq {
self.pop_keyframe_front();
}
if self
.keyframes
.front()
.is_some_and(|k| k.seq + 1 < oldest_seq)
{
self.pop_keyframe_front();
}
}
pub fn bytes(&self) -> usize {
self.bytes
}
#[cfg(test)]
pub fn keyframe_count(&self) -> usize {
self.keyframes.len()
}
pub fn is_empty(&self) -> bool {
self.frames.is_empty()
}
pub fn span_ms(&self) -> Option<(u64, u64)> {
let lo = self.frames.iter().map(|f| f.at_ms).min()?;
let hi = self.frames.iter().map(|f| f.at_ms).max()?;
Some((lo, hi))
}
pub fn replay_from(&self, at_ms: u64) -> (Option<&Keyframe>, Vec<&Frame>) {
let kf = self.keyframes.iter().rev().find(|k| k.at_ms <= at_ms);
let start = kf.map(|k| k.at_ms).unwrap_or(0);
let frames = self
.frames
.iter()
.filter(|f| f.at_ms >= start && f.at_ms <= at_ms)
.collect();
(kf, frames)
}
}
#[derive(Debug)]
pub struct RewindBudget {
inner: Mutex<BudgetState>,
}
#[derive(Debug)]
struct BudgetState {
total: usize,
panes: Vec<Weak<Mutex<RewindBuffer>>>,
}
impl RewindBudget {
pub const fn new(total: usize) -> Self {
Self {
inner: Mutex::new(BudgetState {
total,
panes: Vec::new(),
}),
}
}
pub fn register(&self) -> Arc<Mutex<RewindBuffer>> {
let mut st = self.lock();
let buf = Arc::new(Mutex::new(RewindBuffer::new(0)));
st.panes.push(Arc::downgrade(&buf));
Self::rebalance(&mut st);
buf
}
pub fn release(&self, buf: &Arc<Mutex<RewindBuffer>>) {
let mut st = self.lock();
let target = Arc::downgrade(buf);
st.panes.retain(|w| !w.ptr_eq(&target));
lock_buffer(buf).set_capacity(0);
Self::rebalance(&mut st);
}
pub fn set_total(&self, total: usize) {
let mut st = self.lock();
st.total = total;
Self::rebalance(&mut st);
}
pub fn total(&self) -> usize {
self.lock().total
}
pub fn held_bytes(&self) -> usize {
self.lock()
.panes
.iter()
.filter_map(Weak::upgrade)
.map(|b| lock_buffer(&b).bytes())
.sum()
}
pub fn pane_count(&self) -> usize {
self.lock()
.panes
.iter()
.filter(|w| w.strong_count() > 0)
.count()
}
fn lock(&self) -> std::sync::MutexGuard<'_, BudgetState> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
fn rebalance(st: &mut BudgetState) {
st.panes.retain(|w| w.strong_count() > 0);
let live: Vec<_> = st.panes.iter().filter_map(Weak::upgrade).collect();
let share = st.total / live.len().max(1);
for buf in live {
lock_buffer(&buf).set_capacity(share);
}
}
}
fn lock_buffer(buf: &Mutex<RewindBuffer>) -> std::sync::MutexGuard<'_, RewindBuffer> {
buf.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn budget() -> &'static RewindBudget {
static BUDGET: RewindBudget = RewindBudget::new(DEFAULT_BUDGET_BYTES);
&BUDGET
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_flood_of_small_writes_stays_under_the_cap() {
let mut b = RewindBuffer::new(1024);
for i in 0..10_000u64 {
b.push(i, b"y\n");
}
assert!(
b.bytes() <= 1024,
"the buffer grew past its cap: {} bytes",
b.bytes()
);
assert!(!b.is_empty(), "the buffer evicted everything");
}
#[test]
fn a_write_larger_than_the_budget_keeps_its_tail() {
let mut b = RewindBuffer::new(frame_cost(16));
let big: Vec<u8> = (0u8..100).collect();
b.push(1, &big);
assert_eq!(
b.bytes(),
frame_cost(16),
"a huge write must be clamped to the budget"
);
assert!(!b.is_empty(), "it must not vanish entirely");
let (_, frames) = b.replay_from(u64::MAX);
let kept: Vec<u8> = frames.iter().flat_map(|f| f.data.clone()).collect();
assert_eq!(
kept,
(84u8..100).collect::<Vec<u8>>(),
"the LAST 16 bytes must survive, not the first: a replay shows \
what the command most recently printed"
);
}
#[test]
fn eviction_drops_the_oldest_output_first() {
let mut b = RewindBuffer::new(2 * frame_cost(5));
b.push(1, b"aaaaa");
b.push(2, b"bbbbb");
b.push(3, b"ccccc");
let (_, frames) = b.replay_from(3);
let kept: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert!(
!kept.contains(&b"aaaaa".as_slice()),
"the oldest write should have been evicted: {kept:?}"
);
assert!(
kept.contains(&b"ccccc".as_slice()),
"the newest write must survive: {kept:?}"
);
}
#[test]
fn replay_starts_from_the_newest_keyframe_at_or_before_the_target() {
let mut b = RewindBuffer::new(1 << 20);
b.push(10, b"one");
b.push_keyframe(20, vec![String::from("screen at 20")]);
b.push(30, b"two");
b.push_keyframe(40, vec![String::from("screen at 40")]);
b.push(50, b"three");
let (kf, frames) = b.replay_from(50);
assert_eq!(
kf.map(|k| k.at_ms),
Some(40),
"must pick the newest keyframe at or before the target"
);
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(
data,
vec![b"three".as_slice()],
"only the frames after that keyframe are replayed"
);
let (kf, frames) = b.replay_from(35);
assert_eq!(kf.map(|k| k.at_ms), Some(20));
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(data, vec![b"two".as_slice()]);
let (kf_eq, frames_eq) = b.replay_from(20);
assert_eq!(
kf_eq.map(|k| k.at_ms),
Some(20),
"a keyframe exactly AT the target must be selected, not skipped"
);
let data_eq: Vec<&[u8]> = frames_eq.iter().map(|f| f.data.as_slice()).collect();
assert!(
data_eq.is_empty(),
"the replay range is [20, 20]; \"two\" at 30 is outside it: {data_eq:?}"
);
}
#[test]
fn a_frame_sharing_the_keyframes_timestamp_is_still_replayed() {
let mut b = RewindBuffer::new(1 << 20);
b.push_keyframe(20, vec![String::from("screen at 20")]);
b.push(20, b"same tick");
let (kf, frames) = b.replay_from(30);
assert_eq!(kf.map(|k| k.at_ms), Some(20));
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(
data,
vec![b"same tick".as_slice()],
"the co-timestamped frame must not be swallowed by the keyframe"
);
}
#[test]
fn a_target_before_every_keyframe_replays_from_blank() {
let mut b = RewindBuffer::new(1 << 20);
b.push(10, b"early");
b.push_keyframe(20, vec![String::from("later")]);
let (kf, frames) = b.replay_from(15);
assert!(kf.is_none(), "no keyframe precedes the target");
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(data, vec![b"early".as_slice()]);
}
#[test]
fn keyframes_do_not_outlive_the_frames_they_precede() {
let kf_bytes = ["ancient", "old", "recent"]
.iter()
.map(|s| keyframe_cost(&[String::from(*s)]))
.sum::<usize>();
let mut b = RewindBuffer::new(kf_bytes + 2 * frame_cost(5));
b.push_keyframe(1, vec![String::from("ancient")]);
b.push(2, b"aaaaa");
b.push_keyframe(3, vec![String::from("old")]);
b.push(4, b"bbbbb");
b.push_keyframe(5, vec![String::from("recent")]);
b.push(6, b"ccccc");
let (kf, _) = b.replay_from(6);
assert_eq!(
kf.map(|k| k.screen[0].as_str()),
Some("recent"),
"replay must not start from a keyframe whose frames are gone"
);
assert!(
b.keyframes.len() <= 2,
"stale keyframes accumulated: {:?}",
b.keyframes.iter().map(|k| k.at_ms).collect::<Vec<_>>()
);
}
#[test]
fn replay_never_starts_from_a_keyframe_with_evicted_frames_after_it() {
let mut b = RewindBuffer::new(keyframe_cost(&[String::from("t=1")]) + 2 * frame_cost(5));
b.push_keyframe(1, vec![String::from("t=1")]);
b.push(2, b"aaaaa");
b.push(3, b"bbbbb");
b.push(4, b"ccccc");
let oldest = b.span_ms().expect("frames remain").0;
let (kf, _) = b.replay_from(4);
assert!(
kf.is_none_or(|k| k.at_ms >= oldest),
"replay starts at keyframe {:?} but the oldest surviving frame is \
{oldest}: the output between them was evicted",
kf.map(|k| k.at_ms)
);
let mut b = RewindBuffer::new(1 << 20);
b.push_keyframe(10, vec![String::from("valid")]);
b.push(20, b"x");
b.push(30, b"y");
let (kf, _) = b.replay_from(30);
assert_eq!(
kf.map(|k| k.at_ms),
Some(10),
"an unorphaned keyframe must still be offered as a start point"
);
}
#[test]
fn eviction_within_one_millisecond_still_invalidates_the_keyframe() {
let mut b = RewindBuffer::new(
keyframe_cost(&[String::from("before any output")]) + 3 * frame_cost(5),
);
b.push_keyframe(5, vec![String::from("before any output")]);
b.push(5, b"aaaaa");
b.push(5, b"bbbbb");
b.push(5, b"ccccc");
b.push(5, b"ddddd");
let (kf, frames) = b.replay_from(5);
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert!(
!data.contains(&b"aaaaa".as_slice()),
"precondition: aaaaa must have been evicted, or this proves nothing"
);
assert!(
kf.is_none(),
"the keyframe was kept although output recorded after it was \
evicted: replaying it plus {data:?} shows a screen that never \
existed"
);
}
#[test]
fn a_backwards_timestamp_is_clamped_rather_than_hidden() {
let mut b = RewindBuffer::new(1 << 20);
b.push(1000, b"first");
b.push(500, b"clock stepped back");
b.push(1100, b"after");
let (_, frames) = b.replay_from(u64::MAX);
let seen: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert!(
seen.contains(&b"clock stepped back".as_slice()),
"output recorded across a backward step became unreachable: {seen:?}"
);
let (start, end) = b.span_ms().expect("frames remain");
assert_eq!(
(start, end),
(500, 1100),
"the span must cover the earliest and latest frame, not the first \
and last recorded"
);
}
#[test]
fn a_multi_interval_write_keeps_its_remainder() {
let mut b = RewindBuffer::new(1 << 30);
assert!(
b.push(1, &[b'x'; KEYFRAME_INTERVAL_BYTES * 3]),
"three intervals in one write must ask for a keyframe"
);
assert!(
b.push(2, b"x"),
"the remainder from the big write was discarded"
);
assert!(b.push(3, b"x"), "the second owed keyframe was discarded");
assert!(
!b.push(4, b"x"),
"a fourth keyframe was requested for three intervals of output"
);
}
#[test]
fn a_run_of_stale_keyframes_is_swept_not_just_the_newest() {
let kf_bytes = 3 * keyframe_cost(&[String::from("s1")]);
let mut b = RewindBuffer::new(kf_bytes + 2 * frame_cost(8));
b.push(10, b"aaaaaaaa");
b.push_keyframe(11, vec![String::from("s1")]);
b.push_keyframe(12, vec![String::from("s2")]);
b.push_keyframe(13, vec![String::from("s3")]);
b.push(20, b"bbbbbbbb");
b.push(30, b"cccccccc");
let (kf, frames) = b.replay_from(u64::MAX);
let data: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(
data,
vec![b"bbbbbbbb".as_slice(), b"cccccccc".as_slice()],
"the two newest writes must survive in the 16-byte budget"
);
assert!(
b.keyframe_count() <= 1,
"a run of stale keyframes was left behind: {} retained",
b.keyframe_count()
);
if let Some(k) = kf {
assert!(
k.seq + 1 >= frames[0].seq,
"retained keyframe seq {} is orphaned before frame seq {}",
k.seq,
frames[0].seq
);
}
}
#[test]
fn keyframes_collapse_to_the_newest_when_no_frames_survive() {
let mut b = RewindBuffer::new(1 << 20);
for i in 0..5u64 {
b.push_keyframe(i, vec![format!("pre{i}")]);
}
assert!(
b.is_empty(),
"precondition: no output has arrived, so there are no frames"
);
assert_eq!(
b.keyframe_count(),
1,
"keyframes must collapse to the newest when no frame survives"
);
let (kf, _) = b.replay_from(u64::MAX);
assert_eq!(
kf.map(|k| k.screen.clone()),
Some(vec![String::from("pre4")]),
"the newest pre-output keyframe must be the one retained"
);
assert_eq!(
b.bytes(),
keyframe_cost(&[String::from("pre4")]),
"the collapsed keyframes must give their bytes back"
);
let mut b = RewindBuffer::new(0);
for i in 0..5u64 {
b.push(i, b"never retained");
b.push_keyframe(i, vec![format!("k{i}")]);
}
assert!(b.is_empty());
assert_eq!(b.keyframe_count(), 0);
assert_eq!(b.bytes(), 0);
}
#[test]
fn empty_writes_do_not_accumulate_unevictable_frames() {
let mut b = RewindBuffer::new(1 << 20);
for _ in 0..10_000 {
b.push(1, b"");
}
assert!(
b.is_empty(),
"empty writes must record nothing at all, not unevictable frames"
);
assert_eq!(b.bytes(), 0);
b.push(2, b"real");
let (_, frames) = b.replay_from(u64::MAX);
let kept: Vec<&[u8]> = frames.iter().map(|f| f.data.as_slice()).collect();
assert_eq!(
kept,
vec![b"real".as_slice()],
"a non-empty write must still be recorded"
);
}
#[test]
fn a_zero_capacity_buffer_records_nothing() {
let mut b = RewindBuffer::new(0);
assert!(!b.push(1, b"anything"));
assert!(b.is_empty());
assert_eq!(b.bytes(), 0);
assert_eq!(b.span_ms(), None);
}
#[test]
fn the_span_reports_the_rewindable_range() {
let mut b = RewindBuffer::new(1 << 20);
assert_eq!(b.span_ms(), None, "an empty buffer spans nothing");
b.push(100, b"a");
b.push(900, b"b");
assert_eq!(b.span_ms(), Some((100, 900)));
}
#[test]
fn a_keyframe_is_requested_once_the_byte_interval_is_passed() {
let mut b = RewindBuffer::new(1 << 30);
let chunk = vec![b'x'; 1024];
let mut asked = 0;
for i in 0..(KEYFRAME_INTERVAL_BYTES / 1024) as u64 + 1 {
if b.push(i, &chunk) {
asked += 1;
}
}
assert_eq!(asked, 1, "exactly one keyframe should have been requested");
let mut b = RewindBuffer::new(1 << 30);
let mut asked = 0;
for i in 0..1000u64 {
if b.push(i, b"y\n") {
asked += 1;
}
}
assert_eq!(asked, 0, "2 KB of output must not trigger a keyframe");
let mut b2 = RewindBuffer::new(1 << 20);
assert!(
b2.push(1, &vec![b'x'; KEYFRAME_INTERVAL_BYTES]),
"a write landing exactly on the interval must ask for a keyframe"
);
}
fn recount(b: &RewindBuffer) -> usize {
b.frames
.iter()
.map(|f| frame_cost(f.data.len()))
.sum::<usize>()
+ b.keyframes.iter().map(|k| k.cost).sum::<usize>()
}
fn screen(rows: usize, width: usize) -> Vec<String> {
vec!["x".repeat(width); rows]
}
#[test]
fn keyframes_count_toward_the_cap() {
let cap = 64 * 1024;
let mut b = RewindBuffer::new(cap);
for i in 0..2_000u64 {
b.push(i, &[b'y'; 512]);
b.push_keyframe(i, screen(24, 80));
}
assert!(
b.bytes() <= cap,
"frames plus keyframes grew past the cap: {} > {cap}",
b.bytes()
);
assert_eq!(
b.bytes(),
recount(&b),
"the running total drifted from what is actually held"
);
assert!(b.keyframe_count() > 0, "no keyframe survived at all");
assert!(
b.keyframe_count() < 2_000,
"keyframes accumulated without bound: {}",
b.keyframe_count()
);
}
#[test]
fn a_keyframe_evicts_old_output_to_make_room() {
let kf = screen(2, 10);
let cap = 3 * frame_cost(10) + keyframe_cost(&kf);
let mut b = RewindBuffer::new(cap);
b.push(1, &[b'a'; 10]);
b.push(2, &[b'b'; 10]);
b.push(3, &[b'c'; 10]);
b.push(4, &[b'd'; 10]);
b.push_keyframe(5, kf);
assert!(b.bytes() <= cap);
assert_eq!(b.bytes(), recount(&b));
assert_eq!(b.keyframe_count(), 1, "the keyframe was stored");
let kept: Vec<u8> = b.frames.iter().map(|f| f.data[0]).collect();
assert!(!kept.contains(&b'a'), "the oldest frame must go: {kept:?}");
assert!(kept.contains(&b'd'), "the newest frame must stay: {kept:?}");
}
#[test]
fn a_keyframe_larger_than_the_budget_is_not_stored() {
let mut b = RewindBuffer::new(200);
b.push(1, b"output worth keeping");
b.push_keyframe(2, screen(10, 80));
assert_eq!(b.keyframe_count(), 0, "an oversized keyframe was stored");
let (_, frames) = b.replay_from(u64::MAX);
assert_eq!(
frames.len(),
1,
"refusing the keyframe must not cost the output it would have evicted"
);
}
#[test]
fn set_capacity_trims_immediately_and_zero_empties() {
let mut b = RewindBuffer::new(1 << 20);
for i in 0..100u64 {
b.push(i, &[b'z'; 1000]);
b.push_keyframe(i, screen(4, 40));
}
let before = b.bytes();
b.set_capacity(10_000);
assert!(b.bytes() <= 10_000, "{} bytes after shrinking", b.bytes());
assert!(b.bytes() < before);
assert_eq!(b.bytes(), recount(&b));
assert!(!b.is_empty(), "shrinking must keep the recent past");
b.set_capacity(10);
assert_eq!(b.bytes(), recount(&b));
assert!(b.bytes() <= 10);
b.set_capacity(0);
assert!(b.is_empty());
assert_eq!(b.keyframe_count(), 0);
assert_eq!(b.bytes(), 0);
assert!(!b.push(1, b"after"), "a zero cap records nothing");
}
fn flood(buf: &Arc<Mutex<RewindBuffer>>, bytes: usize) {
let mut b = buf.lock().unwrap();
for i in 0..(bytes / 1024) as u64 {
b.push(i, &[b'q'; 1024]);
}
}
#[test]
fn the_budget_is_shared_across_panes() {
let total = 1024 * 1024;
let budget = RewindBudget::new(total);
let panes: Vec<_> = (0..10).map(|_| budget.register()).collect();
for p in &panes {
flood(p, total);
}
assert!(
budget.held_bytes() <= total,
"ten panes hold {} against a shared {total}",
budget.held_bytes()
);
for p in &panes {
assert!(!p.lock().unwrap().is_empty(), "a pane was starved");
}
let extra = budget.register();
assert!(budget.held_bytes() <= total);
flood(&extra, total);
assert!(
budget.held_bytes() <= total,
"the new pane pushed the total over: {}",
budget.held_bytes()
);
assert_eq!(budget.pane_count(), 11);
assert_eq!(panes[0].lock().unwrap().capacity(), total / 11);
}
#[test]
fn releasing_a_pane_frees_it_and_returns_its_share() {
let total = 1024 * 1024;
let budget = RewindBudget::new(total);
let a = budget.register();
let b = budget.register();
flood(&a, total);
assert_eq!(b.lock().unwrap().capacity(), total / 2);
let reader_clone = a.clone();
budget.release(&a);
assert!(reader_clone.lock().unwrap().is_empty());
assert_eq!(reader_clone.lock().unwrap().capacity(), 0);
assert_eq!(budget.pane_count(), 1);
assert_eq!(
b.lock().unwrap().capacity(),
total,
"the survivor must get the freed share back"
);
}
#[test]
fn set_total_resizes_every_pane() {
let budget = RewindBudget::new(1 << 20);
let a = budget.register();
let b = budget.register();
flood(&a, 1 << 20);
budget.set_total(4096);
assert_eq!(budget.total(), 4096);
assert_eq!(a.lock().unwrap().capacity(), 2048);
assert_eq!(b.lock().unwrap().capacity(), 2048);
assert!(budget.held_bytes() <= 4096);
budget.set_total(0);
assert_eq!(budget.held_bytes(), 0, "a zero total turns rewind off");
}
#[test]
fn the_setting_maps_to_a_budget() {
assert_eq!(configured_budget_bytes(None, false), DEFAULT_BUDGET_BYTES);
assert_eq!(
configured_budget_bytes(None, true),
REMOTE_DEFAULT_BUDGET_BYTES
);
const { assert!(REMOTE_DEFAULT_BUDGET_BYTES < DEFAULT_BUDGET_BYTES) };
assert_eq!(configured_budget_bytes(Some(0), false), 0);
assert_eq!(configured_budget_bytes(Some(32), true), 32 << 20);
assert_eq!(
configured_budget_bytes(Some(usize::MAX), false),
MAX_BUDGET_MB.saturating_mul(1 << 20),
"an absurd value must clamp, not overflow"
);
}
#[test]
fn one_byte_frames_are_charged_their_slot() {
let held = |b: &RewindBuffer| {
b.frames.capacity() * std::mem::size_of::<Frame>()
+ b.frames
.iter()
.map(|f| f.data.capacity().max(MIN_ALLOCATION))
.sum::<usize>()
};
let cap = 1 << 20;
let mut b = RewindBuffer::new(cap);
for i in 0..(4u64 << 20) {
b.push(i, b".");
if i % 4096 == 0 {
assert!(
held(&b) <= cap,
"{} held against {cap} at push {i}",
held(&b)
);
}
}
assert!(
held(&b) <= cap,
"{} frames hold {} bytes against a {cap} cap",
b.frames.len(),
held(&b)
);
assert_eq!(b.bytes(), recount(&b));
assert!(b.frames.len() > 1000, "only {} frames kept", b.frames.len());
let slots_before = b.frames.capacity();
for i in 0..8u64 {
b.push((4 << 20) + i, &vec![b'x'; cap / 8]);
}
assert!(
b.frames.capacity() < slots_before / 100,
"{}",
b.frames.capacity()
);
assert!(held(&b) <= cap, "{} held after big writes", held(&b));
let mut b = RewindBuffer::new(cap);
for i in 0..20_000u64 {
b.push(i, b".");
}
let full = b.frames.capacity();
b.set_capacity(cap / 16);
assert!(
b.frames.capacity() <= full / 8,
"{} of {full}",
b.frames.capacity()
);
assert!(held(&b) <= cap / 16);
b.set_capacity(0);
assert_eq!(b.frames.capacity(), 0, "turning rewind off frees the slots");
}
#[test]
fn a_cap_below_one_frame_records_nothing() {
for cap in 0..600 {
let mut b = RewindBuffer::new(cap);
b.push(1, &[b'x'; 1000]);
assert!(b.bytes() <= cap, "cap {cap}: charged {}", b.bytes());
if let Some(len) = b.frames.front().map(|f| f.data.len()) {
assert!(
frame_cost(len + 1) > cap,
"cap {cap}: {len} bytes kept, one more fits"
);
}
}
let mut b = RewindBuffer::new(FRAME_OVERHEAD);
assert!(!b.push(1, b"x"));
assert!(b.is_empty());
assert_eq!(b.bytes(), 0);
}
}