Skip to content

Instantly share code, notes, and snippets.

@nakst
Created May 20, 2021 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakst/3f237316a0944de1bda830a9d81bb995 to your computer and use it in GitHub Desktop.
Save nakst/3f237316a0944de1bda830a9d81bb995 to your computer and use it in GitHub Desktop.
ini parser
struct INIState {
char *buffer, *section, *key, *value;
size_t bytes, sectionBytes, keyBytes, valueBytes;
};
bool INIParse(INIState *s) {
#define INI_READ(destination, counter, c1, c2) \
s->destination = s->buffer, s->counter = 0; \
while (s->bytes && *s->buffer != c1 && *s->buffer != c2) s->counter++, s->buffer++, s->bytes--; \
if (s->bytes && *s->buffer == c1) s->buffer++, s->bytes--;
while (s->bytes) {
char c = *s->buffer;
if (c == ' ' || c == '\n' || c == '\r') {
s->buffer++, s->bytes--;
continue;
} else if (c == ';') {
s->valueBytes = 0;
INI_READ(key, keyBytes, '\n', 0);
} else if (c == '[') {
s->keyBytes = s->valueBytes = 0;
s->buffer++, s->bytes--;
INI_READ(section, sectionBytes, ']', 0);
} else {
INI_READ(key, keyBytes, '=', '\n');
INI_READ(value, valueBytes, '\n', 0);
}
// Optional! Zero terminate the output strings.
if (s->sectionBytes) s->section[s->sectionBytes] = 0; else s->section = &emptyS
if (s->keyBytes) s->key[s->keyBytes] = 0; else s->key = &emptyString;
if (s->valueBytes) s->value[s->valueBytes] = 0; else s->value = &emptyString;
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment