1、乙個buffer快取簡單實現
#include #include #include #include class buffer
m_cap += m_incr;
m_begin = m_end = 0;
}~buffer()
int getbegin()
int getend()
int getcap()
int getleft()
int contentsize()
void put(const char *c, int len);
char *get(int len);
private:
char *m_buf;
int m_begin; //buffer 內容開始
int m_end; //buffer 內容結束
int m_cap; //buffer 總量
int m_incr;
};void buffer::put(const char *c, int len)
int left = getleft();
if (left <= len)
else
m_cap += expand;
realloc(m_buf, m_cap);
if (m_buf == nullptr)}}
memcpy(m_buf + m_end, c, len);
m_end += len;
}char *buffer::get(int len) //記得釋放
char *p = (char *)malloc(len + 1);
if (p == nullptr)
memcpy(p, m_buf + m_begin, len);
m_begin += len;
return p;
}
2、利用libevent 的evbuffer
#include #include #include using namespace std;
struct buf;
char buff[255];
};int main(int argc, char const *ar**)
3、乙個簡單的環形佇列快取
#include using namespace std;
template class circlequeue
m_cap = m_incr;
m_begin = m_end = 0;
}~circlequeue()
int getcap()
int getusenum()
else
}bool isempty()
bool isfull()
void putq(t elem);
t popq();
bool expand();
void print();
private:
t *m_array;
int m_begin;
int m_end;
int m_cap;
int m_incr;
int m_max;
};template void circlequeue::putq(t elem)
m_array[m_end] = elem;
m_end = (m_end + 1) % m_cap;
if (isfull())
}}template t circlequeue::popq()
template bool circlequeue::expand()
t *new_array = new t[m_cap + m_incr];
if (new_array == nullptr)
m_begin = m_end = 0;
for (int i = 0; i < m_cap; i++)
m_cap += m_incr;
delete m_array;
m_array = new_array;
return true;
}template void circlequeue::print()
}int main(int argc, char const *ar**)
注意:
如果在多執行緒的情況下使用,一定要對他們進行加鎖才可以使用
C 實現的Buffer類
寫c 的同志一定覺得byte 比c 的 byte 加 length的方式好的多。一來,只需要乙個物件就可以是表示一段位元組流,另一方面,由於c 的特性,不需要象c 那樣還要記得刪除指標。由於我工作中,需要頻繁地試用c 和c 所以寫了個c 的類,以便方便地管理位元組流。很簡單,先定義乙個類 cmemo...
C 實現的Buffer類
寫c 的同志一定覺得byte 比c 的 byte 加 length的方式好的多。一來,只需要乙個物件就可以是表示一段位元組流,另一方面,由於c 的特性,不需要象c 那樣還要記得刪除指標。由於我工作中,需要頻繁地試用c 和c 所以寫了個c 的類,以便方便地管理位元組流。很簡單,先定義乙個類 cmemo...
c 實現迴圈快取buffer
迴圈buffer是一種高效快取方式,一般用於接收固定長度協議使用。如果使用不斷擴充套件的快取操作 見 則我們必須要malloc不斷擴張快取,還會memcpy或memmve操作,效率比較低,而ringbuffer則很好的規避這些低效操作。如果協議長度是固定的,則可以使用ringbuffer作為網路的接...