Created
January 5, 2024 20:32
-
-
Save th3terrorist/e2d19aa63ce31baeffa279512ca242a7 to your computer and use it in GitHub Desktop.
test at a simple option type
This file contains hidden or 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 <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
typedef bool b8; | |
typedef unsigned int u32; | |
struct _None {}; | |
#define None (_None{}); | |
template<typename T> | |
struct Option { | |
private: | |
T value; | |
b8 _is_none = true; | |
public: | |
Option(const _None &_) : _is_none(true) {}; | |
Option(const _None &&_) : _is_none(true) {}; | |
Option(const T &&some) : _is_none(false), value(some) {}; | |
Option(const T &some) : _is_none(false), value(some) {}; | |
void operator=(const _None& _) { _is_none = true; }; | |
void operator=(const T& some) { value = some; _is_none = false; }; | |
auto is_none() const -> b8 { return _is_none; }; | |
auto is_some() const -> b8 { return !_is_none; }; | |
auto unwrap() const -> T { return _is_none ? (fprintf(stderr, "OPTION_ERR: cannot call unwrap() on None Option"), exit(1), value) : value; }; | |
}; | |
template<typename T> | |
auto Some(T some) -> Option<T> { return Option<T>(some); } | |
Option<char *> return_good(b8 should_go_ok) { | |
if (should_go_ok) { | |
char *buf = (char*)malloc(sizeof(char) * 32); | |
strcpy(buf, "Hello, World!"); | |
return Some(buf); | |
} | |
return None; | |
} | |
int main( void ) { | |
Option<char *> value = return_good(true); | |
if (value.is_some()) { | |
char *some_str = value.unwrap(); | |
printf("%s\n", some_str); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment