Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / wtf / text / WTFString.cpp
1 /*
2  * (C) 1999 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2012 Apple Inc. All rights reserved.
4  * Copyright (C) 2007-2009 Torch Mobile, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public License
17  * along with this library; see the file COPYING.LIB.  If not, write to
18  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 #include "config.h"
23 #include "WTFString.h"
24
25 #include "IntegerToStringConversion.h"
26 #include <stdarg.h>
27 #include "wtf/ASCIICType.h"
28 #include "wtf/DataLog.h"
29 #include "wtf/HexNumber.h"
30 #include "wtf/MathExtras.h"
31 #include "wtf/text/CString.h"
32 #include "wtf/StringExtras.h"
33 #include "wtf/Vector.h"
34 #include "wtf/dtoa.h"
35 #include "wtf/unicode/CharacterNames.h"
36 #include "wtf/unicode/UTF8.h"
37 #include "wtf/unicode/Unicode.h"
38
39 using namespace std;
40
41 namespace WTF {
42
43 using namespace Unicode;
44 using namespace std;
45
46 // Construct a string with UTF-16 data.
47 String::String(const UChar* characters, unsigned length)
48     : m_impl(characters ? StringImpl::create(characters, length) : nullptr)
49 {
50 }
51
52 // Construct a string with UTF-16 data, from a null-terminated source.
53 String::String(const UChar* str)
54 {
55     if (!str)
56         return;
57     m_impl = StringImpl::create(str, lengthOfNullTerminatedString(str));
58 }
59
60 // Construct a string with latin1 data.
61 String::String(const LChar* characters, unsigned length)
62     : m_impl(characters ? StringImpl::create(characters, length) : nullptr)
63 {
64 }
65
66 String::String(const char* characters, unsigned length)
67     : m_impl(characters ? StringImpl::create(reinterpret_cast<const LChar*>(characters), length) : nullptr)
68 {
69 }
70
71 // Construct a string with latin1 data, from a null-terminated source.
72 String::String(const LChar* characters)
73     : m_impl(characters ? StringImpl::create(characters) : nullptr)
74 {
75 }
76
77 String::String(const char* characters)
78     : m_impl(characters ? StringImpl::create(reinterpret_cast<const LChar*>(characters)) : nullptr)
79 {
80 }
81
82 void String::append(const String& string)
83 {
84     if (string.isEmpty())
85         return;
86     if (!m_impl) {
87         m_impl = string.m_impl;
88         return;
89     }
90
91     // FIXME: This is extremely inefficient. So much so that we might want to take this
92     // out of String's API. We can make it better by optimizing the case where exactly
93     // one String is pointing at this StringImpl, but even then it's going to require a
94     // call into the allocator every single time.
95
96     if (m_impl->is8Bit() && string.m_impl->is8Bit()) {
97         LChar* data;
98         RELEASE_ASSERT(string.length() <= numeric_limits<unsigned>::max() - m_impl->length());
99         RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(m_impl->length() + string.length(), data);
100         memcpy(data, m_impl->characters8(), m_impl->length() * sizeof(LChar));
101         memcpy(data + m_impl->length(), string.characters8(), string.length() * sizeof(LChar));
102         m_impl = newImpl.release();
103         return;
104     }
105
106     UChar* data;
107     RELEASE_ASSERT(string.length() <= numeric_limits<unsigned>::max() - m_impl->length());
108     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(m_impl->length() + string.length(), data);
109
110     if (m_impl->is8Bit())
111         StringImpl::copyChars(data, m_impl->characters8(), m_impl->length());
112     else
113         StringImpl::copyChars(data, m_impl->characters16(), m_impl->length());
114
115     if (string.impl()->is8Bit())
116         StringImpl::copyChars(data + m_impl->length(), string.impl()->characters8(), string.impl()->length());
117     else
118         StringImpl::copyChars(data + m_impl->length(), string.impl()->characters16(), string.impl()->length());
119
120     m_impl = newImpl.release();
121 }
122
123 template <typename CharacterType>
124 inline void String::appendInternal(CharacterType c)
125 {
126     // FIXME: This is extremely inefficient. So much so that we might want to take this
127     // out of String's API. We can make it better by optimizing the case where exactly
128     // one String is pointing at this StringImpl, but even then it's going to require a
129     // call into the allocator every single time.
130     if (!m_impl) {
131         m_impl = StringImpl::create(&c, 1);
132         return;
133     }
134
135     UChar* data; // FIXME: We should be able to create an 8 bit string via this code path.
136     RELEASE_ASSERT(m_impl->length() < numeric_limits<unsigned>::max());
137     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(m_impl->length() + 1, data);
138     if (m_impl->is8Bit())
139         StringImpl::copyChars(data, m_impl->characters8(), m_impl->length());
140     else
141         StringImpl::copyChars(data, m_impl->characters16(), m_impl->length());
142     data[m_impl->length()] = c;
143     m_impl = newImpl.release();
144 }
145
146 void String::append(LChar c)
147 {
148     appendInternal(c);
149 }
150
151 void String::append(UChar c)
152 {
153     appendInternal(c);
154 }
155
156 int codePointCompare(const String& a, const String& b)
157 {
158     return codePointCompare(a.impl(), b.impl());
159 }
160
161 void String::insert(const String& string, unsigned position)
162 {
163     if (string.isEmpty()) {
164         if (string.isNull())
165             return;
166         if (isNull())
167             m_impl = string.impl();
168         return;
169     }
170
171     if (string.is8Bit())
172         insert(string.impl()->characters8(), string.length(), position);
173     else
174         insert(string.impl()->characters16(), string.length(), position);
175 }
176
177 void String::append(const LChar* charactersToAppend, unsigned lengthToAppend)
178 {
179     if (!m_impl) {
180         if (!charactersToAppend)
181             return;
182         m_impl = StringImpl::create(charactersToAppend, lengthToAppend);
183         return;
184     }
185
186     if (!lengthToAppend)
187         return;
188
189     ASSERT(charactersToAppend);
190
191     unsigned strLength = m_impl->length();
192
193     if (m_impl->is8Bit()) {
194         RELEASE_ASSERT(lengthToAppend <= numeric_limits<unsigned>::max() - strLength);
195         LChar* data;
196         RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(strLength + lengthToAppend, data);
197         StringImpl::copyChars(data, m_impl->characters8(), strLength);
198         StringImpl::copyChars(data + strLength, charactersToAppend, lengthToAppend);
199         m_impl = newImpl.release();
200         return;
201     }
202
203     RELEASE_ASSERT(lengthToAppend <= numeric_limits<unsigned>::max() - strLength);
204     UChar* data;
205     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(length() + lengthToAppend, data);
206     StringImpl::copyChars(data, m_impl->characters16(), strLength);
207     StringImpl::copyChars(data + strLength, charactersToAppend, lengthToAppend);
208     m_impl = newImpl.release();
209 }
210
211 void String::append(const UChar* charactersToAppend, unsigned lengthToAppend)
212 {
213     if (!m_impl) {
214         if (!charactersToAppend)
215             return;
216         m_impl = StringImpl::create(charactersToAppend, lengthToAppend);
217         return;
218     }
219
220     if (!lengthToAppend)
221         return;
222
223     unsigned strLength = m_impl->length();
224
225     ASSERT(charactersToAppend);
226     RELEASE_ASSERT(lengthToAppend <= numeric_limits<unsigned>::max() - strLength);
227     UChar* data;
228     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(strLength + lengthToAppend, data);
229     if (m_impl->is8Bit())
230         StringImpl::copyChars(data, characters8(), strLength);
231     else
232         StringImpl::copyChars(data, characters16(), strLength);
233     StringImpl::copyChars(data + strLength, charactersToAppend, lengthToAppend);
234     m_impl = newImpl.release();
235 }
236
237 template<typename CharType>
238 PassRefPtr<StringImpl> insertInternal(PassRefPtr<StringImpl> impl, const CharType* charactersToInsert, unsigned lengthToInsert, unsigned position)
239 {
240     if (!lengthToInsert)
241         return impl;
242
243     ASSERT(charactersToInsert);
244     UChar* data; // FIXME: We should be able to create an 8 bit string here.
245     RELEASE_ASSERT(lengthToInsert <= numeric_limits<unsigned>::max() - impl->length());
246     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(impl->length() + lengthToInsert, data);
247
248     if (impl->is8Bit())
249         StringImpl::copyChars(data, impl->characters8(), position);
250     else
251         StringImpl::copyChars(data, impl->characters16(), position);
252
253     StringImpl::copyChars(data + position, charactersToInsert, lengthToInsert);
254
255     if (impl->is8Bit())
256         StringImpl::copyChars(data + position + lengthToInsert, impl->characters8() + position, impl->length() - position);
257     else
258         StringImpl::copyChars(data + position + lengthToInsert, impl->characters16() + position, impl->length() - position);
259
260     return newImpl.release();
261 }
262
263 void String::insert(const UChar* charactersToInsert, unsigned lengthToInsert, unsigned position)
264 {
265     if (position >= length()) {
266         append(charactersToInsert, lengthToInsert);
267         return;
268     }
269     ASSERT(m_impl);
270     m_impl = insertInternal(m_impl.release(), charactersToInsert, lengthToInsert, position);
271 }
272
273 void String::insert(const LChar* charactersToInsert, unsigned lengthToInsert, unsigned position)
274 {
275     if (position >= length()) {
276         append(charactersToInsert, lengthToInsert);
277         return;
278     }
279     ASSERT(m_impl);
280     m_impl = insertInternal(m_impl.release(), charactersToInsert, lengthToInsert, position);
281 }
282
283 UChar32 String::characterStartingAt(unsigned i) const
284 {
285     if (!m_impl || i >= m_impl->length())
286         return 0;
287     return m_impl->characterStartingAt(i);
288 }
289
290 void String::ensure16Bit()
291 {
292     unsigned length = this->length();
293     if (!length || !is8Bit())
294         return;
295     m_impl = make16BitFrom8BitSource(m_impl->characters8(), length).impl();
296 }
297
298 void String::truncate(unsigned position)
299 {
300     if (position >= length())
301         return;
302     if (m_impl->is8Bit()) {
303         LChar* data;
304         RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(position, data);
305         memcpy(data, m_impl->characters8(), position * sizeof(LChar));
306         m_impl = newImpl.release();
307     } else {
308         UChar* data;
309         RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(position, data);
310         memcpy(data, m_impl->characters16(), position * sizeof(UChar));
311         m_impl = newImpl.release();
312     }
313 }
314
315 template <typename CharacterType>
316 inline void String::removeInternal(const CharacterType* characters, unsigned position, int lengthToRemove)
317 {
318     CharacterType* data;
319     RefPtr<StringImpl> newImpl = StringImpl::createUninitialized(length() - lengthToRemove, data);
320     memcpy(data, characters, position * sizeof(CharacterType));
321     memcpy(data + position, characters + position + lengthToRemove,
322         (length() - lengthToRemove - position) * sizeof(CharacterType));
323
324     m_impl = newImpl.release();
325 }
326
327 void String::remove(unsigned position, int lengthToRemove)
328 {
329     if (lengthToRemove <= 0)
330         return;
331     if (position >= length())
332         return;
333     if (static_cast<unsigned>(lengthToRemove) > length() - position)
334         lengthToRemove = length() - position;
335
336     if (is8Bit()) {
337         removeInternal(characters8(), position, lengthToRemove);
338
339         return;
340     }
341
342     removeInternal(characters16(), position, lengthToRemove);
343 }
344
345 String String::substring(unsigned pos, unsigned len) const
346 {
347     if (!m_impl)
348         return String();
349     return m_impl->substring(pos, len);
350 }
351
352 String String::lower() const
353 {
354     if (!m_impl)
355         return String();
356     return m_impl->lower();
357 }
358
359 String String::upper() const
360 {
361     if (!m_impl)
362         return String();
363     return m_impl->upper();
364 }
365
366 String String::lower(const AtomicString& localeIdentifier) const
367 {
368     if (!m_impl)
369         return String();
370     return m_impl->lower(localeIdentifier);
371 }
372
373 String String::upper(const AtomicString& localeIdentifier) const
374 {
375     if (!m_impl)
376         return String();
377     return m_impl->upper(localeIdentifier);
378 }
379
380 String String::stripWhiteSpace() const
381 {
382     if (!m_impl)
383         return String();
384     return m_impl->stripWhiteSpace();
385 }
386
387 String String::stripWhiteSpace(IsWhiteSpaceFunctionPtr isWhiteSpace) const
388 {
389     if (!m_impl)
390         return String();
391     return m_impl->stripWhiteSpace(isWhiteSpace);
392 }
393
394 String String::simplifyWhiteSpace(StripBehavior stripBehavior) const
395 {
396     if (!m_impl)
397         return String();
398     return m_impl->simplifyWhiteSpace(stripBehavior);
399 }
400
401 String String::simplifyWhiteSpace(IsWhiteSpaceFunctionPtr isWhiteSpace, StripBehavior stripBehavior) const
402 {
403     if (!m_impl)
404         return String();
405     return m_impl->simplifyWhiteSpace(isWhiteSpace, stripBehavior);
406 }
407
408 String String::removeCharacters(CharacterMatchFunctionPtr findMatch) const
409 {
410     if (!m_impl)
411         return String();
412     return m_impl->removeCharacters(findMatch);
413 }
414
415 String String::foldCase() const
416 {
417     if (!m_impl)
418         return String();
419     return m_impl->foldCase();
420 }
421
422 Vector<UChar> String::charactersWithNullTermination() const
423 {
424     if (!m_impl)
425         return Vector<UChar>();
426
427     Vector<UChar> result;
428     result.reserveInitialCapacity(length() + 1);
429     appendTo(result);
430     result.append('\0');
431     return result;
432 }
433
434 unsigned String::copyTo(UChar* buffer, unsigned pos, unsigned maxLength) const
435 {
436     unsigned length = this->length();
437     RELEASE_ASSERT(pos <= length);
438     unsigned numCharacters = std::min(length - pos, maxLength);
439     if (!numCharacters)
440         return 0;
441     if (is8Bit())
442         StringImpl::copyChars(buffer, characters8() + pos, numCharacters);
443     else
444         StringImpl::copyChars(buffer, characters16() + pos, numCharacters);
445     return numCharacters;
446 }
447
448 String String::format(const char *format, ...)
449 {
450     va_list args;
451     va_start(args, format);
452
453     Vector<char, 256> buffer;
454
455     // Do the format once to get the length.
456 #if COMPILER(MSVC)
457     int result = _vscprintf(format, args);
458 #else
459     char ch;
460     int result = vsnprintf(&ch, 1, format, args);
461     // We need to call va_end() and then va_start() again here, as the
462     // contents of args is undefined after the call to vsnprintf
463     // according to http://man.cx/snprintf(3)
464     //
465     // Not calling va_end/va_start here happens to work on lots of
466     // systems, but fails e.g. on 64bit Linux.
467     va_end(args);
468     va_start(args, format);
469 #endif
470
471     if (result == 0)
472         return String("");
473     if (result < 0)
474         return String();
475     unsigned len = result;
476     buffer.grow(len + 1);
477
478     // Now do the formatting again, guaranteed to fit.
479     vsnprintf(buffer.data(), buffer.size(), format, args);
480
481     va_end(args);
482
483     return StringImpl::create(reinterpret_cast<const LChar*>(buffer.data()), len);
484 }
485
486 String String::number(int number)
487 {
488     return numberToStringSigned<String>(number);
489 }
490
491 String String::number(unsigned number)
492 {
493     return numberToStringUnsigned<String>(number);
494 }
495
496 String String::number(long number)
497 {
498     return numberToStringSigned<String>(number);
499 }
500
501 String String::number(unsigned long number)
502 {
503     return numberToStringUnsigned<String>(number);
504 }
505
506 String String::number(long long number)
507 {
508     return numberToStringSigned<String>(number);
509 }
510
511 String String::number(unsigned long long number)
512 {
513     return numberToStringUnsigned<String>(number);
514 }
515
516 String String::number(double number, unsigned precision, TrailingZerosTruncatingPolicy trailingZerosTruncatingPolicy)
517 {
518     NumberToStringBuffer buffer;
519     return String(numberToFixedPrecisionString(number, precision, buffer, trailingZerosTruncatingPolicy == TruncateTrailingZeros));
520 }
521
522 String String::numberToStringECMAScript(double number)
523 {
524     NumberToStringBuffer buffer;
525     return String(numberToString(number, buffer));
526 }
527
528 String String::numberToStringFixedWidth(double number, unsigned decimalPlaces)
529 {
530     NumberToStringBuffer buffer;
531     return String(numberToFixedWidthString(number, decimalPlaces, buffer));
532 }
533
534 int String::toIntStrict(bool* ok, int base) const
535 {
536     if (!m_impl) {
537         if (ok)
538             *ok = false;
539         return 0;
540     }
541     return m_impl->toIntStrict(ok, base);
542 }
543
544 unsigned String::toUIntStrict(bool* ok, int base) const
545 {
546     if (!m_impl) {
547         if (ok)
548             *ok = false;
549         return 0;
550     }
551     return m_impl->toUIntStrict(ok, base);
552 }
553
554 int64_t String::toInt64Strict(bool* ok, int base) const
555 {
556     if (!m_impl) {
557         if (ok)
558             *ok = false;
559         return 0;
560     }
561     return m_impl->toInt64Strict(ok, base);
562 }
563
564 uint64_t String::toUInt64Strict(bool* ok, int base) const
565 {
566     if (!m_impl) {
567         if (ok)
568             *ok = false;
569         return 0;
570     }
571     return m_impl->toUInt64Strict(ok, base);
572 }
573
574 int String::toInt(bool* ok) const
575 {
576     if (!m_impl) {
577         if (ok)
578             *ok = false;
579         return 0;
580     }
581     return m_impl->toInt(ok);
582 }
583
584 unsigned String::toUInt(bool* ok) const
585 {
586     if (!m_impl) {
587         if (ok)
588             *ok = false;
589         return 0;
590     }
591     return m_impl->toUInt(ok);
592 }
593
594 int64_t String::toInt64(bool* ok) const
595 {
596     if (!m_impl) {
597         if (ok)
598             *ok = false;
599         return 0;
600     }
601     return m_impl->toInt64(ok);
602 }
603
604 uint64_t String::toUInt64(bool* ok) const
605 {
606     if (!m_impl) {
607         if (ok)
608             *ok = false;
609         return 0;
610     }
611     return m_impl->toUInt64(ok);
612 }
613
614 double String::toDouble(bool* ok) const
615 {
616     if (!m_impl) {
617         if (ok)
618             *ok = false;
619         return 0.0;
620     }
621     return m_impl->toDouble(ok);
622 }
623
624 float String::toFloat(bool* ok) const
625 {
626     if (!m_impl) {
627         if (ok)
628             *ok = false;
629         return 0.0f;
630     }
631     return m_impl->toFloat(ok);
632 }
633
634 String String::isolatedCopy() const
635 {
636     if (!m_impl)
637         return String();
638     return m_impl->isolatedCopy();
639 }
640
641 bool String::isSafeToSendToAnotherThread() const
642 {
643     if (!impl())
644         return true;
645     if (impl()->isStatic())
646         return true;
647     // AtomicStrings are not safe to send between threads as ~StringImpl()
648     // will try to remove them from the wrong AtomicStringTable.
649     if (impl()->isAtomic())
650         return false;
651     if (impl()->hasOneRef())
652         return true;
653     return false;
654 }
655
656 void String::split(const String& separator, bool allowEmptyEntries, Vector<String>& result) const
657 {
658     result.clear();
659
660     unsigned startPos = 0;
661     size_t endPos;
662     while ((endPos = find(separator, startPos)) != kNotFound) {
663         if (allowEmptyEntries || startPos != endPos)
664             result.append(substring(startPos, endPos - startPos));
665         startPos = endPos + separator.length();
666     }
667     if (allowEmptyEntries || startPos != length())
668         result.append(substring(startPos));
669 }
670
671 void String::split(UChar separator, bool allowEmptyEntries, Vector<String>& result) const
672 {
673     result.clear();
674
675     unsigned startPos = 0;
676     size_t endPos;
677     while ((endPos = find(separator, startPos)) != kNotFound) {
678         if (allowEmptyEntries || startPos != endPos)
679             result.append(substring(startPos, endPos - startPos));
680         startPos = endPos + 1;
681     }
682     if (allowEmptyEntries || startPos != length())
683         result.append(substring(startPos));
684 }
685
686 CString String::ascii() const
687 {
688     // Printable ASCII characters 32..127 and the null character are
689     // preserved, characters outside of this range are converted to '?'.
690
691     unsigned length = this->length();
692     if (!length) {
693         char* characterBuffer;
694         return CString::newUninitialized(length, characterBuffer);
695     }
696
697     if (this->is8Bit()) {
698         const LChar* characters = this->characters8();
699
700         char* characterBuffer;
701         CString result = CString::newUninitialized(length, characterBuffer);
702
703         for (unsigned i = 0; i < length; ++i) {
704             LChar ch = characters[i];
705             characterBuffer[i] = ch && (ch < 0x20 || ch > 0x7f) ? '?' : ch;
706         }
707
708         return result;
709     }
710
711     const UChar* characters = this->characters16();
712
713     char* characterBuffer;
714     CString result = CString::newUninitialized(length, characterBuffer);
715
716     for (unsigned i = 0; i < length; ++i) {
717         UChar ch = characters[i];
718         characterBuffer[i] = ch && (ch < 0x20 || ch > 0x7f) ? '?' : static_cast<char>(ch);
719     }
720
721     return result;
722 }
723
724 CString String::latin1() const
725 {
726     // Basic Latin1 (ISO) encoding - Unicode characters 0..255 are
727     // preserved, characters outside of this range are converted to '?'.
728
729     unsigned length = this->length();
730
731     if (!length)
732         return CString("", 0);
733
734     if (is8Bit())
735         return CString(reinterpret_cast<const char*>(this->characters8()), length);
736
737     const UChar* characters = this->characters16();
738
739     char* characterBuffer;
740     CString result = CString::newUninitialized(length, characterBuffer);
741
742     for (unsigned i = 0; i < length; ++i) {
743         UChar ch = characters[i];
744         characterBuffer[i] = ch > 0xff ? '?' : static_cast<char>(ch);
745     }
746
747     return result;
748 }
749
750 // Helper to write a three-byte UTF-8 code point to the buffer, caller must check room is available.
751 static inline void putUTF8Triple(char*& buffer, UChar ch)
752 {
753     ASSERT(ch >= 0x0800);
754     *buffer++ = static_cast<char>(((ch >> 12) & 0x0F) | 0xE0);
755     *buffer++ = static_cast<char>(((ch >> 6) & 0x3F) | 0x80);
756     *buffer++ = static_cast<char>((ch & 0x3F) | 0x80);
757 }
758
759 CString String::utf8(UTF8ConversionMode mode) const
760 {
761     unsigned length = this->length();
762
763     if (!length)
764         return CString("", 0);
765
766     // Allocate a buffer big enough to hold all the characters
767     // (an individual UTF-16 UChar can only expand to 3 UTF-8 bytes).
768     // Optimization ideas, if we find this function is hot:
769     //  * We could speculatively create a CStringBuffer to contain 'length'
770     //    characters, and resize if necessary (i.e. if the buffer contains
771     //    non-ascii characters). (Alternatively, scan the buffer first for
772     //    ascii characters, so we know this will be sufficient).
773     //  * We could allocate a CStringBuffer with an appropriate size to
774     //    have a good chance of being able to write the string into the
775     //    buffer without reallocing (say, 1.5 x length).
776     if (length > numeric_limits<unsigned>::max() / 3)
777         return CString();
778     Vector<char, 1024> bufferVector(length * 3);
779
780     char* buffer = bufferVector.data();
781
782     if (is8Bit()) {
783         const LChar* characters = this->characters8();
784
785         ConversionResult result = convertLatin1ToUTF8(&characters, characters + length, &buffer, buffer + bufferVector.size());
786         ASSERT_UNUSED(result, result != targetExhausted); // (length * 3) should be sufficient for any conversion
787     } else {
788         const UChar* characters = this->characters16();
789
790         if (mode == StrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD) {
791             const UChar* charactersEnd = characters + length;
792             char* bufferEnd = buffer + bufferVector.size();
793             while (characters < charactersEnd) {
794                 // Use strict conversion to detect unpaired surrogates.
795                 ConversionResult result = convertUTF16ToUTF8(&characters, charactersEnd, &buffer, bufferEnd, true);
796                 ASSERT(result != targetExhausted);
797                 // Conversion fails when there is an unpaired surrogate.
798                 // Put replacement character (U+FFFD) instead of the unpaired surrogate.
799                 if (result != conversionOK) {
800                     ASSERT((0xD800 <= *characters && *characters <= 0xDFFF));
801                     // There should be room left, since one UChar hasn't been converted.
802                     ASSERT((buffer + 3) <= bufferEnd);
803                     putUTF8Triple(buffer, replacementCharacter);
804                     ++characters;
805                 }
806             }
807         } else {
808             bool strict = mode == StrictUTF8Conversion;
809             ConversionResult result = convertUTF16ToUTF8(&characters, characters + length, &buffer, buffer + bufferVector.size(), strict);
810             ASSERT(result != targetExhausted); // (length * 3) should be sufficient for any conversion
811
812             // Only produced from strict conversion.
813             if (result == sourceIllegal) {
814                 ASSERT(strict);
815                 return CString();
816             }
817
818             // Check for an unconverted high surrogate.
819             if (result == sourceExhausted) {
820                 if (strict)
821                     return CString();
822                 // This should be one unpaired high surrogate. Treat it the same
823                 // was as an unpaired high surrogate would have been handled in
824                 // the middle of a string with non-strict conversion - which is
825                 // to say, simply encode it to UTF-8.
826                 ASSERT((characters + 1) == (this->characters16() + length));
827                 ASSERT((*characters >= 0xD800) && (*characters <= 0xDBFF));
828                 // There should be room left, since one UChar hasn't been converted.
829                 ASSERT((buffer + 3) <= (buffer + bufferVector.size()));
830                 putUTF8Triple(buffer, *characters);
831             }
832         }
833     }
834
835     return CString(bufferVector.data(), buffer - bufferVector.data());
836 }
837
838 String String::make8BitFrom16BitSource(const UChar* source, size_t length)
839 {
840     if (!length)
841         return emptyString();
842
843     LChar* destination;
844     String result = String::createUninitialized(length, destination);
845
846     copyLCharsFromUCharSource(destination, source, length);
847
848     return result;
849 }
850
851 String String::make16BitFrom8BitSource(const LChar* source, size_t length)
852 {
853     if (!length)
854         return emptyString16Bit();
855
856     UChar* destination;
857     String result = String::createUninitialized(length, destination);
858
859     StringImpl::copyChars(destination, source, length);
860
861     return result;
862 }
863
864 String String::fromUTF8(const LChar* stringStart, size_t length)
865 {
866     RELEASE_ASSERT(length <= numeric_limits<unsigned>::max());
867
868     if (!stringStart)
869         return String();
870
871     if (!length)
872         return emptyString();
873
874     if (charactersAreAllASCII(stringStart, length))
875         return StringImpl::create(stringStart, length);
876
877     Vector<UChar, 1024> buffer(length);
878     UChar* bufferStart = buffer.data();
879
880     UChar* bufferCurrent = bufferStart;
881     const char* stringCurrent = reinterpret_cast<const char*>(stringStart);
882     if (convertUTF8ToUTF16(&stringCurrent, reinterpret_cast<const char *>(stringStart + length), &bufferCurrent, bufferCurrent + buffer.size()) != conversionOK)
883         return String();
884
885     unsigned utf16Length = bufferCurrent - bufferStart;
886     ASSERT(utf16Length < length);
887     return StringImpl::create(bufferStart, utf16Length);
888 }
889
890 String String::fromUTF8(const LChar* string)
891 {
892     if (!string)
893         return String();
894     return fromUTF8(string, strlen(reinterpret_cast<const char*>(string)));
895 }
896
897 String String::fromUTF8(const CString& s)
898 {
899     return fromUTF8(s.data());
900 }
901
902 String String::fromUTF8WithLatin1Fallback(const LChar* string, size_t size)
903 {
904     String utf8 = fromUTF8(string, size);
905     if (!utf8)
906         return String(string, size);
907     return utf8;
908 }
909
910 // String Operations
911
912 static bool isCharacterAllowedInBase(UChar c, int base)
913 {
914     if (c > 0x7F)
915         return false;
916     if (isASCIIDigit(c))
917         return c - '0' < base;
918     if (isASCIIAlpha(c)) {
919         if (base > 36)
920             base = 36;
921         return (c >= 'a' && c < 'a' + base - 10)
922             || (c >= 'A' && c < 'A' + base - 10);
923     }
924     return false;
925 }
926
927 template <typename IntegralType, typename CharType>
928 static inline IntegralType toIntegralType(const CharType* data, size_t length, bool* ok, int base)
929 {
930     static const IntegralType integralMax = numeric_limits<IntegralType>::max();
931     static const bool isSigned = numeric_limits<IntegralType>::is_signed;
932     const IntegralType maxMultiplier = integralMax / base;
933
934     IntegralType value = 0;
935     bool isOk = false;
936     bool isNegative = false;
937
938     if (!data)
939         goto bye;
940
941     // skip leading whitespace
942     while (length && isSpaceOrNewline(*data)) {
943         --length;
944         ++data;
945     }
946
947     if (isSigned && length && *data == '-') {
948         --length;
949         ++data;
950         isNegative = true;
951     } else if (length && *data == '+') {
952         --length;
953         ++data;
954     }
955
956     if (!length || !isCharacterAllowedInBase(*data, base))
957         goto bye;
958
959     while (length && isCharacterAllowedInBase(*data, base)) {
960         --length;
961         IntegralType digitValue;
962         CharType c = *data;
963         if (isASCIIDigit(c))
964             digitValue = c - '0';
965         else if (c >= 'a')
966             digitValue = c - 'a' + 10;
967         else
968             digitValue = c - 'A' + 10;
969
970         if (value > maxMultiplier || (value == maxMultiplier && digitValue > (integralMax % base) + isNegative))
971             goto bye;
972
973         value = base * value + digitValue;
974         ++data;
975     }
976
977 #if COMPILER(MSVC)
978 #pragma warning(push, 0)
979 #pragma warning(disable:4146)
980 #endif
981
982     if (isNegative)
983         value = -value;
984
985 #if COMPILER(MSVC)
986 #pragma warning(pop)
987 #endif
988
989     // skip trailing space
990     while (length && isSpaceOrNewline(*data)) {
991         --length;
992         ++data;
993     }
994
995     if (!length)
996         isOk = true;
997 bye:
998     if (ok)
999         *ok = isOk;
1000     return isOk ? value : 0;
1001 }
1002
1003 template <typename CharType>
1004 static unsigned lengthOfCharactersAsInteger(const CharType* data, size_t length)
1005 {
1006     size_t i = 0;
1007
1008     // Allow leading spaces.
1009     for (; i != length; ++i) {
1010         if (!isSpaceOrNewline(data[i]))
1011             break;
1012     }
1013
1014     // Allow sign.
1015     if (i != length && (data[i] == '+' || data[i] == '-'))
1016         ++i;
1017
1018     // Allow digits.
1019     for (; i != length; ++i) {
1020         if (!isASCIIDigit(data[i]))
1021             break;
1022     }
1023
1024     return i;
1025 }
1026
1027 int charactersToIntStrict(const LChar* data, size_t length, bool* ok, int base)
1028 {
1029     return toIntegralType<int, LChar>(data, length, ok, base);
1030 }
1031
1032 int charactersToIntStrict(const UChar* data, size_t length, bool* ok, int base)
1033 {
1034     return toIntegralType<int, UChar>(data, length, ok, base);
1035 }
1036
1037 unsigned charactersToUIntStrict(const LChar* data, size_t length, bool* ok, int base)
1038 {
1039     return toIntegralType<unsigned, LChar>(data, length, ok, base);
1040 }
1041
1042 unsigned charactersToUIntStrict(const UChar* data, size_t length, bool* ok, int base)
1043 {
1044     return toIntegralType<unsigned, UChar>(data, length, ok, base);
1045 }
1046
1047 int64_t charactersToInt64Strict(const LChar* data, size_t length, bool* ok, int base)
1048 {
1049     return toIntegralType<int64_t, LChar>(data, length, ok, base);
1050 }
1051
1052 int64_t charactersToInt64Strict(const UChar* data, size_t length, bool* ok, int base)
1053 {
1054     return toIntegralType<int64_t, UChar>(data, length, ok, base);
1055 }
1056
1057 uint64_t charactersToUInt64Strict(const LChar* data, size_t length, bool* ok, int base)
1058 {
1059     return toIntegralType<uint64_t, LChar>(data, length, ok, base);
1060 }
1061
1062 uint64_t charactersToUInt64Strict(const UChar* data, size_t length, bool* ok, int base)
1063 {
1064     return toIntegralType<uint64_t, UChar>(data, length, ok, base);
1065 }
1066
1067 int charactersToInt(const LChar* data, size_t length, bool* ok)
1068 {
1069     return toIntegralType<int, LChar>(data, lengthOfCharactersAsInteger<LChar>(data, length), ok, 10);
1070 }
1071
1072 int charactersToInt(const UChar* data, size_t length, bool* ok)
1073 {
1074     return toIntegralType<int, UChar>(data, lengthOfCharactersAsInteger(data, length), ok, 10);
1075 }
1076
1077 unsigned charactersToUInt(const LChar* data, size_t length, bool* ok)
1078 {
1079     return toIntegralType<unsigned, LChar>(data, lengthOfCharactersAsInteger<LChar>(data, length), ok, 10);
1080 }
1081
1082 unsigned charactersToUInt(const UChar* data, size_t length, bool* ok)
1083 {
1084     return toIntegralType<unsigned, UChar>(data, lengthOfCharactersAsInteger<UChar>(data, length), ok, 10);
1085 }
1086
1087 int64_t charactersToInt64(const LChar* data, size_t length, bool* ok)
1088 {
1089     return toIntegralType<int64_t, LChar>(data, lengthOfCharactersAsInteger<LChar>(data, length), ok, 10);
1090 }
1091
1092 int64_t charactersToInt64(const UChar* data, size_t length, bool* ok)
1093 {
1094     return toIntegralType<int64_t, UChar>(data, lengthOfCharactersAsInteger<UChar>(data, length), ok, 10);
1095 }
1096
1097 uint64_t charactersToUInt64(const LChar* data, size_t length, bool* ok)
1098 {
1099     return toIntegralType<uint64_t, LChar>(data, lengthOfCharactersAsInteger<LChar>(data, length), ok, 10);
1100 }
1101
1102 uint64_t charactersToUInt64(const UChar* data, size_t length, bool* ok)
1103 {
1104     return toIntegralType<uint64_t, UChar>(data, lengthOfCharactersAsInteger<UChar>(data, length), ok, 10);
1105 }
1106
1107 enum TrailingJunkPolicy { DisallowTrailingJunk, AllowTrailingJunk };
1108
1109 template <typename CharType, TrailingJunkPolicy policy>
1110 static inline double toDoubleType(const CharType* data, size_t length, bool* ok, size_t& parsedLength)
1111 {
1112     size_t leadingSpacesLength = 0;
1113     while (leadingSpacesLength < length && isASCIISpace(data[leadingSpacesLength]))
1114         ++leadingSpacesLength;
1115
1116     double number = parseDouble(data + leadingSpacesLength, length - leadingSpacesLength, parsedLength);
1117     if (!parsedLength) {
1118         if (ok)
1119             *ok = false;
1120         return 0.0;
1121     }
1122
1123     parsedLength += leadingSpacesLength;
1124     if (ok)
1125         *ok = policy == AllowTrailingJunk || parsedLength == length;
1126     return number;
1127 }
1128
1129 double charactersToDouble(const LChar* data, size_t length, bool* ok)
1130 {
1131     size_t parsedLength;
1132     return toDoubleType<LChar, DisallowTrailingJunk>(data, length, ok, parsedLength);
1133 }
1134
1135 double charactersToDouble(const UChar* data, size_t length, bool* ok)
1136 {
1137     size_t parsedLength;
1138     return toDoubleType<UChar, DisallowTrailingJunk>(data, length, ok, parsedLength);
1139 }
1140
1141 float charactersToFloat(const LChar* data, size_t length, bool* ok)
1142 {
1143     // FIXME: This will return ok even when the string fits into a double but not a float.
1144     size_t parsedLength;
1145     return static_cast<float>(toDoubleType<LChar, DisallowTrailingJunk>(data, length, ok, parsedLength));
1146 }
1147
1148 float charactersToFloat(const UChar* data, size_t length, bool* ok)
1149 {
1150     // FIXME: This will return ok even when the string fits into a double but not a float.
1151     size_t parsedLength;
1152     return static_cast<float>(toDoubleType<UChar, DisallowTrailingJunk>(data, length, ok, parsedLength));
1153 }
1154
1155 float charactersToFloat(const LChar* data, size_t length, size_t& parsedLength)
1156 {
1157     // FIXME: This will return ok even when the string fits into a double but not a float.
1158     return static_cast<float>(toDoubleType<LChar, AllowTrailingJunk>(data, length, 0, parsedLength));
1159 }
1160
1161 float charactersToFloat(const UChar* data, size_t length, size_t& parsedLength)
1162 {
1163     // FIXME: This will return ok even when the string fits into a double but not a float.
1164     return static_cast<float>(toDoubleType<UChar, AllowTrailingJunk>(data, length, 0, parsedLength));
1165 }
1166
1167 const String& emptyString()
1168 {
1169     DEFINE_STATIC_LOCAL(String, emptyString, (StringImpl::empty()));
1170     return emptyString;
1171 }
1172
1173 const String& emptyString16Bit()
1174 {
1175     DEFINE_STATIC_LOCAL(String, emptyString, (StringImpl::empty16Bit()));
1176     return emptyString;
1177 }
1178
1179 } // namespace WTF
1180
1181 #ifndef NDEBUG
1182 // For use in the debugger
1183 String* string(const char*);
1184 Vector<char> asciiDebug(StringImpl* impl);
1185 Vector<char> asciiDebug(String& string);
1186
1187 void String::show() const
1188 {
1189     dataLogF("%s\n", asciiDebug(impl()).data());
1190 }
1191
1192 String* string(const char* s)
1193 {
1194     // leaks memory!
1195     return new String(s);
1196 }
1197
1198 Vector<char> asciiDebug(StringImpl* impl)
1199 {
1200     if (!impl)
1201         return asciiDebug(String("[null]").impl());
1202
1203     Vector<char> buffer;
1204     for (unsigned i = 0; i < impl->length(); ++i) {
1205         UChar ch = (*impl)[i];
1206         if (isASCIIPrintable(ch)) {
1207             if (ch == '\\')
1208                 buffer.append('\\');
1209             buffer.append(static_cast<char>(ch));
1210         } else {
1211             buffer.append('\\');
1212             buffer.append('u');
1213             appendUnsignedAsHexFixedSize(ch, buffer, 4);
1214         }
1215     }
1216     buffer.append('\0');
1217     return buffer;
1218 }
1219
1220 Vector<char> asciiDebug(String& string)
1221 {
1222     return asciiDebug(string.impl());
1223 }
1224
1225 #endif