1 // -*- c-basic-offset: 2 -*-
3 * This file is part of the KDE libraries
4 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
5 * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
29 #include "collector.h"
32 #include "identifier.h"
33 #include "operations.h"
40 #include <wtf/Vector.h>
54 extern const double NaN;
55 extern const double Inf;
57 static const size_t overflowIndicator = std::numeric_limits<size_t>::max();
58 static const size_t maxUChars = std::numeric_limits<size_t>::max() / sizeof(UChar);
60 static inline UChar* allocChars(size_t length)
63 if (length > maxUChars)
65 return static_cast<UChar*>(fastMalloc(sizeof(UChar) * length));
68 static inline UChar* reallocChars(UChar* buffer, size_t length)
71 if (length > maxUChars)
73 return static_cast<UChar*>(fastRealloc(buffer, sizeof(UChar) * length));
76 // we'd rather not do shared substring append for small strings, since
77 // this runs too much risk of a tiny initial string holding down a
78 // huge buffer. This is also tuned to match the extra cost size, so we
79 // don't ever share a buffer that wouldn't be over the extra cost
81 // FIXME: this should be size_t but that would cause warnings until we
82 // fix UString sizes to be size_t instad of int
83 static const int minShareSize = Collector::minExtraCostSize / sizeof(UChar);
85 COMPILE_ASSERT(sizeof(UChar) == 2, uchar_is_2_bytes)
87 CString::CString(const char *c)
90 data = new char[length+1];
91 memcpy(data, c, length + 1);
94 CString::CString(const char *c, size_t len)
97 data = new char[len+1];
102 CString::CString(const CString &b)
106 data = new char[length+1];
107 memcpy(data, b.data, length + 1);
118 CString &CString::append(const CString &t)
121 n = new char[length+t.length+1];
123 memcpy(n, data, length);
125 memcpy(n+length, t.data, t.length);
135 CString &CString::operator=(const char *c)
140 data = new char[length+1];
141 memcpy(data, c, length + 1);
146 CString &CString::operator=(const CString &str)
155 data = new char[length + 1];
156 memcpy(data, str.data, length + 1);
164 bool operator==(const CString& c1, const CString& c2)
166 size_t len = c1.size();
167 return len == c2.size() && (len == 0 || memcmp(c1.c_str(), c2.c_str(), len) == 0);
170 // Hack here to avoid a global with a constructor; point to an unsigned short instead of a UChar.
171 static unsigned short almostUChar;
172 UString::Rep UString::Rep::null = { 0, 0, 1, 0, 0, &UString::Rep::null, 0, 0, 0, 0, 0 };
173 UString::Rep UString::Rep::empty = { 0, 0, 1, 0, 0, &UString::Rep::empty, reinterpret_cast<UChar*>(&almostUChar), 0, 0, 0, 0 };
174 const int normalStatBufferSize = 4096;
175 static char *statBuffer = 0;
176 static int statBufferSize = 0;
178 PassRefPtr<UString::Rep> UString::Rep::createCopying(const UChar *d, int l)
180 ASSERT(JSLock::lockCount() > 0);
182 int sizeInBytes = l * sizeof(UChar);
183 UChar *copyD = static_cast<UChar *>(fastMalloc(sizeInBytes));
184 memcpy(copyD, d, sizeInBytes);
186 return create(copyD, l);
189 PassRefPtr<UString::Rep> UString::Rep::create(UChar *d, int l)
191 ASSERT(JSLock::lockCount() > 0);
203 r->usedPreCapacity = 0;
206 // steal the single reference this Rep was created with
210 PassRefPtr<UString::Rep> UString::Rep::create(PassRefPtr<Rep> base, int offset, int length)
212 ASSERT(JSLock::lockCount() > 0);
215 int baseOffset = base->offset;
217 base = base->baseString;
219 assert(-(offset + baseOffset) <= base->usedPreCapacity);
220 assert(offset + baseOffset + length <= base->usedCapacity);
223 r->offset = baseOffset + offset;
228 r->baseString = base.releaseRef();
232 r->usedPreCapacity = 0;
235 // steal the single reference this Rep was created with
239 void UString::Rep::destroy()
241 ASSERT(JSLock::lockCount() > 0);
244 Identifier::remove(this);
245 if (baseString != this) {
253 // Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
254 // or anything like that.
255 const unsigned PHI = 0x9e3779b9U;
257 // Paul Hsieh's SuperFastHash
258 // http://www.azillionmonkeys.com/qed/hash.html
259 unsigned UString::Rep::computeHash(const UChar *s, int len)
271 tmp = (s[1].uc << 11) ^ hash;
272 hash = (hash << 16) ^ tmp;
284 // Force "avalanching" of final 127 bits
291 // this avoids ever returning a hash code of 0, since that is used to
292 // signal "hash not computed yet", using a value that is likely to be
293 // effectively the same as 0 when the low bits are masked
300 // Paul Hsieh's SuperFastHash
301 // http://www.azillionmonkeys.com/qed/hash.html
302 unsigned UString::Rep::computeHash(const char *s)
304 // This hash is designed to work on 16-bit chunks at a time. But since the normal case
305 // (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
306 // were 16-bit chunks, which should give matching results
310 size_t l = strlen(s);
317 hash += (unsigned char)s[0];
318 tmp = ((unsigned char)s[1] << 11) ^ hash;
319 hash = (hash << 16) ^ tmp;
326 hash += (unsigned char)s[0];
331 // Force "avalanching" of final 127 bits
338 // this avoids ever returning a hash code of 0, since that is used to
339 // signal "hash not computed yet", using a value that is likely to be
340 // effectively the same as 0 when the low bits are masked
347 // put these early so they can be inlined
348 inline size_t UString::expandedSize(size_t size, size_t otherSize) const
350 // Do the size calculation in two parts, returning overflowIndicator if
351 // we overflow the maximum value that we can handle.
353 if (size > maxUChars)
354 return overflowIndicator;
356 size_t expandedSize = ((size + 10) / 10 * 11) + 1;
357 if (maxUChars - expandedSize < otherSize)
358 return overflowIndicator;
360 return expandedSize + otherSize;
363 inline int UString::usedCapacity() const
365 return m_rep->baseString->usedCapacity;
368 inline int UString::usedPreCapacity() const
370 return m_rep->baseString->usedPreCapacity;
373 void UString::expandCapacity(int requiredLength)
375 Rep* r = m_rep->baseString;
377 if (requiredLength > r->capacity) {
378 size_t newCapacity = expandedSize(requiredLength, r->preCapacity);
379 UChar* oldBuf = r->buf;
380 r->buf = reallocChars(r->buf, newCapacity);
386 r->capacity = newCapacity - r->preCapacity;
388 if (requiredLength > r->usedCapacity) {
389 r->usedCapacity = requiredLength;
393 void UString::expandPreCapacity(int requiredPreCap)
395 Rep* r = m_rep->baseString;
397 if (requiredPreCap > r->preCapacity) {
398 size_t newCapacity = expandedSize(requiredPreCap, r->capacity);
399 int delta = newCapacity - r->capacity - r->preCapacity;
401 UChar* newBuf = allocChars(newCapacity);
406 memcpy(newBuf + delta, r->buf, (r->capacity + r->preCapacity) * sizeof(UChar));
410 r->preCapacity = newCapacity - r->capacity;
412 if (requiredPreCap > r->usedPreCapacity) {
413 r->usedPreCapacity = requiredPreCap;
417 UString::UString(const char *c)
423 size_t length = strlen(c);
428 UChar *d = allocChars(length);
432 for (size_t i = 0; i < length; i++)
434 m_rep = Rep::create(d, static_cast<int>(length));
438 UString::UString(const UChar *c, int length)
443 m_rep = Rep::createCopying(c, length);
446 UString::UString(UChar *c, int length, bool copy)
451 m_rep = Rep::createCopying(c, length);
453 m_rep = Rep::create(c, length);
456 UString::UString(const UString &a, const UString &b)
458 int aSize = a.size();
459 int aOffset = a.m_rep->offset;
460 int bSize = b.size();
461 int bOffset = b.m_rep->offset;
462 int length = aSize + bSize;
469 } else if (bSize == 0) {
472 } else if (aOffset + aSize == a.usedCapacity() && aSize >= minShareSize && 4 * aSize >= bSize &&
473 (-bOffset != b.usedPreCapacity() || aSize >= bSize)) {
474 // - a reaches the end of its buffer so it qualifies for shared append
475 // - also, it's at least a quarter the length of b - appending to a much shorter
476 // string does more harm than good
477 // - however, if b qualifies for prepend and is longer than a, we'd rather prepend
479 x.expandCapacity(aOffset + length);
480 if (a.data() && x.data()) {
481 memcpy(const_cast<UChar *>(a.data() + aSize), b.data(), bSize * sizeof(UChar));
482 m_rep = Rep::create(a.m_rep, 0, length);
485 } else if (-bOffset == b.usedPreCapacity() && bSize >= minShareSize && 4 * bSize >= aSize) {
486 // - b reaches the beginning of its buffer so it qualifies for shared prepend
487 // - also, it's at least a quarter the length of a - prepending to a much shorter
488 // string does more harm than good
490 y.expandPreCapacity(-bOffset + aSize);
491 if (b.data() && y.data()) {
492 memcpy(const_cast<UChar *>(b.data() - aSize), a.data(), aSize * sizeof(UChar));
493 m_rep = Rep::create(b.m_rep, -aSize, length);
497 // a does not qualify for append, and b does not qualify for prepend, gotta make a whole new string
498 size_t newCapacity = expandedSize(length, 0);
499 UChar* d = allocChars(newCapacity);
503 memcpy(d, a.data(), aSize * sizeof(UChar));
504 memcpy(d + aSize, b.data(), bSize * sizeof(UChar));
505 m_rep = Rep::create(d, length);
506 m_rep->capacity = newCapacity;
511 const UString& UString::null()
513 static UString* n = new UString;
517 UString UString::from(int i)
519 UChar buf[1 + sizeof(i) * 3];
520 UChar *end = buf + sizeof(buf) / sizeof(UChar);
525 } else if (i == INT_MIN) {
526 char minBuf[1 + sizeof(i) * 3];
527 sprintf(minBuf, "%d", INT_MIN);
528 return UString(minBuf);
530 bool negative = false;
536 *--p = (unsigned short)((i % 10) + '0');
544 return UString(p, static_cast<int>(end - p));
547 UString UString::from(unsigned int u)
549 UChar buf[sizeof(u) * 3];
550 UChar *end = buf + sizeof(buf) / sizeof(UChar);
557 *--p = (unsigned short)((u % 10) + '0');
562 return UString(p, static_cast<int>(end - p));
565 UString UString::from(long l)
567 UChar buf[1 + sizeof(l) * 3];
568 UChar *end = buf + sizeof(buf) / sizeof(UChar);
573 } else if (l == LONG_MIN) {
574 char minBuf[1 + sizeof(l) * 3];
575 sprintf(minBuf, "%ld", LONG_MIN);
576 return UString(minBuf);
578 bool negative = false;
584 *--p = (unsigned short)((l % 10) + '0');
592 return UString(p, static_cast<int>(end - p));
595 UString UString::from(double d)
597 // avoid ever printing -NaN, in JS conceptually there is only one NaN value
605 char *result = kjs_dtoa(d, 0, 0, &decimalPoint, &sign, NULL);
606 int length = static_cast<int>(strlen(result));
613 if (decimalPoint <= 0 && decimalPoint > -6) {
616 for (int j = decimalPoint; j < 0; j++) {
619 strcpy(buf + i, result);
620 } else if (decimalPoint <= 21 && decimalPoint > 0) {
621 if (length <= decimalPoint) {
622 strcpy(buf + i, result);
624 for (int j = 0; j < decimalPoint - length; j++) {
629 strncpy(buf + i, result, decimalPoint);
632 strcpy(buf + i, result + decimalPoint);
634 } else if (result[0] < '0' || result[0] > '9') {
635 strcpy(buf + i, result);
637 buf[i++] = result[0];
640 strcpy(buf + i, result + 1);
645 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
646 // decimalPoint can't be more than 3 digits decimal given the
647 // nature of float representation
648 int exponential = decimalPoint - 1;
650 exponential = -exponential;
651 if (exponential >= 100)
652 buf[i++] = static_cast<char>('0' + exponential / 100);
653 if (exponential >= 10)
654 buf[i++] = static_cast<char>('0' + (exponential % 100) / 10);
655 buf[i++] = static_cast<char>('0' + exponential % 10);
659 kjs_freedtoa(result);
664 UString UString::spliceSubstringsWithSeparators(const Range* substringRanges, int rangeCount, const UString* separators, int separatorCount) const
666 if (rangeCount == 1 && separatorCount == 0) {
667 int thisSize = size();
668 int position = substringRanges[0].position;
669 int length = substringRanges[0].length;
670 if (position <= 0 && length >= thisSize)
672 return UString::Rep::create(m_rep, max(0, position), min(thisSize, length));
676 for (int i = 0; i < rangeCount; i++)
677 totalLength += substringRanges[i].length;
678 for (int i = 0; i < separatorCount; i++)
679 totalLength += separators[i].size();
681 if (totalLength == 0)
684 UChar* buffer = allocChars(totalLength);
688 int maxCount = max(rangeCount, separatorCount);
690 for (int i = 0; i < maxCount; i++) {
691 if (i < rangeCount) {
692 memcpy(buffer + bufferPos, data() + substringRanges[i].position, substringRanges[i].length * sizeof(UChar));
693 bufferPos += substringRanges[i].length;
695 if (i < separatorCount) {
696 memcpy(buffer + bufferPos, separators[i].data(), separators[i].size() * sizeof(UChar));
697 bufferPos += separators[i].size();
701 return UString::Rep::create(buffer, totalLength);
704 UString &UString::append(const UString &t)
706 int thisSize = size();
707 int thisOffset = m_rep->offset;
708 int tSize = t.size();
709 int length = thisSize + tSize;
715 } else if (tSize == 0) {
717 } else if (m_rep->baseIsSelf() && m_rep->rc == 1) {
718 // this is direct and has refcount of 1 (so we can just alter it directly)
719 expandCapacity(thisOffset + length);
721 memcpy(const_cast<UChar*>(data() + thisSize), t.data(), tSize * sizeof(UChar));
725 } else if (thisOffset + thisSize == usedCapacity() && thisSize >= minShareSize) {
726 // this reaches the end of the buffer - extend it if it's long enough to append to
727 expandCapacity(thisOffset + length);
729 memcpy(const_cast<UChar*>(data() + thisSize), t.data(), tSize * sizeof(UChar));
730 m_rep = Rep::create(m_rep, 0, length);
733 // this is shared with someone using more capacity, gotta make a whole new string
734 size_t newCapacity = expandedSize(length, 0);
735 UChar* d = allocChars(newCapacity);
739 memcpy(d, data(), thisSize * sizeof(UChar));
740 memcpy(const_cast<UChar*>(d + thisSize), t.data(), tSize * sizeof(UChar));
741 m_rep = Rep::create(d, length);
742 m_rep->capacity = newCapacity;
749 UString &UString::append(const char *t)
751 int thisSize = size();
752 int thisOffset = m_rep->offset;
753 int tSize = static_cast<int>(strlen(t));
754 int length = thisSize + tSize;
760 } else if (tSize == 0) {
761 // t is empty, we'll just return *this below.
762 } else if (m_rep->baseIsSelf() && m_rep->rc == 1) {
763 // this is direct and has refcount of 1 (so we can just alter it directly)
764 expandCapacity(thisOffset + length);
765 UChar *d = const_cast<UChar *>(data());
767 for (int i = 0; i < tSize; ++i)
768 d[thisSize + i] = t[i];
772 } else if (thisOffset + thisSize == usedCapacity() && thisSize >= minShareSize) {
773 // this string reaches the end of the buffer - extend it
774 expandCapacity(thisOffset + length);
775 UChar *d = const_cast<UChar *>(data());
777 for (int i = 0; i < tSize; ++i)
778 d[thisSize + i] = t[i];
779 m_rep = Rep::create(m_rep, 0, length);
782 // this is shared with someone using more capacity, gotta make a whole new string
783 size_t newCapacity = expandedSize(length, 0);
784 UChar* d = allocChars(newCapacity);
788 memcpy(d, data(), thisSize * sizeof(UChar));
789 for (int i = 0; i < tSize; ++i)
790 d[thisSize + i] = t[i];
791 m_rep = Rep::create(d, length);
792 m_rep->capacity = newCapacity;
799 UString &UString::append(unsigned short c)
801 int thisOffset = m_rep->offset;
806 // this is empty - must make a new m_rep because we don't want to pollute the shared empty one
807 size_t newCapacity = expandedSize(1, 0);
808 UChar* d = allocChars(newCapacity);
813 m_rep = Rep::create(d, 1);
814 m_rep->capacity = newCapacity;
816 } else if (m_rep->baseIsSelf() && m_rep->rc == 1) {
817 // this is direct and has refcount of 1 (so we can just alter it directly)
818 expandCapacity(thisOffset + length + 1);
819 UChar *d = const_cast<UChar *>(data());
822 m_rep->len = length + 1;
825 } else if (thisOffset + length == usedCapacity() && length >= minShareSize) {
826 // this reaches the end of the string - extend it and share
827 expandCapacity(thisOffset + length + 1);
828 UChar *d = const_cast<UChar *>(data());
831 m_rep = Rep::create(m_rep, 0, length + 1);
834 // this is shared with someone using more capacity, gotta make a whole new string
835 size_t newCapacity = expandedSize(length + 1, 0);
836 UChar* d = allocChars(newCapacity);
840 memcpy(d, data(), length * sizeof(UChar));
842 m_rep = Rep::create(d, length + 1);
843 m_rep->capacity = newCapacity;
850 CString UString::cstring() const
855 char *UString::ascii() const
857 // Never make the buffer smaller than normalStatBufferSize.
858 // Thus we almost never need to reallocate.
860 int neededSize = length + 1;
861 if (neededSize < normalStatBufferSize) {
862 neededSize = normalStatBufferSize;
864 if (neededSize != statBufferSize) {
865 delete [] statBuffer;
866 statBuffer = new char [neededSize];
867 statBufferSize = neededSize;
870 const UChar *p = data();
871 char *q = statBuffer;
872 const UChar *limit = p + length;
874 *q = static_cast<char>(p->uc);
884 void UString::globalClear()
886 delete [] statBuffer;
892 UString &UString::operator=(const char *c)
899 int l = static_cast<int>(strlen(c));
906 if (m_rep->rc == 1 && l <= m_rep->capacity && m_rep->baseIsSelf() && m_rep->offset == 0 && m_rep->preCapacity == 0) {
916 m_rep = Rep::create(d, l);
918 for (int i = 0; i < l; i++)
924 bool UString::is8Bit() const
926 const UChar *u = data();
927 const UChar *limit = u + size();
937 const UChar UString::operator[](int pos) const
944 double UString::toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const
948 // FIXME: If tolerateTrailingJunk is true, then we want to tolerate non-8-bit junk
949 // after the number, so is8Bit is too strict a check.
953 const char *c = ascii();
955 // skip leading white space
961 return tolerateEmptyString ? 0.0 : NaN;
964 if (*c == '0' && (*(c+1) == 'x' || *(c+1) == 'X')) {
965 const char* firstDigitPosition = c + 2;
969 if (*c >= '0' && *c <= '9')
970 d = d * 16.0 + *c - '0';
971 else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f'))
972 d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0;
977 if (d >= mantissaOverflowLowerBound)
978 d = parseIntOverflow(firstDigitPosition, c - firstDigitPosition, 16);
982 d = kjs_strtod(c, &end);
983 if ((d != 0.0 || end != c) && d != Inf && d != -Inf) {
990 else if (*c == '-') {
995 // We used strtod() to do the conversion. However, strtod() handles
996 // infinite values slightly differently than JavaScript in that it
997 // converts the string "inf" with any capitalization to infinity,
998 // whereas the ECMA spec requires that it be converted to NaN.
1000 if (strncmp(c, "Infinity", 8) == 0) {
1003 } else if ((d == Inf || d == -Inf) && *c != 'I' && *c != 'i')
1010 // allow trailing white space
1013 // don't allow anything after - unless tolerant=true
1014 if (!tolerateTrailingJunk && *c != '\0')
1020 double UString::toDouble(bool tolerateTrailingJunk) const
1022 return toDouble(tolerateTrailingJunk, true);
1025 double UString::toDouble() const
1027 return toDouble(false, true);
1030 uint32_t UString::toUInt32(bool *ok) const
1032 double d = toDouble();
1035 if (d != static_cast<uint32_t>(d)) {
1043 return static_cast<uint32_t>(d);
1046 uint32_t UString::toUInt32(bool *ok, bool tolerateEmptyString) const
1048 double d = toDouble(false, tolerateEmptyString);
1051 if (d != static_cast<uint32_t>(d)) {
1059 return static_cast<uint32_t>(d);
1062 uint32_t UString::toStrictUInt32(bool *ok) const
1067 // Empty string is not OK.
1068 int len = m_rep->len;
1071 const UChar *p = m_rep->data();
1072 unsigned short c = p->unicode();
1074 // If the first digit is 0, only 0 itself is OK.
1081 // Convert to UInt32, checking for overflow.
1084 // Process character, turning it into a digit.
1085 if (c < '0' || c > '9')
1087 const unsigned d = c - '0';
1089 // Multiply by 10, checking for overflow out of 32 bits.
1090 if (i > 0xFFFFFFFFU / 10)
1094 // Add in the digit, checking for overflow out of 32 bits.
1095 const unsigned max = 0xFFFFFFFFU - d;
1100 // Handle end of string.
1107 // Get next character.
1108 c = (++p)->unicode();
1112 int UString::find(const UString &f, int pos) const
1122 const UChar *end = data() + sz - fsz;
1123 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1124 const UChar *fdata = f.data();
1125 unsigned short fchar = fdata->uc;
1127 for (const UChar *c = data() + pos; c <= end; c++)
1128 if (c->uc == fchar && !memcmp(c + 1, fdata, fsizeminusone))
1129 return static_cast<int>(c - data());
1134 int UString::find(UChar ch, int pos) const
1138 const UChar *end = data() + size();
1139 for (const UChar *c = data() + pos; c < end; c++)
1141 return static_cast<int>(c - data());
1146 int UString::rfind(const UString &f, int pos) const
1158 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1159 const UChar *fdata = f.data();
1160 for (const UChar *c = data() + pos; c >= data(); c--) {
1161 if (*c == *fdata && !memcmp(c + 1, fdata + 1, fsizeminusone))
1162 return static_cast<int>(c - data());
1168 int UString::rfind(UChar ch, int pos) const
1172 if (pos + 1 >= size())
1174 for (const UChar *c = data() + pos; c >= data(); c--) {
1176 return static_cast<int>(c-data());
1182 UString UString::substr(int pos, int len) const
1195 if (pos == 0 && len == s)
1198 return UString(Rep::create(m_rep, pos, len));
1201 bool operator==(const UString& s1, const UString& s2)
1203 if (s1.m_rep->len != s2.m_rep->len)
1206 return (memcmp(s1.m_rep->data(), s2.m_rep->data(),
1207 s1.m_rep->len * sizeof(UChar)) == 0);
1210 bool operator==(const UString& s1, const char *s2)
1213 return s1.isEmpty();
1216 const UChar *u = s1.data();
1217 const UChar *uend = u + s1.size();
1218 while (u != uend && *s2) {
1219 if (u->uc != (unsigned char)*s2)
1225 return u == uend && *s2 == 0;
1228 bool operator<(const UString& s1, const UString& s2)
1230 const int l1 = s1.size();
1231 const int l2 = s2.size();
1232 const int lmin = l1 < l2 ? l1 : l2;
1233 const UChar *c1 = s1.data();
1234 const UChar *c2 = s2.data();
1236 while (l < lmin && *c1 == *c2) {
1242 return (c1->uc < c2->uc);
1247 int compare(const UString& s1, const UString& s2)
1249 const int l1 = s1.size();
1250 const int l2 = s2.size();
1251 const int lmin = l1 < l2 ? l1 : l2;
1252 const UChar *c1 = s1.data();
1253 const UChar *c2 = s2.data();
1255 while (l < lmin && *c1 == *c2) {
1262 return (c1->uc > c2->uc) ? 1 : -1;
1267 return (l1 > l2) ? 1 : -1;
1270 inline int inlineUTF8SequenceLengthNonASCII(char b0)
1272 if ((b0 & 0xC0) != 0xC0)
1274 if ((b0 & 0xE0) == 0xC0)
1276 if ((b0 & 0xF0) == 0xE0)
1278 if ((b0 & 0xF8) == 0xF0)
1283 int UTF8SequenceLengthNonASCII(char b0)
1285 return inlineUTF8SequenceLengthNonASCII(b0);
1288 inline int inlineUTF8SequenceLength(char b0)
1290 return (b0 & 0x80) == 0 ? 1 : UTF8SequenceLengthNonASCII(b0);
1293 // Given a first byte, gives the length of the UTF-8 sequence it begins.
1294 // Returns 0 for bytes that are not legal starts of UTF-8 sequences.
1295 // Only allows sequences of up to 4 bytes, since that works for all Unicode characters (U-00000000 to U-0010FFFF).
1296 int UTF8SequenceLength(char b0)
1298 return (b0 & 0x80) == 0 ? 1 : inlineUTF8SequenceLengthNonASCII(b0);
1301 // Takes a null-terminated C-style string with a UTF-8 sequence in it and converts it to a character.
1302 // Only allows Unicode characters (U-00000000 to U-0010FFFF).
1303 // Returns -1 if the sequence is not valid (including presence of extra bytes).
1304 int decodeUTF8Sequence(const char *sequence)
1306 // Handle 0-byte sequences (never valid).
1307 const unsigned char b0 = sequence[0];
1308 const int length = inlineUTF8SequenceLength(b0);
1312 // Handle 1-byte sequences (plain ASCII).
1313 const unsigned char b1 = sequence[1];
1320 // Handle 2-byte sequences.
1321 if ((b1 & 0xC0) != 0x80)
1323 const unsigned char b2 = sequence[2];
1327 const int c = ((b0 & 0x1F) << 6) | (b1 & 0x3F);
1333 // Handle 3-byte sequences.
1334 if ((b2 & 0xC0) != 0x80)
1336 const unsigned char b3 = sequence[3];
1340 const int c = ((b0 & 0xF) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F);
1343 // UTF-16 surrogates should never appear in UTF-8 data.
1344 if (c >= 0xD800 && c <= 0xDFFF)
1346 // Backwards BOM and U+FFFF should never appear in UTF-8 data.
1347 if (c == 0xFFFE || c == 0xFFFF)
1352 // Handle 4-byte sequences.
1353 if ((b3 & 0xC0) != 0x80)
1355 const unsigned char b4 = sequence[4];
1359 const int c = ((b0 & 0x7) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);
1360 if (c < 0x10000 || c > 0x10FFFF)
1368 CString UString::UTF8String() const
1370 // Allocate a buffer big enough to hold all the characters.
1371 const int length = size();
1372 Vector<char, 1024> buffer(length * 3);
1374 // Convert to runs of 8-bit characters.
1375 char *p = buffer.begin();
1376 const UChar *d = data();
1377 for (int i = 0; i != length; ++i) {
1378 unsigned short c = d[i].unicode();
1381 } else if (c < 0x800) {
1382 *p++ = (char)((c >> 6) | 0xC0); // C0 is the 2-byte flag for UTF-8
1383 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1384 } else if (c >= 0xD800 && c <= 0xDBFF && i < length && d[i+1].uc >= 0xDC00 && d[i+1].uc <= 0xDFFF) {
1385 unsigned sc = 0x10000 + (((c & 0x3FF) << 10) | (d[i+1].uc & 0x3FF));
1386 *p++ = (char)((sc >> 18) | 0xF0); // F0 is the 4-byte flag for UTF-8
1387 *p++ = (char)(((sc >> 12) | 0x80) & 0xBF); // next 6 bits, with high bit set
1388 *p++ = (char)(((sc >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1389 *p++ = (char)((sc | 0x80) & 0xBF); // next 6 bits, with high bit set
1392 *p++ = (char)((c >> 12) | 0xE0); // E0 is the 3-byte flag for UTF-8
1393 *p++ = (char)(((c >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1394 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1398 // Return the result as a C string.
1399 CString result(buffer, p - buffer);