source: golgotha/src/i4/memory/fixed_array.hh

Last change on this file was 80, checked in by Sam Hocevar, 12 years ago
  • Adding the Golgotha source code. Not sure what's going to be interesting in there, but since it's all public domain, there's certainly stuff to pick up.
File size: 2.3 KB
Line 
1/********************************************************************** <BR>
2  This file is part of Crack dot Com's free source code release of
3  Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for
4  information about compiling & licensing issues visit this URL</a>
5  <PRE> If that doesn't help, contact Jonathan Clark at
6  golgotha_source@usa.net (Subject should have "GOLG" in it)
7***********************************************************************/
8
9#ifndef I4_FIXED_ARRAY_HH
10#define I4_FIXED_ARRAY_HH
11
12// this template class manages an array of object
13// it automaically expands when add() is called and not enough elements are
14// available.  It also has an array reference operator allowing for transparent
15// range checking.
16
17#include "error/error.hh"
18#include "memory/malloc.hh"
19#include "search.hh"
20#include <stdlib.h>
21
22template <class T>
23class i4_fixed_array
24{
25protected:
26  T *entry;
27  int entries;
28public:
29
30  int size() const { return entries; }
31  T& operator[](int i) const
32  {
33    I4_ASSERT(i>=0 && i<entries, "i4_array::bad array reference");
34    return entry[i];
35  }   
36
37  T& operator()(int i) const
38  {
39    I4_ASSERT(i>=0 && i<entries, "i4_array::bad array reference");
40    return entry[i];
41  }   
42
43  void resize(int new_size)
44  {
45    entry = (T*)i4_realloc(entry, sizeof(T) * new_size,"grow array");
46    if (new_size)
47      I4_ASSERT(entry, "i4_array::can't allocate entries");
48
49    entries=new_size;
50  }
51
52  i4_fixed_array(int entries=0) : entries(entries)
53  {
54    entry=0;
55    if (entries)
56      resize(entries);
57  }
58
59  void uninit()     // frees memory (use clear just to reset)
60  {
61    if (entry)
62      i4_free(entry);
63    entry=0;
64    entries=0;
65  }
66 
67  ~i4_fixed_array()
68  {
69    uninit();
70  }
71   
72
73  void sort(int (*compar)(const T *, const T *))
74  {
75    typedef int (*compare_type)(const void *x, const void *y);
76    qsort(entry, size(), sizeof(T), (compare_type)compar);
77  }
78
79  int binary_search(const T *find, int (*compar)(const T* a, const T* b))
80  {
81    if (size()==0) return -1;
82
83    w32 res;
84
85    if (i4_base_bsearch(find, res, entry, sizeof(T), (w32)size(),
86                        (i4_bsearch_compare_function_type)compar))
87      return res;
88    else
89      return -1;                   
90  }
91
92};
93
94#endif
Note: See TracBrowser for help on using the repository browser.