From 96427d927477e5b6327ecb479d9722ca3ed5b571 Mon Sep 17 00:00:00 2001 From: Ben Winston Date: Thu, 9 May 2024 21:18:49 -0400 Subject: refactor: parse string in its own function --- booki.c | 72 ++++++++++++++++++++++++++++++++--------------------------------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/booki.c b/booki.c index 060a4af..fd2f212 100644 --- a/booki.c +++ b/booki.c @@ -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 -- cgit v1.2.3