Skip to content

Instantly share code, notes, and snippets.

@flavio-fernandes
Created May 15, 2019 19:04
Show Gist options
  • Save flavio-fernandes/6cbda1537809f5bd097395fcefda6195 to your computer and use it in GitHub Desktop.
Save flavio-fernandes/6cbda1537809f5bd097395fcefda6195 to your computer and use it in GitHub Desktop.
pipeline code example
#include <assert.h>
#include <stdio.h>
typedef enum Input_type_t {
inputTypeInt,
inputTypeChar,
inputTypeMax // last
} InputType;
typedef struct Input_t {
union {
int i;
char c;
} v;
} Input;
// add one typedef for each supported type
typedef int (*intFunction)(int);
typedef char (*charFunction)(char);
typedef struct Callable_t {
void* function; // actual type depends on pipeline's input type
struct Callable_t* next;
} Callable;
typedef struct Pipeline_t {
const InputType inputType;
Input input; // initialized and used as accumulator
Callable* const callableHead;
} Pipeline;
void _processInt(Pipeline *p) {
Callable* c = p->callableHead;
while (c) {
// cast callable into the type we think it should be (fingers crossed! :))
intFunction funPtr = (intFunction) c->function;
p->input.v.i = (*funPtr)(p->input.v.i);
c = c->next;
}
}
void process(Pipeline *p) {
assert(p);
switch (p->inputType) {
case inputTypeInt:
_processInt(p);
break;
case inputTypeChar:
// fall thru...
default:
assert(NULL); // not implemented
break;
}
}
int multiplyByTwo(int i) {
return i * 2;
}
int subtractFive(int i) {
return i - 5;
}
int main(void) {
Callable c2 = { &subtractFive, NULL };
Callable c1 = { &multiplyByTwo, &c2 };
Input initial = { {.i=10} };
Pipeline p = {inputTypeInt, initial, &c1};
process(&p);
printf("The pipeline initial input is %d and its result is %d\n",
initial.v.i, p.input.v.i);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment