/************************************************ * Fixed element pointer position. * The current pointer points to the latest element * * create zoufuzhou 20201001 * ************************************************/ #ifndef _MEM_FIX_ADDR_CACHE_HPP_ #define _MEM_FIX_ADDR_CACHE_HPP_ #include template class CMemFix { typedef struct { unsigned int maxsize; unsigned int size; unsigned int next; } HEAD; // Local variable private: unsigned int m_getnext; // Memory variable private: HEAD* p_head; T* p_ptr; private: void init(const string& tableName) { char* ptr = (char*)GlobMem::GetInstancePtr()->GetTablePtr(tableName); if (ptr == nullptr) { p_ptr = nullptr; p_head = nullptr; assert(true); return; } p_head = (HEAD*)(ptr); p_ptr = (T*)(ptr + sizeof(HEAD)); }; public: // memfix get not need set cache maxsize CMemFix(const string& tableName) { this->init(tableName); // assert(p_head->maxsize>1); this->m_getnext = p_head->next; }; // memfix push need set cache maxsize CMemFix(const string& tableName, unsigned int maxsize) { // assert(maxsize>1); this->init(tableName); p_head->maxsize = maxsize; if (p_head->size > p_head->maxsize) { p_head->size = p_head->maxsize; } if (p_head->next > p_head->maxsize) { p_head->next = p_head->maxsize; } p_head->next = p_head->next % p_head->maxsize; this->m_getnext = p_head->next; }; ~CMemFix(){}; T* operator()(void) { return p_ptr; }; // Take the next value T* getNext() { if (this->m_getnext == p_head->next) { return nullptr; } else { unsigned int tmpnext = this->m_getnext; this->m_getnext = (this->m_getnext + 1) % this->p_head->maxsize; return this->operator[](tmpnext); } }; // unsigned int get_next() { return this->m_getnext; } // Take the current latest value T* getCur(void) { return p_ptr + this->index_cur(); } unsigned int index_cur(void) { if (p_head->next <= 0) { return this->p_head->maxsize - 1; } else { return (p_head->next - 1) % this->p_head->maxsize; } } unsigned int max_size(void) { return this->p_head->maxsize; } T* operator[](unsigned int i) { if (p_ptr == nullptr) return nullptr; return p_ptr + i; }; void push(T* t) { if (p_ptr == nullptr) return; if (p_head->size < this->p_head->maxsize) { p_head->size++; } memcpy(p_ptr + p_head->next, t, sizeof(T)); // cout<<"p_next:"<next<next = (p_head->next + 1) % this->p_head->maxsize; }; unsigned int size(void) { if (p_head == nullptr) return 0; return p_head->size; }; void clear(void) { if (p_head == nullptr) return; p_head->size = 0; p_head->next = 0; this->m_getnext = p_head->next; }; }; #endif