Vault
4.1
|
00001 /* 00002 Copyright c1997-2014 Trygve Isaacson. All rights reserved. 00003 This file is part of the Code Vault version 4.1 00004 http://www.bombaydigital.com/ 00005 License: MIT. See LICENSE.md in the Vault top level directory. 00006 */ 00007 00008 #ifndef vcompactingdeque_h 00009 #define vcompactingdeque_h 00010 00013 #include "vtypes.h" 00014 00025 template < typename _Tp, typename _Alloc = std::allocator<_Tp> > 00026 class VCompactingDeque : public std::deque<_Tp, _Alloc> { 00027 public: 00028 00036 VCompactingDeque(size_t highWaterMarkRequired = 64, size_t lowWaterMarkRequired = 0) 00037 : std::deque<_Tp, _Alloc>() 00038 , mHighWaterMark(0) 00039 , mHighWaterMarkRequired(highWaterMarkRequired) 00040 , mLowWaterMarkRequired(lowWaterMarkRequired) 00041 {} 00042 ~VCompactingDeque() {} 00043 00050 void pop_front() { 00051 this->_saveHighWaterMark(); 00052 00053 std::deque<_Tp, _Alloc>::pop_front(); 00054 00055 this->_compactIfReachedThreshold(); 00056 } 00057 00064 void pop_back() { 00065 this->_saveHighWaterMark(); 00066 00067 std::deque<_Tp, _Alloc>::pop_back(); 00068 00069 this->_compactIfReachedThreshold(); 00070 } 00071 00078 void compact() { this->_compact(); } 00079 00080 private: 00081 00082 void _saveHighWaterMark() { 00083 mHighWaterMark = V_MAX(mHighWaterMark, this->size()); 00084 } 00085 00086 void _compactIfReachedThreshold() { 00087 if ((mHighWaterMark >= mHighWaterMarkRequired) && (this->size() <= mLowWaterMarkRequired)) { 00088 this->_compact(); 00089 } 00090 } 00091 00092 void _compact() { 00093 // See: http://www.gotw.ca/gotw/054.htm for details. Swap causes a fairly efficient copy to a fresh data structure. 00094 std::deque<_Tp, _Alloc> temp(*this); 00095 temp.swap(*this); 00096 mHighWaterMark = 0; // Doesn't mean current size is zero, means previous hwm is obsolete. 00097 } 00098 00099 size_t mHighWaterMark; 00100 size_t mHighWaterMarkRequired; 00101 size_t mLowWaterMarkRequired; 00102 00103 friend class VMessageUnit; // Unit test can peek at our internal state between operations. 00104 }; 00105 00106 #endif /* vcompactingdeque_h */