treebird/src/string_helpers.c
nekobit c8e3f5d70f Incomplete loop fix
FossilOrigin-Name: 1fb69b8c5ce57d2120cc3e80d08e29a0de27d0f8cc6d4fa96863c1b7fe0cd002
2022-06-01 06:11:50 +00:00

72 lines
2.1 KiB
C

/*
* Treebird - Lightweight frontend for Pleroma
* Copyright (C) 2022 Nekobit
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <fcgi_stdio.h>
#include <string.h>
#include <stdlib.h>
#include "string_helpers.h"
#include "easprintf.h"
char* construct_func_strings(char* (*func)(void*, size_t, size_t*),
void* strings,
size_t strings_len,
size_t* ret_size)
{
char* res_html, *result = NULL;
size_t curr_parse_size = 0, last_parse_size, parse_size;
if (strings_len <= 0) return NULL;
for (size_t i = 0; i < strings_len; ++i)
{
res_html = func(strings, i, &parse_size);
// Don't bother if it returns null
// Null is equivalent to ""
if (!res_html) continue;
if (parse_size == -1) /* Malloc error */
{
if (result) free(result);
return NULL;
}
last_parse_size = curr_parse_size;
curr_parse_size += parse_size;
result = realloc(result, curr_parse_size + 1);
if (result == NULL)
{
perror("malloc");
free(res_html);
return NULL;
}
// Copy res_html to result in correct position
strncpy(result + last_parse_size, res_html, parse_size);
// Cleanup
free(res_html);
}
if (result)
result[curr_parse_size] = '\0';
if (ret_size) *ret_size = curr_parse_size;
return result;
}