Merge aicom-network-branch (without NDIS changes for now)
[reactos.git] / irc / ArchBlackmann / auto_vector.h
1 // auto_vector.h
2 // This file is (C) 2002-2004 Royce Mitchell III
3 // and released under the LGPL & BSD licenses
4
5 #ifndef AUTO_VECTOR_H
6 #define AUTO_VECTOR_H
7
8 #include <sys/types.h>
9 #include "verify.h"
10 #include "auto_ptr.h"
11
12 template<class T>
13 class auto_vector
14 {
15 public:
16 explicit auto_vector ( size_t capacity = 0 )
17 : _arr(0), _capacity(0), _end(0)
18 {
19 if ( capacity != 0 )
20 _arr = new auto_ptr<T>[capacity];
21 _capacity = capacity;
22 }
23
24 ~auto_vector()
25 {
26 delete []_arr;
27 }
28
29 size_t size() const
30 {
31 return _end;
32 }
33
34 const auto_ptr<T>& operator [] ( size_t i ) const
35 {
36 ASSERT ( i < _end );
37 return _arr[i];
38 }
39
40 auto_ptr<T>& operator [] ( size_t i )
41 {
42 ASSERT ( i < _end );
43 return _arr[i];
44 }
45
46 void assign ( size_t i, auto_ptr<T>& p )
47 {
48 ASSERT ( i < _end );
49 _arr[i] = p;
50 }
51
52 void assign_direct ( size_t i, T * p )
53 {
54 ASSERT ( i < _end );
55 reserve ( i + 1 );
56 _arr[i].reset ( p );
57 }
58
59 void push_back ( auto_ptr<T>& p )
60 {
61 reserve ( _end + 1 );
62 _arr[_end++] = p;
63 }
64
65 auto_ptr<T>& back()
66 {
67 ASSERT ( _end != 0 );
68 return _arr[_end-1];
69 }
70
71 void push_back ( T * p )
72 {
73 reserve ( _end + 1 );
74 auto_ptr<T> tmp(p);
75 _arr[_end++] = tmp;
76 //GCC is pedantic, this is an error.
77 //_arr[_end++] = auto_ptr<T>(p);
78 }
79
80 auto_ptr<T> pop_back()
81 {
82 ASSERT ( _end != 0 );
83 if ( !_end )
84 {
85 auto_ptr<T> tmp((T*)0);
86 return tmp;
87 //GCC, this is an error.
88 //return auto_ptr<T>(NULL);
89 }
90 return _arr[--_end];
91 }
92
93 void resize ( size_t newSize )
94 {
95 ASSERT ( newSize >= 0 );
96 reserve ( newSize ); // make sure we have at least this much room
97 _end = newSize;
98 }
99
100 void reserve ( size_t reqCapacity )
101 {
102 if ( reqCapacity <= _capacity )
103 return;
104 size_t newCapacity = 2 * _capacity;
105 if ( reqCapacity > newCapacity )
106 newCapacity = reqCapacity;
107 // allocate new array
108 auto_ptr<T> * arrNew = new auto_ptr<T> [newCapacity];
109 // transfer all entries
110 for ( size_t i = 0; i < _capacity; ++i )
111 arrNew[i] = _arr[i];
112 _capacity = newCapacity;
113 // free old memory
114 delete[] _arr;
115 // substitute new array for old array
116 _arr = arrNew;
117 }
118
119 void remove ( size_t off )
120 {
121 size_t last = _end-1;
122 if ( off == last )
123 resize ( last );
124 else if ( off < last )
125 {
126 auto_ptr<T> tmp ( pop_back().release() );
127 _arr[off] = tmp;
128 }
129 }
130
131 //typedef const_auto_iterator<T> const_iterator;
132 //const_iterator begin () const { return _arr; }
133 //const_iterator end () const { return _arr + _end; }
134
135 private:
136 auto_ptr<T> *_arr;
137 size_t _capacity;
138 size_t _end;
139 };
140
141 #endif//AUTO_VECTOR_H