string-builder: Ajoute un paquet pour construire des char*

main
Clément FRÉVILLE 2 years ago
parent cb6d978cad
commit 27eafc7b9c

@ -0,0 +1,24 @@
CC = gcc
CFLAGS = -Wall -Wextra
all: test
test: testBuilder
./testBuilder
testBuilder: build/builder.o build/testBuilder.o
$(CC) -o $@ $^
build/builder.o: src/builder.c src/builder.h | build
$(CC) $(CFLAGS) -c $< -o $@
build/testBuilder.o: test/testBuilder.c src/builder.h | build
$(CC) $(CFLAGS) -Isrc/ -c $< -o $@
build:
mkdir build
clean:
rm -rf testBuilder build
.PHONY: all test clean

@ -0,0 +1,5 @@
[package]
name = "static-string-builder"
version = "0.1.1"
description = "Global string builder"
license = "MIT"

@ -0,0 +1,42 @@
#include "builder.h"
#include <assert.h>
#include <string.h>
char tmp[TMP_CAP] = {};
size_t tmp_size = 0;
char *tmp_end(void) {
return tmp + tmp_size;
}
char *tmp_alloc(size_t size) {
assert(tmp_size + size <= TMP_CAP);
char *result = tmp_end();
tmp_size += size;
return result;
}
char *tmp_append_char(char c) {
assert(tmp_size < TMP_CAP);
tmp[tmp_size++] = c;
return tmp + tmp_size - 1;
}
char *tmp_append_sized(const char *buffer, size_t buffer_sz) {
char *result = tmp_alloc(buffer_sz);
return memcpy(result, buffer, buffer_sz);
}
char *tmp_append_cstr(const char *cstr) {
return tmp_append_sized(cstr, strlen(cstr));
}
void tmp_clean() {
tmp_size = 0;
}
void tmp_rewind(const char *end) {
tmp_size = end - tmp;
}

@ -0,0 +1,31 @@
#ifndef STATIC_STRING_BUILDER_H
#define STATIC_STRING_BUILDER_H
#include <stddef.h>
#ifndef TMP_CAP
#define TMP_CAP 1024
#endif
/**
* Get a pointer on the byte just after the last character of the buffer.
*
* @return A char pointer
*/
char *tmp_end(void);
/**
* Append a new byte at the end of the current string builder.
*
* @param c The character to add
* @return A pointer just before the character was added
*/
char *tmp_append_char(char c);
char *tmp_append_cstr(const char *cstr);
void tmp_clean();
void tmp_rewind(const char *end);
#endif // STATIC_STRING_BUILDER_H

@ -0,0 +1,35 @@
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "builder.h"
int main(void) {
char *result = tmp_end();
assert(*result == '\0');
tmp_append_char('a');
assert(strcmp(result, "a") == 0);
for (char c = 'b'; c <= 'z'; ++c) {
tmp_append_char(c);
}
char *end = tmp_append_char('\0');
assert(*end == '\0');
assert(strcmp(result, "abcdefghijklmnopqrstuvwxyz") == 0);
tmp_clean();
result = tmp_end();
tmp_append_cstr("Hello,");
char *comma = tmp_append_cstr(" world!");
tmp_append_char('\0');
assert(strcmp(comma, " world!") == 0);
assert(strcmp(result, "Hello, world!") == 0);
tmp_rewind(comma);
tmp_append_cstr(" the world!");
tmp_append_char('\0');
assert(strcmp(result, "Hello, the world!") == 0);
printf("Success!\n");
return 0;
}
Loading…
Cancel
Save