diff options
| author | Ben Winston | 2024-05-09 21:18:49 -0400 |
|---|---|---|
| committer | Ben Winston | 2024-05-09 21:18:49 -0400 |
| commit | 96427d927477e5b6327ecb479d9722ca3ed5b571 (patch) | |
| tree | 876eaea22233e9bcd04fb7654290b0d6b31e110f | |
| parent | f7e1f546e6252495ccf67921067db22a5df01c63 (diff) | |
refactor: parse string in its own function
| -rw-r--r-- | booki.c | 72 |
1 files changed, 35 insertions, 37 deletions
@@ -60,11 +60,41 @@ const char* get_last_word(const char* str) { return 0; } +struct es parse_string(char* current_pos, char** new_pos) { + // TODO handle failure + + char c; + char* value; + + // leading spaces + while ((c = *current_pos) != '"') { + current_pos++; + } + + // go past the quote and set the position of the start of value + current_pos++; + value = current_pos; + + // until the next quote + while ((c = *current_pos) != '"') { + current_pos++; + } + + struct es output; + output.len = current_pos - value; + output.ptr = value; + + // update position + *new_pos = current_pos; + + return output; +} + struct Book parse_book(char* current_pos) { struct Book book = new_book(); char* attr; - char* value; char c = *current_pos; + char* new_pos; // loop until we hit the extra newline while (c != '\n') { // we start at the beginning of a line @@ -75,45 +105,13 @@ struct Book parse_book(char* current_pos) { // attr should be the name of the attribute, with (possibly) trailing spaces if (strncmp(attr, "title", 5) == 0) { - // leading spaces - while ((c = *current_pos) != '"') { - current_pos++; - } - - // go past the quote and set the position of the start of value - current_pos++; - value = current_pos; - - // until the next quote - while ((c = *current_pos) != '"') { - current_pos++; - } - - // set the attribute - struct es title; - title.len = current_pos - value; - title.ptr = value; + struct es title = parse_string(current_pos, &new_pos); book.title = title; + current_pos = new_pos; } else if (strncmp(attr, "author", 6) == 0) { - // leading spaces - while ((c = *current_pos) != '"') { - current_pos++; - } - - // go past the quote and set the position of the start of value - current_pos++; - value = current_pos; - - // until the next quote - while ((c = *current_pos) != '"') { - current_pos++; - } - - // set the attribute - struct es author; - author.len = current_pos - value; - author.ptr = value; + struct es author = parse_string(current_pos, &new_pos); book.author = author; + current_pos = new_pos; } // go to (and then past) the newline |
