MeshKit
1.0
|
00001 #ifndef SIMPLEARRAY_H 00002 #define SIMPLEARRAY_H 00003 00004 #include <algorithm> 00005 #include <cstdlib> 00006 00007 template <typename T> 00008 class SimpleArray 00009 { 00010 private: 00011 // TODO: make SimpleArrays copyable 00012 SimpleArray(const SimpleArray &); 00013 SimpleArray & operator = (const SimpleArray &); 00014 00015 T *arr; 00016 int arrSize; 00017 int arrAllocated; 00018 public: 00019 SimpleArray() : arr(NULL), arrSize(0), arrAllocated(0) {} 00020 00021 SimpleArray( unsigned s ) : arr(NULL), arrSize(s), arrAllocated(s) 00022 { 00023 resize(s); 00024 } 00025 00026 ~SimpleArray() 00027 { 00028 clear(); 00029 } 00030 00031 int size() const { return arrSize; } 00032 int capacity() const { return arrAllocated; } 00033 00034 void resize( unsigned s ) 00035 { 00036 clear(); 00037 if (s == 0) return; 00038 arr = (T*)malloc(s*sizeof(T)); 00039 for (unsigned i = 0; i < s; ++i) 00040 new (arr+i) T(); 00041 arrSize = arrAllocated = s; 00042 } 00043 00044 void clear() 00045 { 00046 if (arr == NULL) return; 00047 for (int i = 0; i < arrSize; ++i) 00048 arr[i].~T(); 00049 free(arr); 00050 arr = NULL; 00051 arrSize = arrAllocated = 0; 00052 } 00053 00054 void swap(SimpleArray &other) 00055 { 00056 using std::swap; 00057 swap(arr, other.arr); 00058 swap(arrSize, other.arrSize); 00059 swap(arrAllocated, other.arrAllocated); 00060 } 00061 00062 typedef T* iterator; 00063 typedef const T* const_iterator; 00064 iterator begin() { return arr; } 00065 const_iterator begin() const { return arr; } 00066 iterator end() { return arr + arrSize; } 00067 const_iterator end() const { return arr + arrSize; } 00068 00069 T& operator[]( unsigned idx ) { return arr[idx]; } 00070 const T& operator[]( unsigned idx ) const { return arr[idx]; } 00071 00072 // Don't use these directly! 00073 T** ptr_() { return &arr; } 00074 int* size_() { return &arrSize; } 00075 int* capacity_() { return &arrAllocated; } 00076 }; 00077 00078 #define ARRAY_INOUT( A ) (A).ptr_(), (A).capacity_(), (A).size_() 00079 #define ARRAY_IN( A ) &(A)[0], (A).size() 00080 00081 namespace std 00082 { 00083 // Alas, this is non-standard, but it works everywhere, and there's no other 00084 // way to do it. 00085 template<typename T> 00086 void swap(SimpleArray<T> &lhs, SimpleArray<T> &rhs) 00087 { 00088 lhs.swap(rhs); 00089 } 00090 } 00091 00092 #endif