From 7f608c00135b2dc94ee501d940d8ba8740a74842 Mon Sep 17 00:00:00 2001 From: SuperNovaa41 Date: Thu, 16 Jan 2025 09:11:52 -0500 Subject: [PATCH] cleans up the add row code a bit --- src/include/term.h | 5 +++++ src/term.c | 23 ++++++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/include/term.h b/src/include/term.h index d16740b..507853d 100644 --- a/src/include/term.h +++ b/src/include/term.h @@ -12,6 +12,9 @@ typedef enum { typedef struct { char* line; size_t len; + + char* render; + size_t r_len; } row_t; typedef struct { @@ -109,6 +112,8 @@ void screen_buffer_free(screen_buffer_t* buf); */ void free_editor_row(void); +void editor_render_row(row_t* row); + void editor_add_row(const char* line, size_t len); #endif diff --git a/src/term.c b/src/term.c index 7fdf349..9de2228 100644 --- a/src/term.c +++ b/src/term.c @@ -164,6 +164,23 @@ void free_editor_row(void) free(editor.rows); } +void editor_render_row(row_t* row) +{ + if (row->render != NULL) // if the row is malloc'd we want to delete it + free(row->render); + row->render = malloc(sizeof(char) * row->len); +} + +// small helper function to initialize a row +void create_row(row_t* row, size_t len) +{ + row->len = len; + row->line = malloc(sizeof(char) * (len + 1)); + + row->render = NULL; + row->r_len = 0; +} + void editor_add_row(const char* line, size_t len) { // Need to add space for another row @@ -171,11 +188,11 @@ void editor_add_row(const char* line, size_t len) // Set len and malloc space for the incoming line +1 for \0 size_t idx = editor.num_rows; - editor.rows[idx].len = len; - editor.rows[idx].line = malloc(sizeof(char) * (len + 1)); + + create_row(&editor.rows[idx], len); memcpy(editor.rows[idx].line, line, len); editor.rows[idx].line[len] = '\0'; // need to null terminate it - + editor.num_rows++; }