00001 #define TRACE_NAME "ByteFIFO"
00002 #include "ByteFIFO.h"
00003 #include <string.h>
00004 #include <cassert>
00005
00006
00008
00009
00010
00012
00013 ByteFIFO::ByteFIFO(const size_t initialAllocation)
00014 {
00015 bytesAllocated=initialAllocation;
00016 buffer=new char [bytesAllocated];
00017 nextToWrite=buffer;
00018 nextToRead=buffer;
00019 }
00020
00021 #if 0
00022
00023 ByteFIFO::ByteFIFO(const ByteFIFO& other)
00024 {
00025 NOT_IMPLEMENTED
00026 }
00027
00028 const ByteFIFO& ByteFIFO::operator=(const ByteFIFO& other)
00029 {
00030 NOT_IMPLEMENTED
00031 }
00032
00033 bool ByteFIFO::operator==(const ByteFIFO& other) const
00034 {
00035 NOT_IMPLEMENTED
00036 }
00037
00038 bool ByteFIFO::operator<(const ByteFIFO& other) const
00039 {
00040 NOT_IMPLEMENTED
00041 }
00042
00043 size_t ByteFIFO::hash() const
00044 {
00045 NOT_IMPLEMENTED
00046 }
00047
00048 std::ostream& ByteFIFO::print_to(std::ostream& stream) const
00049 {
00050 NOT_IMPLEMENTED
00051 }
00052
00053 #endif
00054
00055 ByteFIFO::~ByteFIFO()
00056 {
00057 delete[] buffer;
00058 }
00059
00061
00062
00063
00065
00066 void ByteFIFO::write(const void* const byteBuffer, const size_t numBytes)
00067 {
00068 size_t bytesRemaining = bytesAllocated - (nextToWrite-buffer);
00069 if (numBytes > bytesRemaining) {
00070 makeRoom(numBytes - bytesRemaining);
00071 }
00072 memcpy(nextToWrite, byteBuffer, numBytes);
00073 nextToWrite += numBytes;
00074 }
00075
00076
00077 size_t ByteFIFO::read(void* const byteBuffer, const size_t maxBytes)
00078 {
00079 size_t bytes = nextToWrite - nextToRead;
00080 if (bytes > maxBytes) bytes = maxBytes;
00081 if (bytes > 0) {
00082 memcpy(byteBuffer, nextToRead, bytes);
00083 nextToRead += bytes;
00084 }
00085 return bytes;
00086 }
00087
00088 void* ByteFIFO::peek()
00089 {
00090 return nextToRead;
00091 }
00092
00093 void ByteFIFO::skip(size_t bytes)
00094 {
00095 size_t bytes_possible = nextToWrite - nextToRead;
00096 assert(bytes <= bytes_possible);
00097 nextToRead += bytes_possible;
00098 }
00099
00100
00102
00103
00104
00106
00107 void ByteFIFO::makeRoom(size_t numAdditionalBytes)
00108 {
00109
00110
00111
00112
00113
00114
00115 size_t starting_gap = nextToRead - buffer;
00116 size_t numBytesHeld = nextToWrite-nextToRead;
00117 if (starting_gap >= numAdditionalBytes) {
00118 if (numBytesHeld) memmove(buffer, nextToRead, numBytesHeld);
00119 nextToWrite -= starting_gap;
00120 nextToRead = buffer;
00121 } else {
00122 size_t newAllocation = bytesAllocated;
00123 while (newAllocation < bytesAllocated + numAdditionalBytes) {
00124
00125 newAllocation += newAllocation;
00126 }
00127 char *newBuf = new char [newAllocation];
00128 if (numBytesHeld) memmove(newBuf, nextToRead, numBytesHeld);
00129 delete [] buffer;
00130 buffer = newBuf;
00131 nextToRead = buffer;
00132 nextToWrite = buffer + numBytesHeld;
00133 bytesAllocated = newAllocation;
00134 }
00135 }
00136
00137 #undef TRACE_NAME