forked from ElektraInitiative/libelektra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_array.c
106 lines (97 loc) · 2.33 KB
/
table_array.c
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
97
98
99
100
101
102
103
104
105
106
/**
* @file table_array.c
*
* @brief Contains functionaly for handling table arrays on reading.
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "table_array.h"
#include <kdbhelper.h>
#include <stdio.h>
#include <string.h>
#include "utility.h"
static char * getChildFraction (const Key * parent, const Key * child);
TableArrayList * pushTableArray (TableArrayList * top, Key * key)
{
TableArrayList * ta = elektraCalloc (sizeof (TableArrayList));
ta->key = key;
keyIncRef (key);
if (top != NULL)
{
ta->keyStr = getChildFraction (top->key, key);
if (ta->keyStr == NULL)
{
return NULL;
}
}
if (ta->keyStr == NULL)
{
ta->keyStr = elektraStrDup (keyName (key));
}
ta->currIndex = 0;
ta->next = top;
return ta;
}
TableArrayList * popTableArray (TableArrayList * top)
{
TableArrayList * newTop = top->next;
keyDecRef (top->key);
keyDel (top->key);
elektraFree (top->keyStr);
elektraFree (top);
return newTop;
}
Key * buildTableArrayKeyName (const TableArrayList * ta)
{
if (ta->next == NULL || !keyIsBelow (ta->next->key, ta->key))
{
return keyAppendIndex (ta->currIndex, ta->key);
}
else
{
Key * key = buildTableArrayKeyName (ta->next);
keyAddName (key, ta->keyStr);
char * index = indexToArrayString (ta->currIndex);
keyAddBaseName (key, index);
elektraFree (index);
return key;
}
}
static char * getChildFraction (const Key * parent, const Key * child)
{
if (!keyIsBelow (parent, child))
{
return NULL;
}
else
{
Key * childDup = keyDup (child, KEY_CP_ALL);
size_t fracSize = 256;
char * fraction = elektraCalloc (sizeof (char) * fracSize);
if (fraction == NULL)
{
return NULL;
}
do
{
const char * baseName = keyBaseName (childDup);
if (elektraStrLen (fraction) + elektraStrLen (baseName) - 1 >= fracSize)
{
fracSize *= 2;
size_t oldLen = elektraStrLen (fraction);
if (elektraRealloc ((void **) &fraction, fracSize) < 0)
{
return NULL;
}
memset (fraction + oldLen, 0, fracSize - oldLen);
}
char * fracDup = elektraStrDup (fraction); // TODO: avoid allocation
snprintf (fraction, fracSize, "%s/%s", baseName, fracDup);
elektraFree (fracDup);
keyAddName (childDup, "..");
} while (keyCmp (parent, childDup) != 0);
fraction[elektraStrLen (fraction) - 2] = 0;
keyDel (childDup);
return fraction;
}
}