MongoDB  2.7.0
array.h
1 // array.h
2 
3 /*
4  * Copyright 2010 10gen Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 namespace mongo {
20 
21  /*
22  * simple array class that does no allocations
23  * same api as vector
24  * fixed buffer, so once capacity is exceeded, will assert
25  * meant to be-reused with clear()
26  */
27  template<typename T>
28  class FastArray {
29  public:
30  FastArray( int capacity=10000 )
31  : _capacity( capacity ) , _size(0) , _end(this,capacity) {
32  _data = new T[capacity];
33  }
34 
35  ~FastArray() {
36  delete[] _data;
37  }
38 
39  void clear() {
40  _size = 0;
41  }
42 
43  T& operator[]( int x ) {
44  verify( x >= 0 && x < _capacity );
45  return _data[x];
46  }
47 
48  T& getNext() {
49  return _data[_size++];
50  }
51 
52  void push_back( const T& t ) {
53  verify( _size < _capacity );
54  _data[_size++] = t;
55  }
56 
57  void sort( int (*comp)(const void *, const void *) ) {
58  qsort( _data , _size , sizeof(T) , comp );
59  }
60 
61  int size() {
62  return _size;
63  }
64 
65  bool hasSpace() {
66  return _size < _capacity;
67  }
68  class iterator {
69  public:
70  iterator() {
71  _it = 0;
72  _pos = 0;
73  }
74 
75  iterator( FastArray * it , int pos=0 ) {
76  _it = it;
77  _pos = pos;
78  }
79 
80  bool operator==(const iterator& other ) const {
81  return _pos == other._pos;
82  }
83 
84  bool operator!=(const iterator& other ) const {
85  return _pos != other._pos;
86  }
87 
88  void operator++() {
89  _pos++;
90  }
91 
92  T& operator*() {
93  return _it->_data[_pos];
94  }
95 
96  string toString() const {
97  stringstream ss;
98  ss << _pos;
99  return ss.str();
100  }
101  private:
102  FastArray * _it;
103  int _pos;
104 
105  friend class FastArray;
106  };
107 
108 
109  iterator begin() {
110  return iterator(this);
111  }
112 
113  iterator end() {
114  _end._pos = _size;
115  return _end;
116  }
117 
118 
119  private:
120  int _capacity;
121  int _size;
122 
123  iterator _end;
124 
125  T * _data;
126  };
127 }
Definition: array.h:68
Definition: array.h:28