CharBuffer.cpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #include <stdlib.h>
00019 #include "CharBuffer.h"
00020
00021 CharBuffer::CharBuffer()
00022 : myBuffer(NULL)
00023 {
00024 myBuffer = (char *) malloc(DEFAULT_BUFFER_SIZE);
00025 myBufferAllocatedLen = DEFAULT_BUFFER_SIZE;
00026 reset();
00027 }
00028
00029
00030 CharBuffer::CharBuffer(int32_t initialSize)
00031 : myBuffer(NULL)
00032 {
00033 myBuffer = (char *) malloc(initialSize);
00034 myBufferAllocatedLen = DEFAULT_BUFFER_SIZE;
00035
00036 reset();
00037 }
00038
00039
00040 CharBuffer::~CharBuffer()
00041 {
00042 reset();
00043 if(myBuffer != NULL)
00044 {
00045 free(myBuffer);
00046 myBuffer = NULL;
00047 }
00048 }
00049
00050
00051
00052 CharBuffer::CharBuffer(const CharBuffer& buffer)
00053 : myBuffer(NULL)
00054 {
00055 myBuffer =
00056 (char *) malloc(DEFAULT_BUFFER_SIZE);
00057 myBufferAllocatedLen = DEFAULT_BUFFER_SIZE;
00058
00059 reset();
00060
00061 copy(buffer);
00062 }
00063
00064
00065
00066 CharBuffer& CharBuffer::operator = (const CharBuffer& buffer)
00067 {
00068 copy(buffer);
00069 return(*this);
00070 }
00071
00072
00073
00074 CharBuffer& CharBuffer::operator = (const std::string& stringBuffer)
00075 {
00076
00077 if(prepareNewLength(stringBuffer.length()))
00078 {
00079 memcpy(myBuffer, stringBuffer.c_str(), stringBuffer.length());
00080 }
00081
00082
00083 return(*this);
00084 }
00085
00086
00087 bool CharBuffer::copy(const CharBuffer& buffer)
00088 {
00089
00090 if(this == &buffer)
00091 {
00092 return(true);
00093 }
00094
00095
00096
00097 prepareNewLength(buffer.myBufferLen);
00098
00099 memcpy(myBuffer, buffer.myBuffer, buffer.myBufferLen);
00100 myBufferLen = buffer.myBufferLen;
00101
00102 return(true);
00103 }
00104
00105
00106
00107 void CharBuffer::reset()
00108 {
00109 myBufferLen = 0;
00110 if(myBuffer != NULL)
00111 {
00112 myBuffer[0] = 0;
00113 }
00114 }
00115
00116
00117
00118
00119 int CharBuffer::readFromFile(IFILE filePtr, int32_t length)
00120 {
00121 if(filePtr == NULL)
00122 {
00123 return(0);
00124 }
00125
00126 if(prepareNewLength(length))
00127 {
00128 return(ifread(filePtr, myBuffer, length));
00129 }
00130
00131 return(false);
00132 }
00133
00134
00135
00136 bool CharBuffer::prepareNewLength(int32_t newLen)
00137 {
00138 if(newLen < 0)
00139 {
00140
00141 return(false);
00142 }
00143
00144
00145
00146 if(myBufferAllocatedLen <= newLen)
00147 {
00148
00149 char* tmpBufferPtr = (char *)realloc(myBuffer, newLen);
00150 if(tmpBufferPtr == NULL)
00151 {
00152
00153 fprintf(stderr, "FAILED TO ALLOCATE MEMORY!!!");
00154
00155 return(false);
00156 }
00157
00158 myBuffer = tmpBufferPtr;
00159 myBufferAllocatedLen = newLen;
00160 }
00161 myBufferLen = newLen;
00162 myBuffer[newLen] = 0;
00163 return(true);
00164 }
00165