1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/xpcom/ds/StringBuilder.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,84 @@ 1.4 +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 1.5 +/* vim:set ts=4 sw=4 sts=4 et cindent: */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +/* We would use std::max but MS makes it painful 1.11 +// windef.h defines min and max macros that we don't want 1.12 +// http://support.microsoft.com/kb/143208 1.13 +#ifdef _WIN32 1.14 +#define NOMINMAX 1.15 +#endif 1.16 +*/ 1.17 + 1.18 +#include <stdlib.h> 1.19 +#include <string.h> 1.20 +#include "nsAlgorithm.h" 1.21 + 1.22 +/* This is a standard string builder like ones in Java 1.23 + or C#. It uses a doubling allocation strategy 1.24 + to grow when out of capacity. 1.25 + 1.26 + This does not use nsTArray because nsTArray starts 1.27 + growing by multiples of page size after it is the 1.28 + size of one page. We want to keep doubling in size 1.29 + so that we can continue to append at high speed even 1.30 + for large strings. 1.31 + 1.32 + Eventually, this should be templated for wide characters. 1.33 + 1.34 + */ 1.35 + 1.36 +namespace mozilla { 1.37 + 1.38 +class StringBuilder 1.39 +{ 1.40 +public: 1.41 + StringBuilder() { 1.42 + mCapacity = 16; 1.43 + mLength = 0; 1.44 + mBuffer = static_cast<char*>(malloc(sizeof(char)*mCapacity)); 1.45 + mBuffer[0] = '\0'; 1.46 + } 1.47 + 1.48 + void Append(const char *s) { 1.49 + size_t newLength = strlen(s); 1.50 + 1.51 + EnsureCapacity(mLength + newLength+1); 1.52 + 1.53 + // copy the entire string including the null terminator 1.54 + memcpy(&mBuffer[mLength], s, newLength+1); 1.55 + mLength += newLength; 1.56 + } 1.57 + 1.58 + char *Buffer() { 1.59 + return mBuffer; 1.60 + } 1.61 + 1.62 + size_t Length() { 1.63 + return mLength; 1.64 + } 1.65 + 1.66 + size_t EnsureCapacity(size_t capacity) { 1.67 + if (capacity > mCapacity) { 1.68 + // make sure we at least double in size 1.69 + mCapacity = XPCOM_MAX(capacity, mCapacity*2); 1.70 + mBuffer = static_cast<char*>(realloc(mBuffer, mCapacity)); 1.71 + mCapacity = moz_malloc_usable_size(mBuffer); 1.72 + } 1.73 + return mCapacity; 1.74 + } 1.75 + 1.76 + ~StringBuilder() 1.77 + { 1.78 + free(mBuffer); 1.79 + } 1.80 + 1.81 +private: 1.82 + char *mBuffer; 1.83 + size_t mLength; // the length of the contained string not including the null terminator 1.84 + size_t mCapacity; // the total size of mBuffer 1.85 +}; 1.86 + 1.87 +}