Make text nodes store the string length

This commit is contained in:
Heath Mitchell 2023-03-03 13:25:41 +00:00
parent 12b8599370
commit e8d249d001
2 changed files with 11 additions and 8 deletions

View File

@ -30,8 +30,11 @@ struct TeX_Node
struct TeX_Node *next;
union {
/* Plain text content encoded as UTF-8 */
uint8_t *text;
/* Plain text content encoded as UTF-8 with length */
struct {
uint8_t *text;
size_t text_len;
};
/* Environment pointer */
struct TeX_Env *env;
/* Functional arguments */

View File

@ -21,8 +21,7 @@
enum cursorMoveResult TeX_node_cursor_action(struct TeX_Node *node, struct editContext * context, enum cursorAction action)
{
// Text
// TODO: Store the length of the text in the node
// That way we won't have to call strlen every time
// TODO: Make sure the editing works with UTF-8 (it probably doesn't as-is)
if (node->type == 0)
{
// If this isn't where the cursor is, continue the recursive search
@ -38,7 +37,7 @@ enum cursorMoveResult TeX_node_cursor_action(struct TeX_Node *node, struct editC
return SUCCESS;
}
else if (action == CURSOR_MOVE_RIGHT) {
if (context->offset >= strlen(node->text))
if (context->offset >= node->text_len)
return CURSOR_PAST_END;
context->offset++;
@ -100,10 +99,9 @@ enum cursorMoveResult TeX_node_cursor_enter(struct TeX_Node *node, struct editCo
// Text
if (node->type == 0)
{
int len = strlen(node->text);
context->elementIsText = true;
context->cursorText = node;
context->offset = action == CURSOR_MOVE_RIGHT ? 0 : len;
context->offset = action == CURSOR_MOVE_RIGHT ? 0 : node->text_len;
return SUCCESS;
}
// Regular nodes
@ -155,9 +153,11 @@ struct TeX_Node *TeX_node_text(char const *utf8)
if(!node) return NULL;
/* TODO: Don't use strdup(); convert from utf8 instead */
node->text = malloc(strlen(utf8) + 1);
size_t len = strlen(utf8);
node->text = malloc(len + 1);
if(!node->text) { free(node); return NULL; }
strcpy((void *)node->text, utf8);
node->text_len = len;
node->type = TEX_NODECLASS_TEXT;
return node;