ringBufferTemplate.h
Go to the documentation of this file.00001 #ifndef RING_BUFFER_H
00002 #define RING_BUFFER_H
00003
00017 template<class C> class RingBuffer {
00018 typedef unsigned long size_type;
00019 size_type real_size;
00020 size_type first;
00021 size_type last;
00022 C *buffer;
00023 RingBuffer(void);
00024
00025 public:
00031 RingBuffer(size_type size) : real_size(1), first(0), last(0) {
00032 while (size > (real_size -1)) {
00033 real_size <<= 1;
00034 }
00035 buffer = new C[real_size];
00036 }
00037
00038 ~RingBuffer(void) {
00039 delete [] buffer;
00040 }
00041
00047 size_type size(void) {
00048 return (last >= first) ? last - first : real_size - (first - last);
00049 }
00050
00056 size_type free_size(void) {
00057 return real_size -1 - size();
00058 }
00059
00066 void put(const C* data, size_type size) {
00067 size_type free_length = free_size();
00068 size_type len = (size > free_length) ? free_length : size;
00069
00070 size_type put_end = (len > (real_size - last)) ? real_size : last + len;
00071 C *p = &buffer[last];
00072 C *q = (C *)data;
00073 for (size_type i = last; i < put_end; ++i) {
00074 *p++ = *q++;
00075 }
00076
00077 C *data_last = (C *)data + len;
00078 if (q < data_last) {
00079 p = &buffer[0];
00080 while (q < data_last) {
00081 *p++ = *q++;
00082 }
00083 }
00084 last = static_cast<size_type>((p - &buffer[0]) & (real_size -1));
00085 }
00086
00095 int copy(C* data, size_type size) {
00096 size_type filled_length = this->size();
00097 size_type len = (size > filled_length) ? filled_length : size;
00098
00099 size_type get_end = (len > (real_size - first)) ? real_size : first + len;
00100 C *p = data;
00101 C *q = &buffer[first];
00102 for (size_type i = first; i < get_end; ++i) {
00103 *p++ = *q++;
00104 }
00105
00106 C *data_last = data + len;
00107 if (p < data_last) {
00108 q = &buffer[0];
00109 while (p < data_last) {
00110 *p++ = *q++;
00111 }
00112 }
00113 return len;
00114 }
00115
00124 void get(C* data, size_type size) {
00125 int len = copy(data, size);
00126 first = (first + len) & (real_size -1);
00127 }
00128
00132 void clear(void) {
00133 first = 0;
00134 last = 0;
00135 }
00136 };
00137
00138 #endif
00139