source: list.c @ 124aebc

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 124aebc was ef6e2d1, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
Refactoring list, to include a generic insert method
  • Property mode set to 100644
File size: 1.8 KB
Line 
1#include "owl.h"
2#include <stdlib.h>
3
4static const char fileIdent[] = "$Id$";
5
6#define INITSIZE 30
7#define GROWAT 2
8#define GROWBY 1.5
9
10int owl_list_create(owl_list *l)
11{
12  l->size=0;
13  l->list=(void **)owl_malloc(INITSIZE*sizeof(void *));
14  l->avail=INITSIZE;
15  if (l->list==NULL) return(-1);
16  return(0);
17}
18
19int owl_list_get_size(owl_list *l)
20{
21  return(l->size);
22}
23
24
25void owl_list_grow(owl_list *l, int n) /*noproto*/
26{
27  void *ptr;
28
29  if ((l->size+n) > (l->avail/GROWAT)) {
30    ptr=owl_realloc(l->list, l->avail*GROWBY*sizeof(void *));
31    if (ptr==NULL) abort();
32    l->list=ptr;
33    l->avail=l->avail*GROWBY;
34  }
35
36}
37
38void *owl_list_get_element(owl_list *l, int n)
39{
40  if (n>l->size-1) return(NULL);
41  return(l->list[n]);
42}
43
44int owl_list_insert_element(owl_list *l, int at, void *element)
45{
46  int i;
47  if(at < 0 || at > l->size) return -1;
48  owl_list_grow(l, 1);
49
50  for (i=l->size; i>at; i--) {
51    l->list[i]=l->list[i-1];
52  }
53
54  l->list[at] = element;
55  l->size++;
56  return(0);
57}
58
59int owl_list_append_element(owl_list *l, void *element)
60{
61  return owl_list_insert_element(l, l->size, element);
62}
63
64int owl_list_prepend_element(owl_list *l, void *element)
65{
66  return owl_list_insert_element(l, 0, element);
67}
68
69int owl_list_remove_element(owl_list *l, int n)
70{
71  int i;
72
73  if (n>l->size-1) return(-1);
74  for (i=n; i<l->size-1; i++) {
75    l->list[i]=l->list[i+1];
76  }
77  l->size--;
78  return(0);
79}
80
81/* todo: might leak memory */
82int owl_list_replace_element(owl_list *l, int n, void *element)
83{
84  if (n>l->size-1) return(-1);
85
86  l->list[n]=element;
87  return(0);
88}
89
90void owl_list_free_all(owl_list *l, void (*elefree)(void *))
91{
92  int i;
93
94  for (i=0; i<l->size; i++) {
95    (elefree)(l->list[i]);
96  }
97  owl_free(l->list);
98}
99
100void owl_list_free_simple(owl_list *l)
101{
102  if (l->list) owl_free(l->list);
103}
Note: See TracBrowser for help on using the repository browser.