1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Internal shared allocations free their control block before capacity owners.
//!
//! This primitive supports embedded resource lifetimes across internal crates;
//! hosts should use facade APIs rather than treat it as an integration endpoint.
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::sync::Arc;
#[doc(hidden)]
#[derive(Debug)]
pub struct SharedAllocation<T>(ManuallyDrop<Arc<T>>);
impl<T> SharedAllocation<T> {
pub fn new(value: T) -> Self {
Self(ManuallyDrop::new(Arc::new(value)))
}
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.0)
}
}
impl<T> Clone for SharedAllocation<T> {
fn clone(&self) -> Self {
Self(ManuallyDrop::new(Arc::clone(&self.0)))
}
}
impl<T> Deref for SharedAllocation<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Drop for SharedAllocation<T> {
fn drop(&mut self) {
// Every clone takes this path. Concurrent final drops therefore extract
// the payload exactly once. No weak references or raw Arcs escape, so
// into_inner frees the control block before the returned payload dies.
// An ordinary Arc drop would release a payload's lease before freeing
// the block whose capacity it also accounts for.
// SAFETY: Drop runs once; no method accesses the field after this take.
// ManuallyDrop preserves Arc's representation and prevents a second drop.
let arc = unsafe { ManuallyDrop::take(&mut self.0) };
drop(Arc::into_inner(arc));
}
}