Files
osc2025/lib/initrd.c
2025-04-08 06:59:49 +08:00

89 lines
1.4 KiB
C

#include <stddef.h>
#include <initrd.h>
#include <kmalloc.h>
#include <random.h>
#include <string.h>
#define nullnode ((file_node_t *)0)
void _init_node(file_node_t *node) {
node->l = nullnode;
node->r = nullnode;
node->rand = random();
node->node_size = 1;
}
void _pull_from(file_node_t *to, file_node_t *from)
{
if (!from)
return;
to->node_size += from->node_size;
}
void _pull(file_node_t *node)
{
node->node_size = 1;
_pull_from(node, node->l);
_pull_from(node, node->r);
}
file_node_t *_merge(file_node_t *a, file_node_t *b)
{
if (!a || !b)
return a ?: b;
if (a->rand < b->rand) {
a->r = _merge(a->r, b);
_pull(a);
return a;
}
b->l = _merge(a, b->l);
_pull(b);
return b;
}
void _split(file_node_t *rt, const char *s, file_node_t **a, file_node_t **b)
{
if (!rt) {
*a = *b = nullnode;
return;
}
if (strcmp(s, rt->filename) < 0) {
*a = rt;
_split((*a)->r, s, &(*a)->r, b);
_pull(*a);
} else {
*b = rt;
_split((*b)->l, s, a, &(*b)->l);
_pull(*b);
}
}
file_node_t *initrd_init(void)
{
// TODO
return nullnode;
}
file_node_t *_node_bs(file_node_t *cur, const char *s)
{
if (!cur)
return nullnode;
int cmp = strcmp(s, cur->filename);
if (cmp < 0)
return _node_bs(cur->r, s);
if (cmp > 0)
return _node_bs(cur->l, s);
return cur; // cmp == 0
}
file_node_t *initrd_get(file_node_t *root, const char *filename)
{
return _node_bs(root, filename);
}