ringBuffer.c
00001
00002
00003
00004
00005
00006
00007 #include "ringBuffer.h"
00008
00009
00010
00011 void initRingBuffer(ringBuffer_t *ring, unsigned char *buf, int shiftLength) {
00012 ring->buf = buf;
00013 ring->shiftLength = shiftLength;
00014 ring->length = 1 << shiftLength;
00015 ring->first = 0;
00016 ring->last = 0;
00017 }
00018
00019
00020 void clearRingBuffer(ringBuffer_t *ring) {
00021 ring->first = 0;
00022 ring->last = 0;
00023 }
00024
00025
00026
00027 int getRingFreeSize(ringBuffer_t *ring) {
00028
00029 int fill = ring->last - ring->first;
00030 return (ring->length - (fill + ((fill < 0) ? ring->length : 0))) -1;
00031 }
00032
00033
00034
00035 int getRingFillSize(ringBuffer_t *ring) {
00036 return ring->length - getRingFreeSize(ring) -1;
00037 }
00038
00039
00040
00041 int putRingBuffer(ringBuffer_t *ring, unsigned char ch) {
00042
00043
00044 if (getRingFreeSize(ring) <= 0) {
00045 return -1;
00046 }
00047 ring->buf[ring->last] = ch;
00048 ring->last = (ring->last + 1) & (ring->length - 1);
00049
00050 return 0;
00051 }
00052
00053
00054
00055 int getRingBuffer(ringBuffer_t *ring, unsigned char *ch) {
00056
00057
00058 if (ring->first == ring->last) {
00059 return -1;
00060 }
00061
00062 *ch = ring->buf[ring->first];
00063 ring->first = (ring->first + 1) & (ring->length - 1);
00064
00065 return 0;
00066 }
00067
00068
00069 int putRingBufferStr(ringBuffer_t *ring, const unsigned char *str, int n) {
00070 int i;
00071
00072 for (i = 0; i < n; ++i) {
00073 if (putRingBuffer(ring, str[i]) < 0) {
00074 break;
00075 }
00076 }
00077 return i;
00078 }
00079
00080
00081 int getRingBufferStr(ringBuffer_t *ring, unsigned char *str, int n) {
00082 int i;
00083
00084 for (i = 0; i < n; ++i) {
00085 if (getRingBuffer(ring, (unsigned char *)&str[i]) < 0) {
00086 break;
00087 }
00088 }
00089 return i;
00090 }
00091
00092
00093
00094 int checksumRingBuffer(ringBuffer_t *ring, int num) {
00095 int index;
00096 int sum = 0;
00097 int i;
00098
00099 index = ring->first;
00100 for (i = 0; i < num; ++i) {
00101 sum += ring->buf[index++];
00102 index &= (ring->length -1);
00103 }
00104
00105 if (sum != ring->buf[index]) {
00106 return -1;
00107 } else {
00108 return 0;
00109 }
00110 }
00111
00112
00113
00114 void getRingBufferCopy(unsigned char *header, ringBuffer_t *ring, int num) {
00115 unsigned char *p = header;
00116 int index;
00117 int i;
00118
00119 index = ring->first;
00120 for (i = 0; i < num; ++i) {
00121 *p++ = ring->buf[index++];
00122 index &= (ring->length -1);
00123 }
00124 }
00125