00001 // array.h 00002 00003 /* 00004 * Copyright 2010 10gen Inc. 00005 * 00006 * Licensed under the Apache License, Version 2.0 (the "License"); 00007 * you may not use this file except in compliance with the License. 00008 * You may obtain a copy of the License at 00009 * 00010 * http://www.apache.org/licenses/LICENSE-2.0 00011 * 00012 * Unless required by applicable law or agreed to in writing, software 00013 * distributed under the License is distributed on an "AS IS" BASIS, 00014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00015 * See the License for the specific language governing permissions and 00016 * limitations under the License. 00017 */ 00018 00019 namespace mongo { 00020 00021 template<typename T> 00022 class FastArray { 00023 public: 00024 FastArray( int capacity=10000 ) 00025 : _capacity( capacity ) , _size(0) , _end(this,capacity) { 00026 _data = new T[capacity]; 00027 } 00028 00029 ~FastArray() { 00030 delete[] _data; 00031 } 00032 00033 void clear() { 00034 _size = 0; 00035 } 00036 00037 T& operator[]( int x ) { 00038 assert( x >= 0 && x < _capacity ); 00039 return _data[x]; 00040 } 00041 00042 T& getNext() { 00043 return _data[_size++]; 00044 } 00045 00046 void push_back( const T& t ) { 00047 _data[_size++] = t; 00048 } 00049 00050 void sort( int (*comp)(const void *, const void *) ) { 00051 qsort( _data , _size , sizeof(T) , comp ); 00052 } 00053 00054 int size() { 00055 return _size; 00056 } 00057 00058 bool hasSpace() { 00059 return _size < _capacity; 00060 } 00061 class iterator { 00062 public: 00063 iterator() { 00064 _it = 0; 00065 _pos = 0; 00066 } 00067 00068 iterator( FastArray * it , int pos=0 ) { 00069 _it = it; 00070 _pos = pos; 00071 } 00072 00073 bool operator==(const iterator& other ) const { 00074 return _pos == other._pos; 00075 } 00076 00077 bool operator!=(const iterator& other ) const { 00078 return _pos != other._pos; 00079 } 00080 00081 void operator++() { 00082 _pos++; 00083 } 00084 00085 T& operator*() { 00086 return _it->_data[_pos]; 00087 } 00088 00089 string toString() const { 00090 stringstream ss; 00091 ss << _pos; 00092 return ss.str(); 00093 } 00094 private: 00095 FastArray * _it; 00096 int _pos; 00097 00098 friend class FastArray; 00099 }; 00100 00101 00102 iterator begin() { 00103 return iterator(this); 00104 } 00105 00106 iterator end() { 00107 _end._pos = _size; 00108 return _end; 00109 } 00110 00111 00112 private: 00113 int _capacity; 00114 int _size; 00115 00116 iterator _end; 00117 00118 T * _data; 00119 }; 00120 }