Last active
July 4, 2023 14:04
-
-
Save rzuf79/65f05087a611f11ebf2a3b91ea42609a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _JEVKO_H | |
#define _JEVKO_H | |
#include <stdio.h> | |
#include <string.h> | |
typedef struct { | |
char* name; | |
char* value; | |
} Jevko; | |
Jevko** Jevko_parse(char* string, int* jevkos_count) { | |
Jevko** out_jevkos; | |
char lex[256] = { 0 }; | |
int lexi = 0; | |
int i = 0; | |
int subjevko_depth = 0; | |
*jevkos_count = 0; | |
// determine how many jevkos are there | |
while (string[i] != 0) { | |
if (string[i] == '[') { | |
if (subjevko_depth == 0) { | |
(*jevkos_count) ++; | |
} | |
subjevko_depth ++; | |
} else if (string[i] == ']') { | |
if (subjevko_depth > 0) { | |
subjevko_depth --; | |
} else { | |
// whoops! | |
} | |
} | |
i++; | |
} | |
if (jevkos_count == 0) { | |
*jevkos_count = 1; | |
out_jevkos = malloc(sizeof(Jevko*)); | |
out_jevkos[0] = malloc(sizeof(Jevko*)); | |
out_jevkos[0]->name = NULL; | |
out_jevkos[0]->value = strdup(string); | |
return out_jevkos; | |
} | |
out_jevkos = malloc(sizeof(Jevko*) * (*jevkos_count)); | |
// parse them jevkos | |
i = 0; | |
subjevko_depth = 0; | |
int jevkoi = 0; | |
while (string[i] != 0) { | |
if (string[i] == '[') { | |
out_jevkos[jevkoi] = malloc(sizeof(Jevko*)); | |
if (strlen(lex) > 0) { | |
out_jevkos[jevkoi]->name = strdup(lex); | |
lex[0] = 0; | |
} | |
lexi = 0; | |
i ++; | |
while (string[i] != ']' || subjevko_depth > 0) { | |
if (string[i] == '[') { | |
subjevko_depth ++; | |
} else if (string[i] == ']') { | |
subjevko_depth --; | |
} | |
lex[lexi] = string[i]; | |
lexi ++; | |
i ++; | |
} | |
lex[lexi] = 0; | |
out_jevkos[jevkoi]->value = strdup(lex); | |
jevkoi ++; | |
} else if (string[i] == ' ' || string[i] == '\t' || string[i] == '\n') { | |
if (lexi > 0) { | |
lex[lexi] = 0; | |
lexi = 0; | |
} | |
} else { | |
lex[lexi] = string[i]; | |
lexi ++; | |
} | |
i ++; | |
} | |
return out_jevkos; | |
} | |
char* Jevko_get(Jevko** jevkos, int jevkos_count, const char* name) { | |
for (int i = 0; i < jevkos_count; ++i) { | |
if (strcmp(jevkos[i]->name, name) == 0) { | |
return jevkos[i]->value; | |
} | |
} | |
return NULL; | |
} | |
void Jevko_free(Jevko* jevko) { | |
if (jevko) { | |
if (jevko->name) { | |
free(jevko->name); | |
} | |
if (jevko->value) { | |
free(jevko->value); | |
} | |
free(jevko); | |
} | |
} | |
void Jevkos_free(Jevko** jevkos, int jevkos_count) { | |
for (int i = 0; i < jevkos_count; ++i) { | |
Jevko_free(jevkos[i]); | |
} | |
} | |
#endif // _JEVKO_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment