|
| 1 | +--- |
| 2 | +title: Custom Smart Pointer |
| 3 | +description: Implementation of a custom reference-counted smart pointer with interior mutability |
| 4 | +author: pyyupsk |
| 5 | +tags: rust,smart-pointer,memory-management,unsafe |
| 6 | +--- |
| 7 | + |
| 8 | +```rust |
| 9 | +use std::cell::UnsafeCell; |
| 10 | +use std::ops::{Deref, DerefMut}; |
| 11 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
| 12 | +use std::sync::Arc; |
| 13 | + |
| 14 | +pub struct Interior<T> { |
| 15 | + ref_count: AtomicUsize, |
| 16 | + data: UnsafeCell<T>, |
| 17 | +} |
| 18 | + |
| 19 | +pub struct SmartPtr<T> { |
| 20 | + ptr: Arc<Interior<T>>, |
| 21 | +} |
| 22 | + |
| 23 | +impl<T> SmartPtr<T> { |
| 24 | + pub fn new(data: T) -> Self { |
| 25 | + SmartPtr { |
| 26 | + ptr: Arc::new(Interior { |
| 27 | + ref_count: AtomicUsize::new(1), |
| 28 | + data: UnsafeCell::new(data), |
| 29 | + }), |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + pub fn get_ref_count(&self) -> usize { |
| 34 | + self.ptr.ref_count.load(Ordering::SeqCst) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl<T> Clone for SmartPtr<T> { |
| 39 | + fn clone(&self) -> Self { |
| 40 | + self.ptr.ref_count.fetch_add(1, Ordering::SeqCst); |
| 41 | + SmartPtr { |
| 42 | + ptr: Arc::clone(&self.ptr), |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl<T> Drop for SmartPtr<T> { |
| 48 | + fn drop(&mut self) { |
| 49 | + if self.ptr.ref_count.fetch_sub(1, Ordering::SeqCst) == 1 { |
| 50 | + // Last reference is being dropped |
| 51 | + unsafe { |
| 52 | + drop(Box::from_raw(self.ptr.data.get())); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<T> Deref for SmartPtr<T> { |
| 59 | + type Target = T; |
| 60 | + |
| 61 | + fn deref(&self) -> &Self::Target { |
| 62 | + unsafe { &*self.ptr.data.get() } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl<T> DerefMut for SmartPtr<T> { |
| 67 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 68 | + unsafe { &mut *self.ptr.data.get() } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// Usage: |
| 73 | +let ptr = SmartPtr::new(42); |
| 74 | +let cloned = ptr.clone(); |
| 75 | +assert_eq!(ptr.get_ref_count(), 2); |
| 76 | +assert_eq!(*ptr, 42); |
| 77 | +``` |
0 commit comments