Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* vim:set ts=4 sw=4 sts=4 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* We would use std::max but MS makes it painful
8 // windef.h defines min and max macros that we don't want
9 // http://support.microsoft.com/kb/143208
10 #ifdef _WIN32
11 #define NOMINMAX
12 #endif
13 */
15 #include <stdlib.h>
16 #include <string.h>
17 #include "nsAlgorithm.h"
19 /* This is a standard string builder like ones in Java
20 or C#. It uses a doubling allocation strategy
21 to grow when out of capacity.
23 This does not use nsTArray because nsTArray starts
24 growing by multiples of page size after it is the
25 size of one page. We want to keep doubling in size
26 so that we can continue to append at high speed even
27 for large strings.
29 Eventually, this should be templated for wide characters.
31 */
33 namespace mozilla {
35 class StringBuilder
36 {
37 public:
38 StringBuilder() {
39 mCapacity = 16;
40 mLength = 0;
41 mBuffer = static_cast<char*>(malloc(sizeof(char)*mCapacity));
42 mBuffer[0] = '\0';
43 }
45 void Append(const char *s) {
46 size_t newLength = strlen(s);
48 EnsureCapacity(mLength + newLength+1);
50 // copy the entire string including the null terminator
51 memcpy(&mBuffer[mLength], s, newLength+1);
52 mLength += newLength;
53 }
55 char *Buffer() {
56 return mBuffer;
57 }
59 size_t Length() {
60 return mLength;
61 }
63 size_t EnsureCapacity(size_t capacity) {
64 if (capacity > mCapacity) {
65 // make sure we at least double in size
66 mCapacity = XPCOM_MAX(capacity, mCapacity*2);
67 mBuffer = static_cast<char*>(realloc(mBuffer, mCapacity));
68 mCapacity = moz_malloc_usable_size(mBuffer);
69 }
70 return mCapacity;
71 }
73 ~StringBuilder()
74 {
75 free(mBuffer);
76 }
78 private:
79 char *mBuffer;
80 size_t mLength; // the length of the contained string not including the null terminator
81 size_t mCapacity; // the total size of mBuffer
82 };
84 }