00001 /* 00002 * The Mana World 00003 * Copyright (C) 2004 The Mana World Development Team 00004 * 00005 * This file is part of The Mana World. 00006 * 00007 * This program is free software; you can redistribute it and/or modify 00008 * it under the terms of the GNU General Public License as published by 00009 * the Free Software Foundation; either version 2 of the License, or 00010 * any later version. 00011 * 00012 * This program is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU General Public License 00018 * along with this program; if not, write to the Free Software 00019 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00020 */ 00021 00022 #ifndef LOCKEDARRAY_H 00023 #define LOCKEDARRAY_H 00024 00025 #include <algorithm> 00026 00034 template<class T> 00035 class LockedArray 00036 { 00037 public: 00038 LockedArray(unsigned int size); 00039 ~LockedArray(); 00040 00041 void lock() { mLocked = true; }; 00042 void unlock() { mLocked = false; }; 00043 00044 bool isLocked() const { return mLocked; }; 00045 00046 T getEntry() const { return mData[mCurEntry]; }; 00047 void setEntry(T entry) { mData[mCurEntry] = entry; mFilled = true; }; 00048 00049 void next(); 00050 void prev(); 00051 void select(unsigned int pos); 00052 unsigned int getPos() const { return mCurEntry; } 00053 00054 unsigned int getSize() const { return mSize; }; 00055 00059 void clear(); 00060 00061 protected: 00062 unsigned int mSize; 00063 00064 T* mData; 00065 00066 unsigned int mCurEntry; 00067 bool mLocked; 00068 00069 bool mFilled; 00070 }; 00071 00072 template<class T> 00073 LockedArray<T>::LockedArray(unsigned int size): 00074 mSize(size), mData(new T[size]), mCurEntry(0), mLocked(false), 00075 mFilled(false) 00076 { 00077 std::fill_n(mData, mSize, (T)0); 00078 } 00079 00080 template<class T> 00081 LockedArray<T>::~LockedArray() 00082 { 00083 delete [] mData; 00084 } 00085 00086 template<class T> 00087 void LockedArray<T>::next() 00088 { 00089 if (mLocked) 00090 return; 00091 00092 if (++mCurEntry == mSize) 00093 mCurEntry = 0; 00094 } 00095 00096 template<class T> 00097 void LockedArray<T>::prev() 00098 { 00099 if (mLocked) 00100 return; 00101 00102 mCurEntry = mCurEntry ? (--mCurEntry) : (mSize - 1); 00103 } 00104 00105 template<class T> 00106 void LockedArray<T>::select(unsigned int pos) 00107 { 00108 if (mLocked) 00109 return; 00110 00111 mCurEntry = pos; 00112 if (mCurEntry >= mSize) 00113 mCurEntry = 0; 00114 } 00115 00116 template<class T> 00117 void LockedArray<T>::clear() 00118 { 00119 if (!mFilled) return; 00120 00121 delete [] mData; 00122 00123 mData = new T[mSize]; 00124 00125 std::fill_n(mData, mSize, (T)0); 00126 00127 mCurEntry = 0; 00128 00129 mLocked = false; 00130 } 00131 #endif