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
//! Register system — a yank ring for clipboard history.
//!
//! The yank ring is the authoritative source of clipboard history. The
//! system clipboard is only a best-effort synchronisation target; all paste
//! operations read from the ring rather than the OS clipboard.
use std::collections::VecDeque;
/// A fixed-capacity ring of yanked strings, newest at the front.
#[derive(Debug, Default)]
pub struct Registers {
ring: VecDeque<String>,
max: usize,
}
impl Registers {
pub fn new(max: usize) -> Self {
Self {
ring: VecDeque::with_capacity(max),
max,
}
}
/// Push a new entry. Consecutive duplicates are silently dropped.
pub fn push(&mut self, text: String) {
if text.is_empty() {
return;
}
if self.ring.front().map(|t| t == &text).unwrap_or(false) {
return;
}
self.ring.push_front(text);
if self.ring.len() > self.max {
self.ring.pop_back();
}
}
/// The most recently yanked text.
pub fn latest(&self) -> Option<&str> {
self.ring.front().map(|s| s.as_str())
}
/// Get the entry at position `idx` (0 = newest).
pub fn get(&self, idx: usize) -> Option<&str> {
self.ring.get(idx).map(|s| s.as_str())
}
pub fn len(&self) -> usize {
self.ring.len()
}
pub fn is_empty(&self) -> bool {
self.ring.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &String> {
self.ring.iter()
}
}