stack.h
#ifndef __STACK_H__
#define __STACK_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C"{
#endif
struct validator
{
bool (*const vali) (struct validator *p_this,int value);
void *const p_data;
}validator;
struct range
{
int min;
int max;
}range;
struct
{
int previous_value;
}previous;
struct stack
{
int top;
const size_t size;
struct validator * const p_validator;
int *p_buf;
}stack;
#ifdef __cplusplus
}
#endif
#endif
stack.c
#include "stack.h"
static int stack_empty(struct stack *p_this)
{
return p_this->top == 0;
}
static int stack_full(struct stack *p_this)
{
return p_this->top == p_this->size;
}
static int validate_range(struct validator *p_this,int value)
{
if(!p_this)
return -1;
struct range *temp = (struct range *) p_this->p_data;
return (temp->min < value && temp->max > value);
}
int validate(struct validator *p_this,int value)
{
if(!p_this)
return 0;
return p_this->vali(p_this,value);
}
int pop(struct stack *p_this,int *value)
{
if(!p_this || stack_empty(p_this))
return -1;
p_this->top--;
*value = p_this->p_buf[p_this->top];
return 0;
}
int push(struct stack *p_this,int value)
{
if(stack_full(p_this) || !validate(p_this->p_validator,value))
return -1;
p_this->p_buf[p_this->top] = value;
p_this->top++;
return 0;
}
int main(int argc,char *argv[])
{
int buff[16];
struct range a = {
.min = 10,
.max = 100
};
struct validator b = {
.p_data = (void *)&a,
.vali = validate_range,
};
struct stack c = {
.top = 0,
.size = 16,
.p_validator = &b,
.p_buf = buff,
};
push(&c,12);
int d;
pop(&c,&d);
printf("%d\n",d);
return 0;
}
Makefile
src=stack.c
obj=$(src:.o=.c)
target=stack
all:$(target)
$(target):$(obj)
gcc $(obj) -o $@ -std=c99
%.o : %.c
gcc -c $< -O $@ -std=c99
clean:
rm -af $(target) $(obj)