initial commit
This commit is contained in:
4
exercises/07_threads/06_interior_mutability/Cargo.toml
Normal file
4
exercises/07_threads/06_interior_mutability/Cargo.toml
Normal file
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "interior_mutability"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
46
exercises/07_threads/06_interior_mutability/src/lib.rs
Normal file
46
exercises/07_threads/06_interior_mutability/src/lib.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
// TODO: Use `Rc` and `RefCell` to implement `DropTracker<T>`, a wrapper around a value of type `T`
|
||||
// that increments a shared `usize` counter every time the wrapped value is dropped.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub struct DropTracker<T> {
|
||||
value: T,
|
||||
counter: todo!(),
|
||||
}
|
||||
|
||||
impl<T> DropTracker<T> {
|
||||
pub fn new(value: T, counter: todo!()) -> Self {
|
||||
Self { value, counter }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for DropTracker<T> {
|
||||
fn drop(&mut self) {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let counter = Rc::new(RefCell::new(0));
|
||||
let _ = DropTracker::new((), Rc::clone(&counter));
|
||||
assert_eq!(*counter.borrow(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple() {
|
||||
let counter = Rc::new(RefCell::new(0));
|
||||
|
||||
{
|
||||
let a = DropTracker::new(5, Rc::clone(&counter));
|
||||
let b = DropTracker::new(6, Rc::clone(&counter));
|
||||
}
|
||||
|
||||
assert_eq!(*counter.borrow(), 2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user