arraylist.c 2.22 KB
Newer Older
Andrei Paskevich's avatar
Andrei Paskevich committed
1
2
3
4
5
6
7
8
9
10
11
/********************************************************************/
/*                                                                  */
/*  The Why3 Verification Platform   /   The Why3 Development Team  */
/*  Copyright 2010-2016   --   INRIA - CNRS - Paris-Sud University  */
/*                                                                  */
/*  This software is distributed under the terms of the GNU Lesser  */
/*  General Public License version 2.1, with the special exception  */
/*  on linking described in file LICENSE.                           */
/*                                                                  */
/********************************************************************/

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <assert.h>
#include <stdlib.h>
#include "arraylist.h"

#define INVALID_INDEX (-1)

int list_lookup_index(plist l, int key);
void list_resize(plist l);

plist init_list(int capacity) {
  plist result;
  result = (plist) malloc (sizeof(t_list));
  result->capacity = capacity;
  result->len = 0;
  result->key = (int*) malloc(sizeof(int) * capacity);
  result->data = (void**) malloc(sizeof(void*) * capacity);
  return result;
}

bool list_is_empty(plist l) {
  return (l->len == 0);
}

int list_lookup_index(plist l, int key) {
  int i;
  for (i = 0; i < l->len; i++) {
    if (l->key[i] == key) {
       return i;
    }
  }
  return INVALID_INDEX;
}

void* list_lookup(plist l, int key) {
  int i = list_lookup_index(l, key);
  if (i == INVALID_INDEX) {
    return NULL;
  } else {
    return l->data[i];
  }
}

void list_remove(plist l, int key) {
  int i = list_lookup_index(l, key);
  if (i != INVALID_INDEX) {
    assert (!list_is_empty(l));
    l->len--;
    l->key[i] = l->key[l->len];
    l->data[i] = l->data[l->len];
  }
}

void free_list(plist l) {
  assert (list_is_empty(l));
  free(l->data);
  free(l->key);
  free(l);
}

void list_resize(plist l) {
  int newcap = l->capacity * 2;
  l->capacity = newcap;
  l->key = (int*) realloc(l->key, sizeof(int) * newcap);
  l->data = (void**) realloc(l->data, sizeof(void*) * newcap);
}

void list_append(plist l, int key, void* elt) {
  if (l->len == l->capacity) {
     list_resize(l);
  }
  l->key[l->len] = key;
  l->data[l->len] = elt;
  l->len++;
}

int list_length(plist l) {
  return l->len;
}