Skip to content

Commit 669bd82

Browse files
committed
Make LeafNode #[repr(C)] and put the metadata before generic items
This way we can safely statically allocate a LeafNode to use as the placeholder before allocating, and any type accessing it will be able to access the metadata at the same offset.
1 parent 64e6dda commit 669bd82

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/liballoc/btree/node.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,12 @@ pub const CAPACITY: usize = 2 * B - 1;
6060
///
6161
/// See also rust-lang/rfcs#197, which would make this structure significantly more safe by
6262
/// avoiding accidentally dropping unused and uninitialized keys and values.
63+
///
64+
/// We put the metadata first so that its position is the same for every `K` and `V`, in order
65+
/// to statically allocate a single dummy node to avoid allocations. This struct is `repr(C)` to
66+
/// prevent them from being reordered.
67+
#[repr(C)]
6368
struct LeafNode<K, V> {
64-
/// The arrays storing the actual data of the node. Only the first `len` elements of each
65-
/// array are initialized and valid.
66-
keys: [K; CAPACITY],
67-
vals: [V; CAPACITY],
68-
6969
/// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`.
7070
/// This either points to an actual node or is null.
7171
parent: *const InternalNode<K, V>,
@@ -77,10 +77,14 @@ struct LeafNode<K, V> {
7777

7878
/// The number of keys and values this node stores.
7979
///
80-
/// This is at the end of the node's representation and next to `parent_idx` to encourage
81-
/// the compiler to join `len` and `parent_idx` into the same 32-bit word, reducing space
82-
/// overhead.
80+
/// This next to `parent_idx` to encourage the compiler to join `len` and
81+
/// `parent_idx` into the same 32-bit word, reducing space overhead.
8382
len: u16,
83+
84+
/// The arrays storing the actual data of the node. Only the first `len` elements of each
85+
/// array are initialized and valid.
86+
keys: [K; CAPACITY],
87+
vals: [V; CAPACITY],
8488
}
8589

8690
impl<K, V> LeafNode<K, V> {

0 commit comments

Comments
 (0)