aboutsummaryrefslogtreecommitdiff
path: root/src/util.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/util.c')
-rw-r--r--src/util.c76
1 files changed, 47 insertions, 29 deletions
diff --git a/src/util.c b/src/util.c
index 0a2ade8..805d397 100644
--- a/src/util.c
+++ b/src/util.c
@@ -6,18 +6,6 @@
#include "util.h"
#include "any_log.h"
-void pair_copy(pair_t *copy, const pair_t *pair)
-{
- copy->key = strcopy(pair->key);
- copy->value = strcopy(pair->value);
-}
-
-void pair_free(pair_t *pair)
-{
- free(pair->key);
- free(pair->value);
-}
-
char *color_to_string(color_t *color)
{
unsigned int r = color->r * 255,
@@ -127,26 +115,56 @@ size_t strprefix(const char *string, const char *prefix)
return i;
}
-size_t strcount(const char *string, const char *subs[])
+// FIXME: Slow and inefficient
+char *strformat(const char *string, char delim, const char **keys, const char **values)
{
- size_t count = 0;
- for (int i = 0; string[i] != '\0'; ) {
-next:
- for (int j = 0; subs[j] != NULL; j++) {
- size_t pl = strprefix(string + i, subs[j]);
- if (pl) {
- i += pl;
- count++;
- goto next;
+ size_t length = strlen(string);
+ size_t size = length;
+ size_t n = 0;
+ char *buffer = malloc(size);
+
+ for (size_t i = 0; i < length; i++) {
+ if (string[i] == delim && i + 2 < length && string[i + 1] == '{') {
+ bool found = false;
+ size_t j = i + 2;
+ for ( ; j < length; j++) {
+ if (string[j] == '}') {
+ found = true;
+ break;
+ }
}
+
+ if (found) {
+ for (int k = 0; keys[k] != NULL; k++) {
+ if (!strncmp(string + i + 2, keys[k], j - i - 2)) {
+
+ size_t vl = strlen(values[k]);
+ while (n + vl >= size) {
+ size *= 1.5;
+ buffer = realloc(buffer, size);
+ if (buffer == NULL)
+ return NULL;
+ }
+
+ memcpy(buffer + n, values[k], vl);
+ n += vl;
+ i = j;
+ goto next;
+ }
+ }
+ }
+ }
+
+ if (n + 1 >= size) {
+ size *= 1.5;
+ buffer = realloc(buffer, size);
+ if (buffer == NULL)
+ return NULL;
}
- ++i;
+ buffer[n++] = string[i];
+next:
}
- return count;
-}
-char *strformat(const char *string, const char *keys[], const char *values[])
-{
- // TODO
- return NULL;
+ buffer[n] = '\0';
+ return buffer;
}