use parking_lot::lock_api::{ArcRwLockReadGuard, ArcRwLockWriteGuard};
use parking_lot::{RawRwLock, RwLock};
use std::fmt;
use std::sync::Arc;
pub type ReadGuard<T> = ArcRwLockReadGuard<RawRwLock, T>;
pub type WriteGuard<T> = ArcRwLockWriteGuard<RawRwLock, T>;
pub struct Handle<T> {
cell: Arc<RwLock<T>>,
}
impl<T> Handle<T> {
pub fn new(value: T) -> Self {
Self {
cell: Arc::new(RwLock::new(value)),
}
}
pub fn read(&self) -> ReadGuard<T> {
self.cell.read_arc()
}
pub fn write(&self) -> WriteGuard<T> {
self.cell.write_arc()
}
pub fn same_object(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.cell, &other.cell)
}
pub fn id(&self) -> usize {
Arc::as_ptr(&self.cell) as *const () as usize
}
fn tag(&self) -> usize {
self.id() & 0xff_ffff
}
}
impl<T> Clone for Handle<T> {
fn clone(&self) -> Self {
Self {
cell: self.cell.clone(),
}
}
}
impl<T> fmt::Display for Handle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let short = std::any::type_name::<T>()
.rsplit("::")
.next()
.unwrap_or("?");
write!(f, "<{} #{:x}>", short, self.tag())
}
}
impl<T> fmt::Debug for Handle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Handle<{}> {{ #{:x} }}",
std::any::type_name::<T>(),
self.tag()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug, PartialEq)]
struct P(Vec<f64>);
#[test]
fn new_then_read() {
let h = Handle::new(P(vec![1.0, 2.0]));
assert_eq!(h.read().0, vec![1.0, 2.0]);
}
#[test]
fn write_modifies_in_place() {
let h = Handle::new(P(vec![]));
h.write().0.push(7.0);
assert_eq!(h.read().0, vec![7.0]);
}
#[test]
fn clone_shares_the_object() {
let a = Handle::new(P(vec![1.0]));
let b = a.clone();
assert!(a.same_object(&b));
b.write().0.push(2.0);
assert_eq!(a.read().0.len(), 2);
}
#[test]
fn distinct_objects_are_not_the_same() {
let a = Handle::new(P(vec![1.0]));
let b = Handle::new(P(vec![1.0]));
assert!(!a.same_object(&b), "equal contents are not one object");
}
static DROPPED: AtomicUsize = AtomicUsize::new(0);
struct Counted;
impl Drop for Counted {
fn drop(&mut self) {
DROPPED.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn the_object_dies_with_the_last_handle_and_only_then() {
DROPPED.store(0, Ordering::SeqCst);
let a = Handle::new(Counted);
let b = a.clone();
drop(a);
assert_eq!(
DROPPED.load(Ordering::SeqCst),
0,
"one handle still names it"
);
drop(b);
assert_eq!(DROPPED.load(Ordering::SeqCst), 1, "exactly one drop");
}
#[test]
fn a_guard_outlives_the_last_handle() {
DROPPED.store(0, Ordering::SeqCst);
let h = Handle::new(Counted);
let g = h.read();
drop(h);
assert_eq!(
DROPPED.load(Ordering::SeqCst),
0,
"the guard still holds it"
);
drop(g);
assert_eq!(DROPPED.load(Ordering::SeqCst), 1);
}
#[test]
fn display_does_not_touch_the_object() {
let h = Handle::new(P(vec![1.0]));
let _w = h.write();
let shown = format!("{h}");
assert!(shown.starts_with("<P #"), "unexpected: {shown}");
}
#[test]
fn concurrent_readers() {
let h = Handle::new(P(vec![1.0, 2.0]));
std::thread::scope(|s| {
for _ in 0..4 {
let h = h.clone();
s.spawn(move || {
let g = h.read();
assert_eq!(g.0.len(), 2);
});
}
});
}
}