aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNicholas Johnson <nick@nicksphere.ch>2022-01-18 00:00:00 +0000
committerNicholas Johnson <nick@nicksphere.ch>2022-01-18 00:00:00 +0000
commit1dfb40ad3eac92bf27936f4862d5a3e5b759eba392af99a325fe6d8bafd70cc8 (patch)
tree98ba096192e9c816f0257ed6e0826ec39249850638d5b7528a197766c37d3fbc
parent5061c75c11817a44f53084785da02a7ba5afa6bab35c45d7a3fc380510570883 (diff)
Replace pointer arithmetic in escape_and_add_tags with strcpy() and add documentation
-rw-r--r--src/gemini2html.c28
1 files changed, 18 insertions, 10 deletions
diff --git a/src/gemini2html.c b/src/gemini2html.c
index bbc5788..827f1dc 100644
--- a/src/gemini2html.c
+++ b/src/gemini2html.c
@@ -90,28 +90,36 @@ void skip_non_whitespace(const char* str, size_t* pos) {
while (str[*pos] != '\0' && !(str[*pos] == ' ' || str[*pos] == '\t')) (*pos)++;
}
-char* escape_and_add_tags(const char* opening_tag, const char* unescaped, const char* closing_tag, const size_t unescaped_size, const bool add_newline) {
+char* escape_and_add_tags(const char* opening_tag, const char* unescaped, const char* closing_tag, const size_t unescaped_size, const bool append_newline) {
char* escaped = escape_text(unescaped, unescaped_size);
+ size_t opening_tag_len = strlen(opening_tag);
size_t escaped_len = strlen(escaped);
- char* escaped_with_tags = malloc(strlen(opening_tag) + escaped_len + strlen(closing_tag) + 1);
+ size_t closing_tag_len = strlen(closing_tag);
+
+ char* escaped_with_tags = malloc(opening_tag_len + escaped_len + closing_tag_len + 1);
size_t index = 0;
- // write opening tag
- for (size_t i = 0; i < strlen(opening_tag); i++) escaped_with_tags[index++] = opening_tag[i];
+ /* append opening tag */
+ strncpy(escaped_with_tags + index, opening_tag, opening_tag_len);
+ index += opening_tag_len;
- // write innerText
- for (size_t i = 0; i < escaped_len - 1; i++) escaped_with_tags[index++] = escaped[i];
+ /* append escaped text without newline at the end, if one exists */
+ strncpy(escaped_with_tags + index, escaped, escaped_len - 1);
+ index += escaped_len - 1;
bool is_newline = escaped[escaped_len - 1] == '\n';
if (!is_newline) escaped_with_tags[index++] = escaped[escaped_len - 1];
- // free escaped HTML memory
+ /* escaped string is no longer needed, so free it */
free(escaped);
escaped = NULL;
- // write closing tag
- for (size_t i = 0; i < strlen(closing_tag); i++) escaped_with_tags[index++] = closing_tag[i];
- if (add_newline) escaped_with_tags[index++] = '\n';
+ /* append closing tag */
+ strncpy(escaped_with_tags + index, closing_tag, closing_tag_len);
+ index += closing_tag_len;
+
+ /* append newline if caller wants one */
+ if (append_newline) escaped_with_tags[index++] = '\n';
escaped_with_tags[index] = '\0';
return escaped_with_tags;