source: list.c @ 93ee554

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