cu
option.h File Reference

Datatype for wrapping pointer in a safer way. More...

#include <stdbool.h>

Go to the source code of this file.

Data Structures

struct  option_t
 option_t wraps a pointer und does checks whether it is null. More...
 

Functions

option_t option (void *data)
 Create a new option_t for given pointer. More...
 
void * unwrap (option_t *self)
 Unwrap the option_t and retrieve the underlying pointer. More...
 
void * expect (option_t *self, const char *msg)
 Unwraps the option_t and retrieve the underlying pointer. More...
 
void * unwrap_or (option_t *self, void *default_val)
 Unwraps the option_t and retrieve the underlying pointer. More...
 
bool is_some (option_t *self)
 Check if the underlying data contains a valid pointer. More...
 
bool is_none (option_t *self)
 Check if the underlying data is a invalid pointer. More...
 

Detailed Description

Datatype for wrapping pointer in a safer way.

Function Documentation

void* expect ( option_t self,
const char *  msg 
)

Unwraps the option_t and retrieve the underlying pointer.

In case of an error see unwrap(), the passed error msg is printed and abort is called.

int *data = malloc(20);
void *my_data = opt.expect(&opt, "Data was NULL");
Parameters
selfreference to the option
msgmessage to print to stderr
Returns
retrieve the underlying pointer
bool is_none ( option_t self)

Check if the underlying data is a invalid pointer.

option_t opt = option(NULL);
bool is = opt.is_none(&opt); // returns false
Parameters
selfreference to the option_t
Returns
Is false in case that the pointer passed is NULL
bool is_some ( option_t self)

Check if the underlying data contains a valid pointer.

int *data = malloc(20);
option_t opt = option(data);
bool is = opt.is_some(&opt); // with a high probability is 1
Parameters
selfreference to the option_t
Returns
true in case that the underlying pointer is not NULL
option_t option ( void *  data)

Create a new option_t for given pointer.

int *data = malloc(20);
option_t opt = option(data);
Parameters
dataexpects a pointer
Returns
returns a pointer struct which wraps the pointer
void* unwrap ( option_t self)

Unwrap the option_t and retrieve the underlying pointer.

In case that the underlying data is NULL, abort() is called.

int *data = malloc(20);
option_t opt = option(data);
void *my_data = opt.unwrap(&opt);
Parameters
selfreference to option
Returns
get the underlying data of the option
void* unwrap_or ( option_t self,
void *  default_val 
)

Unwraps the option_t and retrieve the underlying pointer.

int *data = malloc(20);
int default[20] = {};
option_t opt = option(data);
void *my_data = opt.unwrap_or(&opt, default);
Parameters
selfreference to the option_t
default_valdefault value to return
Returns
retrieve the underlying pointer