Home | History | Annotate | Download | only in conntrack
      1 /*
      2  * (C) 2005-2011 by Pablo Neira Ayuso <pablo (at) netfilter.org>
      3  *
      4  * This program is free software; you can redistribute it and/or modify it
      5  * under the terms of the GNU General Public License as published by
      6  * the Free Software Foundation; either version 2 of the License, or
      7  * (at your option) any later version.
      8  */
      9 
     10 #include <stdio.h>
     11 #include <stdlib.h>
     12 #include <string.h>
     13 #include <errno.h>
     14 
     15 #include "internal/stack.h"
     16 
     17 struct stack {
     18 	int num_elems;
     19 	int max_elems;
     20 	size_t elem_size;
     21 	char *data;
     22 };
     23 
     24 struct stack *stack_create(size_t elem_size, int max_elems)
     25 {
     26 	struct stack *s;
     27 
     28 	s = calloc(sizeof(struct stack), 1);
     29 	if (s == NULL)
     30 		return NULL;
     31 
     32 	s->data = calloc(elem_size * max_elems, 1);
     33 	if (s->data == NULL) {
     34 		free(s);
     35 		return NULL;
     36 	}
     37 	s->elem_size = elem_size;
     38 	s->max_elems = max_elems;
     39 
     40 	return s;
     41 }
     42 
     43 void stack_destroy(struct stack *s)
     44 {
     45 	free(s->data);
     46 	free(s);
     47 }
     48 
     49 int stack_push(struct stack *s, void *data)
     50 {
     51 	if (s->num_elems >= s->max_elems) {
     52 		errno = ENOSPC;
     53 		return -1;
     54 	}
     55 	memcpy(s->data + (s->elem_size * s->num_elems), data, s->elem_size);
     56 	s->num_elems++;
     57 	return 0;
     58 }
     59 
     60 int stack_pop(struct stack *s, void *data)
     61 {
     62 	if (s->num_elems <= 0) {
     63 		errno = EINVAL;
     64 		return -1;
     65 	}
     66 	s->num_elems--;
     67 	memcpy(data, s->data + (s->elem_size * s->num_elems), s->elem_size);
     68 	return 0;
     69 }
     70