Skip to content

Instantly share code, notes, and snippets.

@velddev
Last active December 18, 2019 19:17
Show Gist options
  • Save velddev/3f0ca0c93bb2d9f8dc26cccb59549d94 to your computer and use it in GitHub Desktop.
Save velddev/3f0ca0c93bb2d9f8dc26cccb59549d94 to your computer and use it in GitHub Desktop.
C style weird unmaintainable string type???
#include <stdlib.h>
#include <stdio.h>
#define result(type) type ## Result
#define __decl_result(type) typedef struct type ## __result{ \
type *value; \
char* errorMsg; \
} type ## Result; \
\
type ## Result type ## Result_complete(type ## Result *value) { \
type ## Result r; \
r.value = value; \
r.errorMsg = 0; \
return r; \
}\
\
type ## Result type ## Result_fail(char* err) { \
\
type ## Result r; \
r.errorMsg = err;\
return r; \
}
typedef struct stringArray {
int size;
char* array;
} StringArray;
__decl_result(StringArray)
void init_StringArray(StringArray* array) {
for (int i = 0; i < array->size; i++) {
array->array[i] = (char)0;
}
}
result(StringArray) __new_StringArray(int size) {
StringArray *strArray = (StringArray*)malloc(sizeof(StringArray));
if (!strArray) {
return StringArrayResult_fail("could not allocate StringArray");
}
strArray->size = size;
strArray->array = (char*)malloc(sizeof(char) * size + 1);
if (!strArray->array) {
return StringArrayResult_fail("could not allocate array");
}
strArray->array[size] = '\0';
return StringArrayResult_complete(strArray);
}
result(StringArray) new_StringArray(int size) {
result(StringArray) strArray = __new_StringArray(size);
if (strArray.errorMsg) {
return strArray;
}
init_StringArray(strArray.value);
return strArray;
}
char* resize_StringArray(StringArray* array, int newSize) {
if (array->size >= newSize) {
return;
}
free(array->array);
free(array);
result(StringArray) newResult = __new_StringArray(newSize);
if (newResult.errorMsg) {
return newResult.errorMsg;
}
array = newResult.value;
return 0;
}
char* set_StringArray(StringArray* array, char* string) {
int size = strlen(string);
if (size > array->size) {
char* err = resize_StringArray(array, size);
if (err) {
return err;
}
}
int i = 0;
for (; i < size; i++) {
array->array[i] = string[i];
}
if (i < array->size) {
array->array[i] = '\0';
}
return 0;
}
void handleError(char* c) {
if (c) {
printf("ERR: %s", c);
exit(1);
}
}
int main()
{
result(StringArray) res_a = new_StringArray(4);
handleError(res_a.errorMsg);
StringArray* a = res_a.value;
printf("length : %d\n", a->size);
printf("content: %s\n", a->array);
char* err = set_StringArray(a, "hello world");
handleError(err);
printf("length : %d\n", a->size);
printf("content: %s\n", a->array);
err = set_StringArray(a, "hello");
handleError(err);
printf("length : %d\n", a->size);
printf("content: %s\n", a->array);
return 0;
}
@Nielsbishere
Copy link

No
But consider this:
yes.
No

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment