Result impl and example

This commit is contained in:
Able 2021-11-04 22:58:40 -05:00
parent 6568820407
commit 79c2b417c2
2 changed files with 38 additions and 1 deletions

16
main.c
View file

@ -6,3 +6,19 @@ fn(main(), int) {
print("Hello, World!\n", a);
Ok();
}
typedef const char *ErrString;
typedef void *MemHandle;
Result_impl(MemHandle, ErrString)
Result_unwrap_impl(MemHandle, ErrString)
fn (gimmy_memory(size_t n_bytes), Result(MemHandle, ErrString)){
Result(MemHandle, ErrString) possible =
{.is_valid = true, .data = malloc(n_bytes)};
if (!possible.data)
{
possible.is_valid = false;
possible.err = "memory allocation failure";
}
return possible;
}

23
rust.h
View file

@ -1,6 +1,6 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define fn(decl, type) type decl
#define let(decl, type) const type decl
@ -12,3 +12,24 @@
#define Err(); return 1
#define enum union
// Rust like return impl
#define Result_impl(T, E) \
typedef struct { \
bool is_valid; \
union { \
T data; \
E err; \
}; \
} Result_##T##_##E;
#define Result(T, E) Result_##T##_##E
#define Result_unwrap_impl(T, E) \
T Result_##T##_unwrap (Result(T, E) result) { \
if (result.is_valid) \
return result.data; \
\
fprintf(stderr, "%s\n", result.err); \
exit(1); \
}