1 /* 2 * tBuffer.h 3 * Avida 4 * 5 * Called "tBuffer.hh" prior to 12/7/05. 6 * Copyright 1999-2011 Michigan State University. All rights reserved. 7 * Copyright 1993-2003 California Institute of Technology. 8 * 9 * 10 * This file is part of Avida. 11 * 12 * Avida is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License 13 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 14 * 15 * Avida is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. 17 * 18 * You should have received a copy of the GNU Lesser General Public License along with Avida. 19 * If not, see <http://www.gnu.org/licenses/>. 20 * 21 */ 22 23 #ifndef tBuffer_h 24 #define tBuffer_h 25 26 #include "cString.h" 27 #include "tArray.h" 28 29 #include <cassert> 30 #include <iostream> 31 32 33 template <class T> class tBuffer 34 { 35 private: 36 tArray<T> data; // Contents of buffer... 37 int offset; // Position in buffer to next write. 38 int total; // Total inputs ever... 39 int last_total; // Total inputs at time of last ZeroNumAdds. 40 public: tBuffer(const int size)41 explicit tBuffer(const int size) : data(size), offset(0), total(0), last_total(0) { ; } tBuffer(const tBuffer<T> & in)42 tBuffer(const tBuffer<T> & in) : data(in.data), offset(in.offset), total(in.total), last_total(in.last_total) { ; } ~tBuffer()43 ~tBuffer() { ; } 44 45 tBuffer& operator=(const tBuffer<T>& in) 46 { 47 data = in.data; 48 offset = in.offset; 49 total = in.total; 50 last_total = in.last_total; 51 return *this; 52 } 53 Clear()54 void Clear() { offset = 0; total = 0; last_total = 0; } ZeroNumAdds()55 void ZeroNumAdds() { last_total = total; total = 0; } 56 Add(const T & in_value)57 void Add(const T& in_value) 58 { 59 data[offset] = in_value; 60 total++; 61 offset++; 62 offset %= data.GetSize(); 63 } 64 Pop()65 void Pop() 66 { 67 total--; 68 offset--; 69 if (offset < 0) offset += data.GetSize(); 70 } 71 72 T operator[](int i) const 73 { 74 // assert(i < total); 75 int index = offset - i - 1; 76 if (index < 0) index += data.GetSize(); 77 assert(index >= 0 && index < data.GetSize()); 78 return data[index]; 79 } 80 GetCapacity()81 int GetCapacity() const { return data.GetSize(); } GetTotal()82 int GetTotal() const { return total; } GetNumStored()83 int GetNumStored() const { return (total <= data.GetSize()) ? total : data.GetSize(); } GetNum()84 int GetNum() const { return total - last_total; } 85 }; 86 87 #endif 88