diff --git a/core/src/chunk.rs b/core/src/chunk.rs index 6dc5a6c..544a84a 100644 --- a/core/src/chunk.rs +++ b/core/src/chunk.rs @@ -181,6 +181,11 @@ impl Chunk { next_chunk } + + pub(crate) fn clear(&mut self) { + self.next = None; + self.prev = None; + } } impl ToString for Chunk { diff --git a/core/src/magic_string.rs b/core/src/magic_string.rs index 8a70cd4..637de64 100644 --- a/core/src/magic_string.rs +++ b/core/src/magic_string.rs @@ -811,3 +811,21 @@ impl ToString for MagicString { format!("{}{}", str, self.outro) } } + +impl Drop for MagicString { + fn drop(&mut self) { + // explicitly clear Rc RefCell cyclic references by setting them to + // None before dropping to avoid memory leak caused by reference cycles + self.last_chunk.borrow_mut().clear(); + self.first_chunk.borrow_mut().clear(); + self.last_searched_chunk.borrow_mut().clear(); + self + .chunk_by_end + .iter_mut() + .for_each(|v| v.1.borrow_mut().clear()); + self + .chunk_by_start + .iter_mut() + .for_each(|v| v.1.borrow_mut().clear()); + } +}