Last active
March 17, 2018 23:11
-
-
Save SebastianMestre/a972d876c7845d7ba48eb16cf7b06609 to your computer and use it in GitHub Desktop.
Generic data structures for the C language. Makes heavy use of the C preprocessor
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
#ifndef MESTRE_GENERIC_STACK | |
#define MESTRE_GENERIC_STACK | |
#include <stdlib.h> | |
#define stack(T) struct T ## Stack | |
#define newStack(T) T ## NewStack | |
#define popStack(T) T ## PopStack | |
#define pushStack(T) T ## PushStack | |
#define stackDef(T) \ | |
stack(T){\ | |
T data;\ | |
stack(T) *next;\ | |
};\ | |
stack(T) * newStack(T)(T value){\ | |
stack(T) *this = malloc(sizeof(stack(T)));\ | |
this->data = value;\ | |
this->next = NULL;\ | |
return this;\ | |
}\ | |
void pushStack(T)(stack(T) **thisp, T data){\ | |
stack(T) *this = *thisp;\ | |
stack(T) *next = malloc(sizeof(stack(T)));\ | |
next->data = data;\ | |
next->next = this;\ | |
*thisp = next;\ | |
}\ | |
void popStack(T)(stack(T) **thisp){\ | |
stack(T) *this = *thisp;\ | |
*thisp = this->next;\ | |
free(this);\ | |
} | |
#endif//MESTRE_GENERIC_STACK |
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
#ifndef MESTRE_GENERIC_VECTOR | |
#define MESTRE_GENERIC_VECTOR | |
#include <stdlib.h> | |
#define vector(T) struct T ## Vector | |
#define newVector(T) T ## NewVector | |
#define getVector(T) T ## GetVector | |
#define pushVector(T) T ## PushVector | |
#define extendVector(T) T ## ExtendVector | |
#define vectorDef(T) \ | |
vector(T){\ | |
T* data;\ | |
int size, index;\ | |
};\ | |
vector(T) newVector(T)(int length){\ | |
vector(T) this;\ | |
this.size = length;\ | |
this.index = 0;\ | |
this.data = malloc(length * sizeof(T));\ | |
if(!this.data)\ | |
exit(1);\ | |
return this;\ | |
}\ | |
T getVector(T)(vector(T)* this, int index){\ | |
return this->data[index];\ | |
}\ | |
void extendVector(T)(vector(T)* this, int extension){\ | |
this->size += extension;\ | |
this->data = realloc(this->data, this->size * sizeof(T));\ | |
if(!this->data)\ | |
exit(1);\ | |
}\ | |
void pushVector(T)(vector(T)* this, int value){\ | |
if(this->index == this->size)\ | |
extendVector(T)(this, this->size);\ | |
this->data[this->index++] = value;\ | |
} | |
#endif//MESTRE_GENERIC_VECTOR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment