byedpi/mpool.c

102 lines
1.8 KiB
C
Raw Normal View History

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