ccubes-cl/config.c

137 lines
2.3 KiB
C
Raw Normal View History

2025-03-20 19:32:25 +02:00
/*
* Copyright (c) 2012, Marius Barbu <msb@avengis.com>
* Copyright (c) 2013, Paul Irofti <paul@irofti.net>
*/
#include <stdio.h> /* sscanf/snprintf */
#include <string.h> /* stricmp */
#include <stdlib.h>
#include "tree.h"
#include "config.h"
#if _MSC_VER
#define snprintf _snprintf
#endif
struct ConfigMap {
char *name;
char *value;
RB_ENTRY(ConfigMap) entry;
};
int
cfg_cmp(struct ConfigMap *cfg1, struct ConfigMap *cfg2)
{
return (strcmp(cfg1->name, cfg2->name));
}
RB_HEAD(cfgtree, ConfigMap) cfg_head = RB_INITIALIZER(&cfg_head);
RB_GENERATE(cfgtree, ConfigMap, entry, cfg_cmp);
void
config_set_string(char *name, char *value)
{
struct ConfigMap *dup = NULL;
struct ConfigMap *cfg = malloc(sizeof *cfg);
if (cfg == NULL || name == NULL || value == NULL)
return;
cfg->name = strdup(name);
if (cfg->name == NULL)
return;
cfg->value = strdup(value);
if (cfg->value == NULL)
return;
if ((dup = RB_INSERT(cfgtree, &cfg_head, cfg))) {
dup->value = cfg->value;
free(cfg->name);
free(cfg);
}
}
void
config_set_int(char *name, int value)
{
char buff[20];
snprintf(buff, sizeof buff, "%d", value);
config_set_string(name, buff);
}
void
config_set_bool(char *name, int value)
{
char buff[20];
snprintf(buff, sizeof buff, "%d", value ? 1 : 0);
config_set_string(name, buff);
}
char*
config_get_string(char *name, char *def)
{
struct ConfigMap find, *found = NULL;
find.name = (char *)name;
found = RB_FIND(cfgtree, &cfg_head, &find);
if (found == NULL) {
return def;
}
return found->value;
}
int
config_get_int(char *name, int def)
{
int val = def;
struct ConfigMap find, *found = NULL;
find.name = (char *)name;
found = RB_FIND(cfgtree, &cfg_head, &find);
if (found == NULL) {
return def;
}
sscanf(found->value, "%i", &val);
return val;
}
int
config_get_bool(char *name, int def)
{
struct ConfigMap find, *found = NULL;
find.name = (char *)name;
found = RB_FIND(cfgtree, &cfg_head, &find);
if (found == NULL) {
return def;
}
if (strcmp(found->value, "0") == 0 ||
strcmp(found->value, "false") == 0) {
return 0;
}
return 1;
}
void
config_destroy()
{
struct ConfigMap *var, *nxt;
for (var = RB_MIN(cfgtree, &cfg_head); var != NULL; var = nxt) {
nxt = RB_NEXT(cfgtree, &cfg_head, var);
RB_REMOVE(cfgtree, &cfg_head, var);
free(var->name);
free(var->value);
free(var);
}
}