1/*
2 * Copyright (C) 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Google Inc. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#ifndef StringBuilder_h
28#define StringBuilder_h
29
30#include <wtf/text/AtomicString.h>
31#include <wtf/text/StringView.h>
32#include <wtf/text/WTFString.h>
33
34namespace WTF {
35
36class StringBuilder {
37    // Disallow copying since it's expensive and we don't want code to do it by accident.
38    WTF_MAKE_NONCOPYABLE(StringBuilder);
39
40public:
41    StringBuilder()
42        : m_length(0)
43        , m_is8Bit(true)
44        , m_bufferCharacters8(0)
45    {
46    }
47
48    WTF_EXPORT_PRIVATE void append(const UChar*, unsigned);
49    WTF_EXPORT_PRIVATE void append(const LChar*, unsigned);
50
51    ALWAYS_INLINE void append(const char* characters, unsigned length) { append(reinterpret_cast<const LChar*>(characters), length); }
52
53    void append(const String& string)
54    {
55        if (!string.length())
56            return;
57
58        // If we're appending to an empty string, and there is not a buffer (reserveCapacity has not been called)
59        // then just retain the string.
60        if (!m_length && !m_buffer) {
61            m_string = string;
62            m_length = string.length();
63            m_is8Bit = m_string.is8Bit();
64            return;
65        }
66
67        if (string.is8Bit())
68            append(string.characters8(), string.length());
69        else
70            append(string.characters16(), string.length());
71    }
72
73    void append(const StringBuilder& other)
74    {
75        if (!other.m_length)
76            return;
77
78        // If we're appending to an empty string, and there is not a buffer (reserveCapacity has not been called)
79        // then just retain the string.
80        if (!m_length && !m_buffer && !other.m_string.isNull()) {
81            m_string = other.m_string;
82            m_length = other.m_length;
83            return;
84        }
85
86        if (other.is8Bit())
87            append(other.characters8(), other.m_length);
88        else
89            append(other.characters16(), other.m_length);
90    }
91
92    void append(StringView stringView)
93    {
94        if (stringView.is8Bit())
95            append(stringView.characters8(), stringView.length());
96        else
97            append(stringView.characters16(), stringView.length());
98    }
99
100    void append(const String& string, unsigned offset, unsigned length)
101    {
102        if (!string.length())
103            return;
104
105        if ((offset + length) > string.length())
106            return;
107
108        if (string.is8Bit())
109            append(string.characters8() + offset, length);
110        else
111            append(string.characters16() + offset, length);
112    }
113
114    void append(const char* characters)
115    {
116        if (characters)
117            append(characters, strlen(characters));
118    }
119
120    void append(UChar c)
121    {
122        if (m_buffer && m_length < m_buffer->length() && m_string.isNull()) {
123            if (!m_is8Bit) {
124                m_bufferCharacters16[m_length++] = c;
125                return;
126            }
127
128            if (!(c & ~0xff)) {
129                m_bufferCharacters8[m_length++] = static_cast<LChar>(c);
130                return;
131            }
132        }
133        append(&c, 1);
134    }
135
136    void append(LChar c)
137    {
138        if (m_buffer && m_length < m_buffer->length() && m_string.isNull()) {
139            if (m_is8Bit)
140                m_bufferCharacters8[m_length++] = c;
141            else
142                m_bufferCharacters16[m_length++] = c;
143        } else
144            append(&c, 1);
145    }
146
147    void append(char c)
148    {
149        append(static_cast<LChar>(c));
150    }
151
152    void append(UChar32 c)
153    {
154        if (U_IS_BMP(c)) {
155            append(static_cast<UChar>(c));
156            return;
157        }
158        append(U16_LEAD(c));
159        append(U16_TRAIL(c));
160    }
161
162    template<unsigned charactersCount>
163    ALWAYS_INLINE void appendLiteral(const char (&characters)[charactersCount]) { append(characters, charactersCount - 1); }
164
165    WTF_EXPORT_PRIVATE void appendNumber(int);
166    WTF_EXPORT_PRIVATE void appendNumber(unsigned int);
167    WTF_EXPORT_PRIVATE void appendNumber(long);
168    WTF_EXPORT_PRIVATE void appendNumber(unsigned long);
169    WTF_EXPORT_PRIVATE void appendNumber(long long);
170    WTF_EXPORT_PRIVATE void appendNumber(unsigned long long);
171    WTF_EXPORT_PRIVATE void appendNumber(double, unsigned precision = 6, TrailingZerosTruncatingPolicy = TruncateTrailingZeros);
172    WTF_EXPORT_PRIVATE void appendECMAScriptNumber(double);
173    WTF_EXPORT_PRIVATE void appendFixedWidthNumber(double, unsigned decimalPlaces);
174
175    String toString()
176    {
177        shrinkToFit();
178        if (m_string.isNull())
179            reifyString();
180        return m_string;
181    }
182
183    const String& toStringPreserveCapacity() const
184    {
185        if (m_string.isNull())
186            reifyString();
187        return m_string;
188    }
189
190    AtomicString toAtomicString() const
191    {
192        if (!m_length)
193            return emptyAtom;
194
195        // If the buffer is sufficiently over-allocated, make a new AtomicString from a copy so its buffer is not so large.
196        if (canShrink()) {
197            if (is8Bit())
198                return AtomicString(characters8(), length());
199            return AtomicString(characters16(), length());
200        }
201
202        if (!m_string.isNull())
203            return AtomicString(m_string);
204
205        ASSERT(m_buffer);
206        return AtomicString(m_buffer.get(), 0, m_length);
207    }
208
209    unsigned length() const
210    {
211        return m_length;
212    }
213
214    bool isEmpty() const { return !m_length; }
215
216    WTF_EXPORT_PRIVATE void reserveCapacity(unsigned newCapacity);
217
218    unsigned capacity() const
219    {
220        return m_buffer ? m_buffer->length() : m_length;
221    }
222
223    WTF_EXPORT_PRIVATE void resize(unsigned newSize);
224
225    WTF_EXPORT_PRIVATE bool canShrink() const;
226
227    WTF_EXPORT_PRIVATE void shrinkToFit();
228
229    UChar operator[](unsigned i) const
230    {
231        ASSERT_WITH_SECURITY_IMPLICATION(i < m_length);
232        if (m_is8Bit)
233            return characters8()[i];
234        return characters16()[i];
235    }
236
237    const LChar* characters8() const
238    {
239        ASSERT(m_is8Bit);
240        if (!m_length)
241            return 0;
242        if (!m_string.isNull())
243            return m_string.characters8();
244        ASSERT(m_buffer);
245        return m_buffer->characters8();
246    }
247
248    const UChar* characters16() const
249    {
250        ASSERT(!m_is8Bit);
251        if (!m_length)
252            return 0;
253        if (!m_string.isNull())
254            return m_string.characters16();
255        ASSERT(m_buffer);
256        return m_buffer->characters16();
257    }
258
259    bool is8Bit() const { return m_is8Bit; }
260
261    void clear()
262    {
263        m_length = 0;
264        m_string = String();
265        m_buffer = 0;
266        m_bufferCharacters8 = 0;
267        m_is8Bit = true;
268    }
269
270    void swap(StringBuilder& stringBuilder)
271    {
272        std::swap(m_length, stringBuilder.m_length);
273        m_string.swap(stringBuilder.m_string);
274        m_buffer.swap(stringBuilder.m_buffer);
275        std::swap(m_is8Bit, stringBuilder.m_is8Bit);
276        std::swap(m_bufferCharacters8, stringBuilder.m_bufferCharacters8);
277    }
278
279private:
280    void allocateBuffer(const LChar* currentCharacters, unsigned requiredLength);
281    void allocateBuffer(const UChar* currentCharacters, unsigned requiredLength);
282    void allocateBufferUpConvert(const LChar* currentCharacters, unsigned requiredLength);
283    template <typename CharType>
284    void reallocateBuffer(unsigned requiredLength);
285    template <typename CharType>
286    ALWAYS_INLINE CharType* appendUninitialized(unsigned length);
287    template <typename CharType>
288    CharType* appendUninitializedSlow(unsigned length);
289    template <typename CharType>
290    ALWAYS_INLINE CharType * getBufferCharacters();
291    WTF_EXPORT_PRIVATE void reifyString() const;
292
293    unsigned m_length;
294    mutable String m_string;
295    RefPtr<StringImpl> m_buffer;
296    bool m_is8Bit;
297    union {
298        LChar* m_bufferCharacters8;
299        UChar* m_bufferCharacters16;
300    };
301};
302
303template <>
304ALWAYS_INLINE LChar* StringBuilder::getBufferCharacters<LChar>()
305{
306    ASSERT(m_is8Bit);
307    return m_bufferCharacters8;
308}
309
310template <>
311ALWAYS_INLINE UChar* StringBuilder::getBufferCharacters<UChar>()
312{
313    ASSERT(!m_is8Bit);
314    return m_bufferCharacters16;
315}
316
317template <typename CharType>
318bool equal(const StringBuilder& s, const CharType* buffer, unsigned length)
319{
320    if (s.length() != length)
321        return false;
322
323    if (s.is8Bit())
324        return equal(s.characters8(), buffer, length);
325
326    return equal(s.characters16(), buffer, length);
327}
328
329template <typename StringType>
330bool equal(const StringBuilder& a, const StringType& b)
331{
332    if (a.length() != b.length())
333        return false;
334
335    if (!a.length())
336        return true;
337
338    if (a.is8Bit()) {
339        if (b.is8Bit())
340            return equal(a.characters8(), b.characters8(), a.length());
341        return equal(a.characters8(), b.characters16(), a.length());
342    }
343
344    if (b.is8Bit())
345        return equal(a.characters16(), b.characters8(), a.length());
346    return equal(a.characters16(), b.characters16(), a.length());
347}
348
349inline bool operator==(const StringBuilder& a, const StringBuilder& b) { return equal(a, b); }
350inline bool operator!=(const StringBuilder& a, const StringBuilder& b) { return !equal(a, b); }
351inline bool operator==(const StringBuilder& a, const String& b) { return equal(a, b); }
352inline bool operator!=(const StringBuilder& a, const String& b) { return !equal(a, b); }
353inline bool operator==(const String& a, const StringBuilder& b) { return equal(b, a); }
354inline bool operator!=(const String& a, const StringBuilder& b) { return !equal(b, a); }
355
356} // namespace WTF
357
358using WTF::StringBuilder;
359
360#endif // StringBuilder_h
361