Last active
April 13, 2018 05:27
-
-
Save HotelCalifornia/4475709aefdb5e3fec2c47396117c523 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#define ENONE -999 | |
typedef int Err; | |
// TODO: this isn't so much an optional type as it is a Result type, like in Rust. rename accordingly (e.g. Result->Value/Type; | |
// Option->Result) | |
typedef union { | |
int8_t i8; | |
int16_t i16; | |
int32_t i32; | |
int64_t i64; | |
uint8_t u8; | |
uint16_t u16; | |
uint32_t u32; | |
uint64_t u64; | |
float f; | |
void* v; | |
} Result; | |
typedef struct { | |
Result result; | |
Err error; | |
} Option; | |
int has_value(Option* o) { | |
return o->error == ENONE; | |
} | |
Err get_err_code(Option* o) { | |
return o->error; | |
} | |
Result get_result(Option* o) { | |
return o->result; | |
} | |
/** | |
* \brief foobar | |
* \return An Option<int32_t> containing result or error | |
*/ | |
Option foo() { | |
int i = 10; | |
Option o = { | |
.result = { .i32 = i }, | |
.error = ENONE, | |
}; | |
return o; | |
} | |
Option bar() { | |
Option o = { | |
.error = 69, // set to some meaningful, well-documented value | |
}; | |
return o; | |
} | |
int main() { | |
Option o = foo(); | |
printf("has value: %d\n", has_value(&o)); | |
if (has_value(&o)) { | |
printf("result = %d\n", get_result(&o).i32); | |
} else { | |
printf("error occurred! %d\n", get_err_code(&o)); | |
} | |
o = bar(); // reuse name | |
if (has_value(&o)) { | |
printf("result = %s\n", get_result(&o).str); | |
} else { | |
printf("error occurred! %d\n", get_err_code(&o)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment