summaryrefslogtreecommitdiff
path: root/Algorithms/bplus-tree/src/bplus_remove.c
blob: 9265ce18d2a67a93557662d758dad4c61485c7b7 (plain)
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
/**
 * Distributed under the Boost Software License, Version 1.0.
 * See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
 */

#include "bplus_remove.h"

#include "bplus_node.h"
#include "bplus_search.h"
#include "bplus_rebalance.h"

void bplus_node_remove_at(BplusTree const* tree, BplusNode* node, size_t const index, size_t const length)
{
    g_return_if_fail(node != NULL);
    g_return_if_fail(index < node->length);
    g_return_if_fail(index + length <= node->length);

    bplus_node_move_and_resize_data(tree, node, index, index + length);
}

BplusValue bplus_tree_remove_first(BplusTree* tree)
{
    BplusPath    path  = { .leaf = (BplusNode*) tree->first };
    BplusNode*   node  = (BplusNode*) path.leaf;
    size_t const index = path.index[0];

    BplusValue value = bplus_value_at(node, 0);
    bplus_node_remove_at(tree, node, index, 1);
    if (index == 0)
        bplus_rebalance_propagate(tree, &path);

    if (bplus_node_underfilled(node))
        bplus_rebalance_underfilled(tree, &path);

    return value;
}

BplusValue bplus_tree_remove(BplusTree* tree, BplusKey const key)
{
    BplusPath path;
    bplus_tree_get_path_to_key(tree, key, &path);

    size_t const index = path.index[0];
    BplusNode*   node  = (BplusNode*) path.leaf;

    if (bplus_key_eq(tree, bplus_key_at(node, index), key))
    {
        BplusValue value = bplus_value_at(node, index);
        bplus_node_remove_at(tree, node, index, 1);
        if (index == 0)
            bplus_rebalance_propagate(tree, &path);

        if (bplus_node_underfilled(node))
            bplus_rebalance_underfilled(tree, &path);

        return value;
    }

    return NULL;
}