Skip to content

Commit

Permalink
Merge pull request #16 from wasmerio/impl-for-weak
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan authored May 27, 2021
2 parents dad9613 + 6a15807 commit 3108424
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion crates/loupe/src/memory_usage/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::{
AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32,
AtomicU64, AtomicU8, AtomicUsize,
},
Arc, Mutex, RwLock,
Arc, Mutex, RwLock, Weak,
};

macro_rules! impl_memory_usage_for_numeric {
Expand Down Expand Up @@ -52,6 +52,22 @@ where
}
}

impl<T> MemoryUsage for Weak<T>
where
T: MemoryUsage + ?Sized,
{
fn size_of_val(&self, tracker: &mut dyn MemoryUsageTracker) -> usize {
mem::size_of_val(self)
+ if tracker.track(Weak::as_ptr(self) as *const ()) {
Weak::upgrade(self)
.map(|arc| arc.as_ref().size_of_val(tracker))
.unwrap_or(0)
} else {
0
}
}
}

impl<T> MemoryUsage for Mutex<T>
where
T: MemoryUsage + ?Sized,
Expand Down Expand Up @@ -112,6 +128,25 @@ mod test_sync_types {
assert_size_of_val_eq!(arc, empty_arc_size + POINTER_BYTE_SIZE + 4);
}

#[test]
fn test_weak() {
let empty_weak_size = mem::size_of_val(&Arc::downgrade(&Arc::new(())));

let arc: Arc<i32> = Arc::new(1);
let weak: Weak<i32> = Arc::downgrade(&arc);
assert_size_of_val_eq!(weak, empty_weak_size + 4);

let arc: Arc<Option<i32>> = Arc::new(Some(1));
let weak: Weak<Option<i32>> = Arc::downgrade(&arc);
assert_size_of_val_eq!(weak, empty_weak_size + POINTER_BYTE_SIZE + 4);

let weak: Weak<i32> = {
let arc: Arc<i32> = Arc::new(5);
Arc::downgrade(&arc)
};
assert_size_of_val_eq!(weak, empty_weak_size);
}

#[test]
fn test_mutex() {
let empty_mutex_size = mem::size_of_val(&Mutex::new(()));
Expand Down

0 comments on commit 3108424

Please sign in to comment.