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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! Shared live-stream state. In M1 every stdin-bound widget renders from one
//! shared buffer (per-widget transforms/queries arrive with the query engine).
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Instant;
pub struct StreamState {
/// Lines are `Arc<str>`, not `String`, so a consumer that needs to keep its
/// own list — fzf mode builds a candidate per line — shares this allocation
/// instead of copying the text. At a million lines that copy was ~113MB.
pub lines: VecDeque<Arc<str>>,
pub total: u64,
pub start: Instant,
cap: usize,
}
impl StreamState {
pub fn new() -> Self {
Self::with_cap(5000)
}
/// A stream buffer with a custom retention cap. `usize::MAX` = keep every
/// line (fzf select mode, where dropping lines would lose marks and shift the
/// cursor as the stream grows).
pub fn with_cap(cap: usize) -> Self {
Self {
lines: VecDeque::new(),
total: 0,
start: Instant::now(),
cap,
}
}
/// Append a line, dropping the oldest beyond the retention cap.
pub fn push(&mut self, line: impl Into<Arc<str>>) {
self.lines.push_back(line.into());
self.total += 1;
self.trim();
}
/// Append a whole batch under one lock — the reader hands lines over in
/// chunks, so a fast producer doesn't pay a mutex round trip per line.
pub fn extend<I: IntoIterator<Item = Arc<str>>>(&mut self, batch: I) {
for line in batch {
self.lines.push_back(line);
self.total += 1;
}
self.trim();
}
fn trim(&mut self) {
while self.lines.len() > self.cap {
self.lines.pop_front();
}
}
/// Lines per second since start.
pub fn rate(&self) -> f64 {
let secs = self.start.elapsed().as_secs_f64().max(0.001);
self.total as f64 / secs
}
}
impl Default for StreamState {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_bounds_retention_to_cap_but_counts_all() {
let mut s = StreamState::with_cap(3);
for i in 0..10 {
s.push(format!("line{i}"));
}
// Only the last `cap` lines are retained (oldest dropped)...
assert_eq!(s.lines.len(), 3);
assert_eq!(s.lines.front().map(|l| &**l), Some("line7"));
assert_eq!(s.lines.back().map(|l| &**l), Some("line9"));
// ...but `total` counts every line ever pushed, so a finite cap bounds
// memory without losing the cumulative count.
assert_eq!(s.total, 10);
}
}