byedpi/mpool.c

102 lines
1.8 KiB
C
Raw Permalink Normal View History

2024-08-07 11:25:26 +00:00
#include "mpool.h"
2024-03-08 00:37:02 +00:00
#include <stdlib.h>
#include <string.h>
2024-05-08 17:15:57 +00:00
2024-03-08 00:37:02 +00:00
2024-04-16 17:55:41 +00:00
static inline int scmp(const struct elem *p, const struct elem *q)
2024-03-08 00:37:02 +00:00
{
2024-04-16 17:55:41 +00:00
if (p->len != q ->len) {
return p->len < q->len ? -1 : 1;
2024-03-08 00:37:02 +00:00
}
2024-04-16 17:55:41 +00:00
return memcmp(p->data, q->data, p->len);
}
2024-03-08 00:37:02 +00:00
2024-04-16 17:55:41 +00:00
KAVL_INIT(my, struct elem, head, scmp)
struct mphdr *mem_pool(bool cst)
{
struct mphdr *hdr = calloc(sizeof(struct mphdr), 1);
if (hdr) {
hdr->stat = cst;
2024-03-08 00:37:02 +00:00
}
return hdr;
}
2024-04-16 17:55:41 +00:00
struct elem *mem_get(struct mphdr *hdr, char *str, int len)
2024-03-08 00:37:02 +00:00
{
2024-04-16 17:55:41 +00:00
struct {
int len;
char *data;
} temp = { .len = len, .data = str };
2024-03-08 00:37:02 +00:00
2024-04-16 17:55:41 +00:00
return kavl_find(my, hdr->root, (struct elem *)&temp, 0);
2024-03-08 00:37:02 +00:00
}
2024-04-16 17:55:41 +00:00
struct elem *mem_add(struct mphdr *hdr, char *str, int len)
2024-03-08 00:37:02 +00:00
{
2024-05-08 17:15:57 +00:00
struct elem *v, *e = calloc(sizeof(struct elem), 1);
2024-04-16 17:55:41 +00:00
if (!e) {
return 0;
}
e->len = len;
if (!hdr->stat) {
e->data = malloc(len);
if (!e->data) {
free(e);
2024-03-08 00:37:02 +00:00
return 0;
}
2024-04-16 17:55:41 +00:00
memcpy(e->data, str, len);
2024-03-08 00:37:02 +00:00
}
2024-04-16 17:55:41 +00:00
else {
e->data = str;
2024-03-08 00:37:02 +00:00
}
2024-04-16 17:55:41 +00:00
v = kavl_insert(my, &hdr->root, e, 0);
if (e != v) {
if (!hdr->stat) {
free(e->data);
}
free(e);
2024-03-08 00:37:02 +00:00
}
2024-04-16 17:55:41 +00:00
return v;
2024-03-08 00:37:02 +00:00
}
2024-03-08 18:33:25 +00:00
2024-04-16 17:55:41 +00:00
void mem_delete(struct mphdr *hdr, char *str, int len)
2024-03-08 18:33:25 +00:00
{
2024-04-16 17:55:41 +00:00
struct {
int len;
char *data;
} temp = { .len = len, .data = str };
struct elem *e = kavl_erase(my, &hdr->root, (struct elem *)&temp, 0);
if (!e) {
2024-03-08 18:33:25 +00:00
return;
}
2024-04-16 17:55:41 +00:00
if (!hdr->stat) {
free(e->data);
e->data = 0;
2024-03-08 18:33:25 +00:00
}
2024-04-16 17:55:41 +00:00
free(e);
2024-03-08 18:33:25 +00:00
}
void mem_destroy(struct mphdr *hdr)
{
2024-04-16 17:55:41 +00:00
while (hdr->root) {
struct elem *e = kavl_erase_first(my, &hdr->root);
if (!e) {
2024-04-16 17:55:41 +00:00
break;
}
if (!hdr->stat && e->data) {
free(e->data);
}
2024-04-16 17:55:41 +00:00
e->data = 0;
free(e);
}
2024-03-26 20:47:01 +00:00
free(hdr);
2024-04-23 05:47:27 +00:00
}