Result impl and example
This commit is contained in:
parent
6568820407
commit
79c2b417c2
16
main.c
16
main.c
|
@ -6,3 +6,19 @@ fn(main(), int) {
|
||||||
print("Hello, World!\n", a);
|
print("Hello, World!\n", a);
|
||||||
Ok();
|
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
23
rust.h
|
@ -1,6 +1,6 @@
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
#define fn(decl, type) type decl
|
#define fn(decl, type) type decl
|
||||||
#define let(decl, type) const type decl
|
#define let(decl, type) const type decl
|
||||||
|
@ -12,3 +12,24 @@
|
||||||
#define Err(); return 1
|
#define Err(); return 1
|
||||||
|
|
||||||
#define enum union
|
#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); \
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue