pub struct SharedBox<T: ?Sized> { /* private fields */ }Expand description
A structure owning the original Box
which can be used to create multiple SharedBoxRef to send to other thread.
It uses a counter to record the number of SharedBoxRef that has been created and not given back.
Dropping SharedBox without returning all SharedBoxRef that it has created leaks its heap memory.
When panic-on-drop feature is enabled, it will panic:
let r = {
let mut b = manual_share::SharedBox::new(0);
b.borrow()
// dropping SharedBox, panic here
};
println!("{}", r.get());When all SharedBoxRef have been returned back to SharedBox,
it will free and properly release its heap memory when SharedBox is dropped.
let mut b = manual_share::SharedBox::new(0);
let r = b.borrow();
b.try_return(r).unwrap();
// Dropping SharedBox here will free the heap memory it owns. No panic will occur.Implementations§
Sourcepub fn borrow(&mut self) -> SharedBoxRef<T>
pub fn borrow(&mut self) -> SharedBoxRef<T>
Create a SharedBoxRef and increase the borrow count.
§panics
Panics when borrow count overflows usize.
Sourcepub fn try_return(
&mut self,
reference: SharedBoxRef<T>,
) -> Result<(), SharedBoxRef<T>>
pub fn try_return( &mut self, reference: SharedBoxRef<T>, ) -> Result<(), SharedBoxRef<T>>
Try to return back the SharedBoxRef.
Returns Err if the SharedBoxRef does not originate from the same SharedBox.
Decrease the borrow count if not error occurs.
use manual_share::SharedBox;
let mut b1 = SharedBox::from_box(Box::new(8));
let r1 = b1.borrow();
b1.try_return(r1).unwrap();
let mut b2 = SharedBox::from_box(Box::new(9));
let r2 = b2.borrow();
// Giving SharedBoxRef to the wrong SharedBox returns Err.
let r2 = b1.try_return(r2).unwrap_err();
b2.try_return(r2).unwrap();Sourcepub fn try_into_box(self) -> Result<Box<T>, Self>
pub fn try_into_box(self) -> Result<Box<T>, Self>
Try to convert Self into a Box if all borrowed SharedBoxRef has been given back.
use manual_share::SharedBox;
let b = Box::new(0);
let mut b = SharedBox::from_box(b);
let r = b.borrow();
// Try to convert to Box without returning all SharedBoxRef returns Err.
let mut b = b.try_into_box().unwrap_err();
b.try_return(r).unwrap();
let b = b.try_into_box().unwrap();
assert_eq!(b, Box::new(0));