| 131 | } |
| 132 | |
| 133 | void asCString::Allocate(size_t len, bool keepData) |
| 134 | { |
| 135 | // If we stored the capacity of the dynamically allocated buffer it would be possible |
| 136 | // to save some memory allocations if a string decreases in size then increases again, |
| 137 | // but this would require extra bytes in the string object itself, or a decrease of |
| 138 | // the static buffer, which in turn would mean extra memory is needed. I've tested each |
| 139 | // of these options, and it turned out that the current choice is what best balanced |
| 140 | // the number of allocations against the size of the allocations. |
| 141 | |
| 142 | if( len > 11 && len > length ) |
| 143 | { |
| 144 | // Allocate a new dynamic buffer if the new one is larger than the old |
| 145 | char *buf = asNEWARRAY(char,len+1); |
| 146 | if( buf == 0 ) |
| 147 | { |
| 148 | // Out of memory. Return without modifying anything |
| 149 | return; |
| 150 | } |
| 151 | |
| 152 | if( keepData ) |
| 153 | { |
| 154 | int l = (int)len < (int)length ? (int)len : (int)length; |
| 155 | memcpy(buf, AddressOf(), l); |
| 156 | } |
| 157 | |
| 158 | if( length > 11 ) |
| 159 | { |
| 160 | asDELETEARRAY(dynamic); |
| 161 | } |
| 162 | |
| 163 | dynamic = buf; |
| 164 | } |
| 165 | else if( len <= 11 && length > 11 ) |
| 166 | { |
| 167 | // Free the dynamic buffer, since it is no longer needed |
| 168 | char *buf = dynamic; |
| 169 | if( keepData ) |
| 170 | { |
| 171 | memcpy(&local, buf, len); |
| 172 | } |
| 173 | asDELETEARRAY(buf); |
| 174 | } |
| 175 | |
| 176 | length = (int)len; |
| 177 | |
| 178 | // Make sure the buffer is null terminated |
| 179 | AddressOf()[length] = 0; |
| 180 | } |
| 181 | |
| 182 | void asCString::Assign(const char *str, size_t len) |
| 183 | { |