Annotation of embedaddon/iftop/vector.c, revision 1.1
1.1 ! misho 1: /*
! 2: * vector.c:
! 3: * simple vectors
! 4: *
! 5: * Copyright (c) 2001 Chris Lightfoot. All rights reserved.
! 6: *
! 7: */
! 8:
! 9: static const char rcsid[] = "$Id: vector.c,v 1.3 2003/11/07 02:16:41 pdw Exp $";
! 10:
! 11: #ifdef HAVE_CONFIG_H
! 12: /*include "configuration.h"*/
! 13: #endif /* HAVE_CONFIG_H */
! 14:
! 15: #include <stdlib.h>
! 16: #include <string.h>
! 17:
! 18: #include "vector.h"
! 19: #include "iftop.h"
! 20:
! 21: vector vector_new(void) {
! 22: vector v;
! 23:
! 24: v = xcalloc(1, sizeof *v);
! 25: if (!v) return NULL;
! 26:
! 27: v->ary = xcalloc(16, sizeof *v->ary);
! 28: v->n = 16;
! 29: v->n_used = 0;
! 30: return v;
! 31: }
! 32:
! 33: void vector_delete(vector v) {
! 34: xfree(v->ary);
! 35: xfree(v);
! 36: }
! 37:
! 38: void vector_delete_free(vector v) {
! 39: item *i;
! 40: vector_iterate(v, i) {
! 41: xfree(i->v);
! 42: }
! 43: xfree(v->ary);
! 44: xfree(v);
! 45: }
! 46:
! 47: void vector_push_back(vector v, const item t) {
! 48: if (v->n_used == v->n) vector_reallocate(v, v->n * 2);
! 49: v->ary[v->n_used++] = t;
! 50: }
! 51:
! 52: void vector_pop_back(vector v) {
! 53: if (v->n_used > 0) {
! 54: --v->n_used;
! 55: if (v->n_used < v->n / 2) vector_reallocate(v, v->n / 2);
! 56: }
! 57: }
! 58:
! 59: item vector_back(vector v) {
! 60: return v->ary[v->n_used - 1];
! 61: }
! 62:
! 63: item *vector_remove(vector v, item *t) {
! 64: if (t >= v->ary + v->n_used) return NULL;
! 65: if (t < v->ary + v->n_used - 1)
! 66: memmove(t, t + 1, (v->n_used - (t - v->ary)) * sizeof(item));
! 67: memset(v->ary + v->n_used--, 0, sizeof(item));
! 68: if (v->n_used < v->n / 2 && v->n > 16) {
! 69: size_t i = t - v->ary;
! 70: vector_reallocate(v, v->n / 2);
! 71: t = v->ary + i;
! 72: }
! 73: return t;
! 74: }
! 75:
! 76: void vector_reallocate(vector v, const size_t n) {
! 77: if (n < v->n_used || n <= 0) return;
! 78: v->ary = xrealloc(v->ary, n * sizeof(item));
! 79: memset(v->ary + v->n_used, 0, (v->n - v->n_used) * sizeof(item));
! 80: v->n = n;
! 81: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>