refactor: reuse built-ins and shared helpers
This commit is contained in:
@@ -36,7 +36,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use thiserror::Error;
|
||||
@@ -712,7 +712,7 @@ impl DiagnosticExport {
|
||||
/// diagnostic export and state-sync replay verification.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProtocolEventRecorder {
|
||||
events: Vec<String>,
|
||||
events: VecDeque<String>,
|
||||
capacity: usize,
|
||||
}
|
||||
|
||||
@@ -720,17 +720,20 @@ impl ProtocolEventRecorder {
|
||||
/// Create a recorder with the given ring-buffer capacity.
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
events: Vec::with_capacity(capacity),
|
||||
events: VecDeque::with_capacity(capacity),
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, ts: &str, kind: &str, detail: &str) {
|
||||
if self.capacity == 0 {
|
||||
return;
|
||||
}
|
||||
let s = format!("[{ts}] {kind}: {detail}");
|
||||
if self.events.len() >= self.capacity {
|
||||
self.events.remove(0);
|
||||
self.events.pop_front();
|
||||
}
|
||||
self.events.push(s);
|
||||
self.events.push_back(s);
|
||||
}
|
||||
|
||||
/// Record a successful connection.
|
||||
@@ -777,12 +780,12 @@ impl ProtocolEventRecorder {
|
||||
|
||||
/// Drain all recorded events and reset the buffer.
|
||||
pub fn drain(&mut self) -> Vec<String> {
|
||||
std::mem::take(&mut self.events)
|
||||
self.events.drain(..).collect()
|
||||
}
|
||||
|
||||
/// Snapshot all recorded events without clearing the buffer.
|
||||
pub fn snapshot(&self) -> Vec<String> {
|
||||
self.events.clone()
|
||||
self.events.iter().cloned().collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,4 +1106,13 @@ mod tests {
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(drained, first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_event_zero_capacity_drops_events() {
|
||||
let mut recorder = ProtocolEventRecorder::new(0);
|
||||
recorder.record_connected("Server");
|
||||
|
||||
assert!(recorder.snapshot().is_empty());
|
||||
assert!(recorder.drain().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user