use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use ropey::Rope;
use crate::Revision;
#[derive(Debug, Default)]
pub struct RopeSnapshotRegistry {
by_id: Mutex<HashMap<u64, Weak<Rope>>>,
}
impl RopeSnapshotRegistry {
#[must_use]
pub fn instance() -> &'static Self {
static INSTANCE: OnceLock<RopeSnapshotRegistry> = OnceLock::new();
INSTANCE.get_or_init(RopeSnapshotRegistry::default)
}
#[must_use]
pub fn live_snapshot_count(&self) -> usize {
match self.by_id.lock() {
Ok(map) => map.values().filter(|weak| weak.strong_count() > 0).count(),
Err(_) => 0,
}
}
#[must_use]
pub fn distinct_arc_heads(&self) -> usize {
let Ok(map) = self.by_id.lock() else {
return 0;
};
let mut heads: Vec<*const Rope> = Vec::with_capacity(map.len());
for weak in map.values() {
if let Some(strong) = weak.upgrade() {
heads.push(Arc::as_ptr(&strong));
}
}
heads.sort_unstable();
heads.dedup();
heads.len()
}
fn register(&self, id: u64, rope: &Arc<Rope>) {
if let Ok(mut map) = self.by_id.lock() {
map.insert(id, Arc::downgrade(rope));
}
}
fn deregister(&self, id: u64) {
if let Ok(mut map) = self.by_id.lock() {
map.remove(&id);
}
}
}
fn next_snapshot_id() -> u64 {
static COUNTER: AtomicU64 = AtomicU64::new(1);
COUNTER.fetch_add(1, Ordering::Relaxed)
}
#[derive(Debug)]
pub struct RopeSnapshot {
rope: Arc<Rope>,
revision: Revision,
registry_id: u64,
}
impl Clone for RopeSnapshot {
fn clone(&self) -> Self {
let registry_id = next_snapshot_id();
RopeSnapshotRegistry::instance().register(registry_id, &self.rope);
Self {
rope: Arc::clone(&self.rope),
revision: self.revision,
registry_id,
}
}
}
impl Drop for RopeSnapshot {
fn drop(&mut self) {
RopeSnapshotRegistry::instance().deregister(self.registry_id);
}
}
impl RopeSnapshot {
#[must_use]
pub fn new(rope: Arc<Rope>, revision: Revision) -> Self {
let registry_id = next_snapshot_id();
RopeSnapshotRegistry::instance().register(registry_id, &rope);
Self {
rope,
revision,
registry_id,
}
}
#[must_use]
pub fn rope(&self) -> &Rope {
&self.rope
}
#[must_use]
pub fn rope_arc(&self) -> &Arc<Rope> {
&self.rope
}
#[must_use]
pub fn revision(&self) -> Revision {
self.revision
}
}
#[cfg(test)]
mod tests {
use super::*;
fn count_snapshots_for_rope(registry: &RopeSnapshotRegistry, rope: &Arc<Rope>) -> usize {
registry
.by_id
.lock()
.expect("test registry lock should not be poisoned")
.values()
.filter_map(Weak::upgrade)
.filter(|registered| Arc::ptr_eq(registered, rope))
.count()
}
#[test]
fn snapshot_clone_shares_underlying_rope() {
let rope = Arc::new(Rope::from_str("hello"));
let s = RopeSnapshot::new(Arc::clone(&rope), Revision(5));
let s2 = s.clone();
assert_eq!(s.revision(), s2.revision());
assert!(std::ptr::eq(s.rope(), s2.rope()));
assert_eq!(s.rope().to_string(), "hello");
}
#[test]
fn snapshot_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RopeSnapshot>();
}
#[test]
fn snapshot_registry_tracks_distinct_heads() {
let registry = RopeSnapshotRegistry::instance();
let rope_a = Arc::new(Rope::from_str("alpha"));
let s1 = RopeSnapshot::new(Arc::clone(&rope_a), Revision(1));
let s2 = s1.clone();
assert_eq!(count_snapshots_for_rope(registry, &rope_a), 2);
let rope_b = Arc::new(Rope::from_str("beta"));
let s3 = RopeSnapshot::new(Arc::clone(&rope_b), Revision(2));
assert_eq!(count_snapshots_for_rope(registry, &rope_b), 1);
drop(s1);
drop(s2);
drop(s3);
assert_eq!(count_snapshots_for_rope(registry, &rope_a), 0);
assert_eq!(count_snapshots_for_rope(registry, &rope_b), 0);
}
}