Skip to main content

heap_drop/
lib.rs

1//! Provides a way of deallocating a value using a heap-allocated queue to traverse fields instead of stack recursion.
2//!
3//! This effectively does nothing for types which implement `Copy`, e.g.
4//! integers. Such values are copied and _then_ moved into the function, so the
5//! value persists after this function call.
6//!
7//! # Examples
8//!
9//! Basic usage:
10//!
11//! ```
12//! use heap_drop::{HeapDrop, heap_drop};
13//!
14//! #[derive(HeapDrop)]
15//! struct Node(Option<Box<Node>>);
16//!
17//! let v = Node(Some(Box::new(Node(None /* could be a very deep structure */))));
18//! heap_drop(v);
19//! ```
20//!
21use std::collections::VecDeque;
22
23pub use heap_drop_macros::HeapDrop;
24
25/// A trait that allows a type to be disposed of using a heap-allocated queue instead of the stack.
26///
27/// See the [heap_drop] function.
28pub trait HeapDrop {
29    /// Returns a vector of children of the current value which implement `HeapDrop`.
30    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>>;
31}
32
33// standard library implementations
34
35impl<T: HeapDrop + 'static> HeapDrop for Option<T> {
36    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
37        match *self {
38            Some(value) => vec![Box::new(value) as Box<dyn HeapDrop>],
39            None => vec![],
40        }
41    }
42}
43
44impl<T: HeapDrop + 'static> HeapDrop for Box<T> {
45    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
46        vec![*self as Box<dyn HeapDrop>]
47    }
48}
49
50impl<T: HeapDrop + 'static> HeapDrop for Vec<T> {
51    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
52        self.into_iter().map(|item| Box::new(item) as Box<dyn HeapDrop>).collect()
53    }
54}
55
56impl<T: HeapDrop + 'static> HeapDrop for VecDeque<T> {
57    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
58        self.into_iter().map(|item| Box::new(item) as Box<dyn HeapDrop>).collect()
59    }
60}
61
62impl<T: HeapDrop + 'static> HeapDrop for std::collections::LinkedList<T> {
63    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
64        self.into_iter().map(|item| Box::new(item) as Box<dyn HeapDrop>).collect()
65    }
66}
67
68impl<T: HeapDrop + 'static> HeapDrop for std::collections::HashSet<T> {
69    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
70        self.into_iter().map(|item| Box::new(item) as Box<dyn HeapDrop>).collect()
71    }
72}
73
74impl<K, V: HeapDrop + 'static> HeapDrop for std::collections::HashMap<K, V> {
75    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
76        self.into_values().map(|value| Box::new(value) as Box<dyn HeapDrop>).collect()
77    }
78}
79
80impl<T: HeapDrop + 'static> HeapDrop for std::cell::Cell<T> {
81    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
82        vec![Box::new(self.into_inner()) as Box<dyn HeapDrop>]
83    }
84}
85
86impl<T: HeapDrop + 'static> HeapDrop for core::cell::RefCell<T> {
87    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
88        vec![Box::new(self.into_inner()) as Box<dyn HeapDrop>]
89    }
90}
91
92impl<T: HeapDrop + 'static> HeapDrop for std::rc::Rc<T> {
93    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
94        vec![Box::new((*self).clone()) as Box<dyn HeapDrop>]
95    }
96}
97
98impl<T: HeapDrop + 'static> HeapDrop for std::sync::Arc<T> {
99    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
100        vec![Box::new((*self).clone()) as Box<dyn HeapDrop>]
101    }
102}
103
104impl<T: HeapDrop + 'static> HeapDrop for std::sync::Mutex<T> {
105    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
106        vec![Box::new(self.into_inner().unwrap()) as Box<dyn HeapDrop>]
107    }
108}
109
110impl<T: HeapDrop + 'static> HeapDrop for std::sync::RwLock<T> {
111    fn into_children(self: Box<Self>) -> Vec<Box<dyn HeapDrop>> {
112        vec![Box::new(self.into_inner().unwrap()) as Box<dyn HeapDrop>]
113    }
114}
115
116// implementation detection logic
117
118#[doc(hidden)]
119pub struct HeapDropDetect<T>(pub Box<T>);
120
121#[doc(hidden)]
122pub trait HeapDropDetectFallback {
123    fn detect(self) -> Option<Box<dyn HeapDrop>>;
124}
125
126impl<T> HeapDropDetectFallback for HeapDropDetect<T> {
127    fn detect(self) -> Option<Box<dyn HeapDrop>> {
128        None
129    }
130}
131
132impl<T: HeapDrop + 'static> HeapDropDetect<T> {
133    pub fn detect(self) -> Option<Box<dyn HeapDrop>> {
134        Some(self.0 as Box<dyn HeapDrop>)
135    }
136}
137
138/// A macro that attempts to cast a value to a `Box<dyn HeapDrop>`, returning `None` if the value does not implement `HeapDrop`.
139///
140/// This macro requires that the value has a concrete type in the caller scope, and will not work with generic type parameters.
141/// It is not part of the public API and should not be used outside of the crate.
142#[doc(hidden)]
143#[macro_export]
144macro_rules! maybe_as_heap_drop {
145    ($val:expr) => {{
146        #[allow(unused_imports)]
147        use $crate::HeapDropDetectFallback;
148        $crate::HeapDropDetect(Box::new($val)).detect()
149    }};
150}
151
152// public api functions
153
154/// Disposes of a value using a heap-allocated queue to traverse fields instead of the stack.
155///
156/// This effectively does nothing for types which implement `Copy`, e.g.
157/// integers. Such values are copied and _then_ moved into the function, so the
158/// value persists after this function call.
159///
160/// # Examples
161///
162/// Basic usage:
163///
164/// ```
165/// use heap_drop::{HeapDrop, heap_drop};
166///
167/// #[derive(HeapDrop)]
168/// struct Node(Option<Box<Node>>);
169///
170/// let v = Node(Some(Box::new(Node(None /* could be a very deep structure */))));
171/// heap_drop(v);
172/// ```
173pub fn heap_drop<T: HeapDrop>(value: T) {
174    let mut queue = VecDeque::new();
175
176    // add all anscestors to the queue and drop them one by one
177    queue.push_back(Box::new(value) as Box<dyn HeapDrop>);
178    while let Some(item) = queue.pop_front() {
179        let children = item.into_children();
180        queue.extend(children);
181    }
182}