File: keyval.c

package info (click to toggle)
cmus 2.3.3-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,440 kB
  • ctags: 3,053
  • sloc: ansic: 25,337; sh: 1,111; makefile: 181; python: 26
file content (96 lines) | stat: -rw-r--r-- 1,801 bytes parent folder | download
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "debug.h"
#include "keyval.h"
#include "xmalloc.h"

#include <string.h>

struct keyval *keyvals_dup(const struct keyval *keyvals)
{
	struct keyval *c;
	int i;

	for (i = 0; keyvals[i].key; i++)
		; /* nothing */
	c = xnew(struct keyval, i + 1);
	for (i = 0; keyvals[i].key; i++) {
		c[i].key = xstrdup(keyvals[i].key);
		c[i].val = xstrdup(keyvals[i].val);
	}
	c[i].key = NULL;
	c[i].val = NULL;
	return c;
}

void keyvals_free(struct keyval *keyvals)
{
	int i;

	for (i = 0; keyvals[i].key; i++) {
		free(keyvals[i].key);
		free(keyvals[i].val);
	}
	free(keyvals);
}

const char *keyvals_get_val(const struct keyval *keyvals, const char *key)
{
	int i;

	for (i = 0; keyvals[i].key; i++) {
		if (strcasecmp(keyvals[i].key, key) == 0)
			return keyvals[i].val;
	}
	return NULL;
}

void keyvals_init(struct growing_keyvals *c, const struct keyval *keyvals)
{
	int i;

	BUG_ON(c->keyvals);

	for (i = 0; keyvals[i].key; i++)
		; /* nothing */

	c->keyvals = keyvals_dup(keyvals);
	c->alloc = i;
	c->count = i;
}

void keyvals_add(struct growing_keyvals *c, const char *key, char *val)
{
	int n = c->count + 1;

	if (n > c->alloc) {
		n = (n + 3) & ~3;
		c->keyvals = xrenew(struct keyval, c->keyvals, n);
		c->alloc = n;
	}

	c->keyvals[c->count].key = xstrdup(key);
	c->keyvals[c->count].val = val;
	c->count++;
}

const char *keyvals_get_val_growing(const struct growing_keyvals *c, const char *key)
{
	int i;

	for (i = 0; i < c->count; ++i)
		if (strcasecmp(c->keyvals[i].key, key) == 0)
			return c->keyvals[i].val;

	return NULL;
}

void keyvals_terminate(struct growing_keyvals *c)
{
	int alloc = c->count + 1;

	if (alloc > c->alloc) {
		c->keyvals = xrenew(struct keyval, c->keyvals, alloc);
		c->alloc = alloc;
	}
	c->keyvals[c->count].key = NULL;
	c->keyvals[c->count].val = NULL;
}