Skip to content

Commit 16db51d

Browse files
committed
Implement Box::forget for the singleton pool
1 parent ab9f251 commit 16db51d

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

src/pool/singleton.rs

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,32 @@ where
146146
}
147147
}
148148

149+
impl<P> Box<P, Init>
150+
where
151+
P: Pool,
152+
{
153+
/// Forgets the contents of this memory block without running its destructor.
154+
///
155+
/// Note that this this does not return the memory block to the pool. The
156+
/// block can be reused, or returned to the pool by dropping it.
157+
pub fn forget(self) -> Box<P, Uninit> {
158+
let node = self.inner.node;
159+
160+
mem::forget(self);
161+
mem::forget(unsafe {
162+
ptr::read(node.as_ref().data.get())
163+
});
164+
165+
Box {
166+
inner: super::Box {
167+
node,
168+
_state: PhantomData,
169+
},
170+
_pool: PhantomData,
171+
}
172+
}
173+
}
174+
149175
impl<P> Deref for Box<P>
150176
where
151177
P: Pool,
@@ -348,17 +374,23 @@ mod tests {
348374

349375
let x = A::alloc().unwrap().init(X::new());
350376
let y = A::alloc().unwrap().init(X::new());
377+
let z = A::alloc().unwrap().init(X::new());
351378

352-
assert_eq!(COUNT.load(Ordering::Relaxed), 2);
379+
assert_eq!(COUNT.load(Ordering::Relaxed), 3);
353380

354381
// this runs `X`'s destructor
355382
drop(x);
356383

357-
assert_eq!(COUNT.load(Ordering::Relaxed), 1);
384+
assert_eq!(COUNT.load(Ordering::Relaxed), 2);
358385

359386
// this leaks memory
360387
mem::forget(y);
361388

362-
assert_eq!(COUNT.load(Ordering::Relaxed), 1);
389+
assert_eq!(COUNT.load(Ordering::Relaxed), 2);
390+
391+
// this forgets `X` without leaking memory
392+
z.forget();
393+
394+
assert_eq!(COUNT.load(Ordering::Relaxed), 2);
363395
}
364396
}

0 commit comments

Comments
 (0)