fn insert(self: *Self, key: Key, parent: ?*Node, node: *Node) void 196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218 fn insert(self: *Self, key: Key, parent: ?*Node, node: *Node) void {
// generate a random priority & prepare the node to be inserted into the tree
node.key = key;
node.priority = self.prng.random(@intFromPtr(node));
node.parent = parent;
node.children = [_]?*Node{ null, null };
// point the parent at the new node
const link = if (parent) |p| &p.children[@intFromBool(compare(key, p.key) == .gt)] else &self.root;
assert(link.* == null);
link.* = node;
// rotate the node up into the tree to balance it according to its priority
while (node.parent) |p| {
if (p.priority <= node.priority) break;
const is_right = p.children[1] == node;
assert(p.children[@intFromBool(is_right)] == node);
const rotate_right = !is_right;
self.rotate(p, rotate_right);
}
}