interpret/src/lorem.c

64 lines
1.6 KiB
C

/** @license 2023 Neil Edelman, distributed under the terms of the
[MIT License](https://opensource.org/licenses/MIT).
Global stable pool of temporary strings duplicated from substrings. Doesn't
support deletion, only growing.
@std C89 */
#include "lorem.h"
#include <assert.h>
#include <errno.h>
#define ARRAY_NAME block
#define ARRAY_TYPE char *
#include "array.h"
static struct {
size_t capacity, size; /* Lead block. */
struct block_array blocks;
} lorem;
const char *lorem_dup(const struct lorem sub) {
char *string;
size_t size;
if(!sub.sub) { errno = EDOM; return 0; } /* Null substring. */
if(sub.size == ~(size_t)0) { errno = ERANGE; return 0; } /* Unlikely. */
if((size = sub.size + 1) > lorem.capacity - lorem.size) {
size_t c0 = lorem.capacity < 8 ? 8 : lorem.capacity;
char *block = 0, **record = 0;
while(c0 < size) { /* Grow. */
size_t c1 = c0 + (c0 >> 1) + (c0 >> 3);
if(c0 >= c1) { c0 = ~(size_t)0; break; } /* Unlikely. */
c0 = c1;
}
if(!(block = malloc(c0))
|| !(record = block_array_new(&lorem.blocks))) { /* Error. */
free(block);
if(!errno) errno = ERANGE;
return 0;
}
*record = block;
lorem.capacity = c0;
lorem.size = 0;
/*printf("%s size %zu\n", orcify(block), c0);*/
}
assert(lorem.blocks.size);
string = lorem.blocks.data[lorem.blocks.size - 1] + lorem.size;
memcpy(string, sub.sub, sub.size);
string[sub.size] = '\0';
lorem.size += size;
return string;
}
void lorem_(void) {
size_t i;
for(i = 0; i < lorem.blocks.size; i++) {
char *block = lorem.blocks.data[i];
/*printf("free %s\n", orcify(block));*/
free(block);
}
lorem.capacity = lorem.size = 0;
block_array_(&lorem.blocks);
}