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 Apple Computer, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
38 #include "operations.h"
39 #include "identifier.h"
43 #include <kxmlcore/Vector.h>
47 #include <kxmlcore/unicode/Unicode.h>
51 extern const double NaN;
52 extern const double Inf;
54 CString::CString(const char *c)
57 data = new char[length+1];
58 memcpy(data, c, length + 1);
61 CString::CString(const char *c, int len)
64 data = new char[len+1];
69 CString::CString(const CString &b)
73 data = new char[length+1];
74 memcpy(data, b.data, length + 1);
85 CString &CString::append(const CString &t)
88 n = new char[length+t.length+1];
90 memcpy(n, data, length);
92 memcpy(n+length, t.data, t.length);
102 CString &CString::operator=(const char *c)
107 data = new char[length+1];
108 memcpy(data, c, length + 1);
113 CString &CString::operator=(const CString &str)
122 data = new char[length + 1];
123 memcpy(data, str.data, length + 1);
131 bool operator==(const CString& c1, const CString& c2)
134 return len == c2.size() && (len == 0 || memcmp(c1.c_str(), c2.c_str(), len) == 0);
137 // Hack here to avoid a global with a constructor; point to an unsigned short instead of a UChar.
138 static unsigned short almostUChar;
139 UString::Rep UString::Rep::null = { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
140 UString::Rep UString::Rep::empty = { 0, 0, 1, 0, 0, 0, reinterpret_cast<UChar*>(&almostUChar), 0, 0, 0, 0 };
141 const int normalStatBufferSize = 4096;
142 static char *statBuffer = 0;
143 static int statBufferSize = 0;
145 UChar UChar::toLower() const
147 return KXMLCore::Unicode::toLower(uc);
150 UChar UChar::toUpper() const
152 return KXMLCore::Unicode::toUpper(uc);
155 UCharReference& UCharReference::operator=(UChar c)
157 str->copyForWriting();
158 if (offset < str->rep()->len)
159 *(str->rep()->data() + offset) = c;
160 /* TODO: lengthen string ? */
164 UChar& UCharReference::ref() const
166 if (offset < str->rep()->len)
167 return *(str->rep()->data() + offset);
169 static UChar callerBetterNotModifyThis('\0');
170 return callerBetterNotModifyThis;
174 PassRefPtr<UString::Rep> UString::Rep::createCopying(const UChar *d, int l)
176 int sizeInBytes = l * sizeof(UChar);
177 UChar *copyD = static_cast<UChar *>(fastMalloc(sizeInBytes));
178 memcpy(copyD, d, sizeInBytes);
180 return create(copyD, l);
183 PassRefPtr<UString::Rep> UString::Rep::create(UChar *d, int l)
195 r->usedPreCapacity = 0;
198 // steal the single reference this Rep was created with
202 PassRefPtr<UString::Rep> UString::Rep::create(PassRefPtr<Rep> base, int offset, int length)
206 int baseOffset = base->offset;
208 if (base->baseString) {
209 base = base->baseString;
212 assert(-(offset + baseOffset) <= base->usedPreCapacity);
213 assert(offset + baseOffset + length <= base->usedCapacity);
216 r->offset = baseOffset + offset;
221 r->baseString = base.release();
225 r->usedPreCapacity = 0;
228 // steal the single reference this Rep was created with
232 void UString::Rep::destroy()
235 Identifier::remove(this);
244 // Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
245 // or anything like that.
246 const unsigned PHI = 0x9e3779b9U;
248 // Paul Hsieh's SuperFastHash
249 // http://www.azillionmonkeys.com/qed/hash.html
250 unsigned UString::Rep::computeHash(const UChar *s, int len)
262 tmp = (s[1].uc << 11) ^ hash;
263 hash = (hash << 16) ^ tmp;
275 // Force "avalanching" of final 127 bits
282 // this avoids ever returning a hash code of 0, since that is used to
283 // signal "hash not computed yet", using a value that is likely to be
284 // effectively the same as 0 when the low bits are masked
291 // Paul Hsieh's SuperFastHash
292 // http://www.azillionmonkeys.com/qed/hash.html
293 unsigned UString::Rep::computeHash(const char *s)
295 // This hash is designed to work on 16-bit chunks at a time. But since the normal case
296 // (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
297 // were 16-bit chunks, which should give matching results
301 unsigned l = strlen(s);
308 hash += (unsigned char)s[0];
309 tmp = ((unsigned char)s[1] << 11) ^ hash;
310 hash = (hash << 16) ^ tmp;
317 hash += (unsigned char)s[0];
322 // Force "avalanching" of final 127 bits
329 // this avoids ever returning a hash code of 0, since that is used to
330 // signal "hash not computed yet", using a value that is likely to be
331 // effectively the same as 0 when the low bits are masked
338 // put these early so they can be inlined
339 inline int UString::expandedSize(int size, int otherSize) const
341 int s = (size * 11 / 10) + 1 + otherSize;
345 inline int UString::usedCapacity() const
347 return m_rep->baseString ? m_rep->baseString->usedCapacity : m_rep->usedCapacity;
350 inline int UString::usedPreCapacity() const
352 return m_rep->baseString ? m_rep->baseString->usedPreCapacity : m_rep->usedPreCapacity;
355 void UString::expandCapacity(int requiredLength)
357 Rep *r = m_rep->baseString ? m_rep->baseString : rep();
359 if (requiredLength > r->capacity) {
360 int newCapacity = expandedSize(requiredLength, r->preCapacity);
361 r->buf = static_cast<UChar *>(fastRealloc(r->buf, newCapacity * sizeof(UChar)));
362 r->capacity = newCapacity - r->preCapacity;
364 if (requiredLength > r->usedCapacity) {
365 r->usedCapacity = requiredLength;
369 void UString::expandPreCapacity(int requiredPreCap)
371 Rep *r = m_rep->baseString ? m_rep->baseString : rep();
373 if (requiredPreCap > r->preCapacity) {
374 int newCapacity = expandedSize(requiredPreCap, r->capacity);
375 int delta = newCapacity - r->capacity - r->preCapacity;
377 UChar *newBuf = static_cast<UChar *>(fastMalloc(newCapacity * sizeof(UChar)));
378 memcpy(newBuf + delta, r->buf, (r->capacity + r->preCapacity) * sizeof(UChar));
382 r->preCapacity = newCapacity - r->capacity;
384 if (requiredPreCap > r->usedPreCapacity) {
385 r->usedPreCapacity = requiredPreCap;
390 UString::UString(char c)
392 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar)));
394 m_rep = Rep::create(d, 1);
397 UString::UString(const char *c)
403 int length = strlen(c);
408 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * length));
409 for (int i = 0; i < length; i++)
411 m_rep = Rep::create(d, length);
414 UString::UString(const UChar *c, int length)
419 m_rep = Rep::createCopying(c, length);
422 UString::UString(UChar *c, int length, bool copy)
427 m_rep = Rep::createCopying(c, length);
429 m_rep = Rep::create(c, length);
432 UString::UString(const UString &a, const UString &b)
434 int aSize = a.size();
435 int aOffset = a.m_rep->offset;
436 int bSize = b.size();
437 int bOffset = b.m_rep->offset;
438 int length = aSize + bSize;
445 } else if (bSize == 0) {
448 } else if (aOffset + aSize == a.usedCapacity() && 4 * aSize >= bSize &&
449 (-bOffset != b.usedPreCapacity() || aSize >= bSize)) {
450 // - a reaches the end of its buffer so it qualifies for shared append
451 // - also, it's at least a quarter the length of b - appending to a much shorter
452 // string does more harm than good
453 // - however, if b qualifies for prepend and is longer than a, we'd rather prepend
455 x.expandCapacity(aOffset + length);
456 memcpy(const_cast<UChar *>(a.data() + aSize), b.data(), bSize * sizeof(UChar));
457 m_rep = Rep::create(a.m_rep, 0, length);
458 } else if (-bOffset == b.usedPreCapacity() && 4 * bSize >= aSize) {
459 // - b reaches the beginning of its buffer so it qualifies for shared prepend
460 // - also, it's at least a quarter the length of a - prepending to a much shorter
461 // string does more harm than good
463 y.expandPreCapacity(-bOffset + aSize);
464 memcpy(const_cast<UChar *>(b.data() - aSize), a.data(), aSize * sizeof(UChar));
465 m_rep = Rep::create(b.m_rep, -aSize, length);
467 // a does not qualify for append, and b does not qualify for prepend, gotta make a whole new string
468 int newCapacity = expandedSize(length, 0);
469 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * newCapacity));
470 memcpy(d, a.data(), aSize * sizeof(UChar));
471 memcpy(d + aSize, b.data(), bSize * sizeof(UChar));
472 m_rep = Rep::create(d, length);
473 m_rep->capacity = newCapacity;
477 const UString &UString::null()
483 UString UString::from(int i)
485 UChar buf[1 + sizeof(i) * 3];
486 UChar *end = buf + sizeof(buf) / sizeof(UChar);
491 } else if (i == INT_MIN) {
492 char minBuf[1 + sizeof(i) * 3];
493 sprintf(minBuf, "%d", INT_MIN);
494 return UString(minBuf);
496 bool negative = false;
502 *--p = (unsigned short)((i % 10) + '0');
510 return UString(p, end - p);
513 UString UString::from(unsigned int u)
515 UChar buf[sizeof(u) * 3];
516 UChar *end = buf + sizeof(buf) / sizeof(UChar);
523 *--p = (unsigned short)((u % 10) + '0');
528 return UString(p, end - p);
531 UString UString::from(long l)
533 UChar buf[1 + sizeof(l) * 3];
534 UChar *end = buf + sizeof(buf) / sizeof(UChar);
539 } else if (l == LONG_MIN) {
540 char minBuf[1 + sizeof(l) * 3];
541 sprintf(minBuf, "%ld", LONG_MIN);
542 return UString(minBuf);
544 bool negative = false;
550 *--p = (unsigned short)((l % 10) + '0');
558 return UString(p, end - p);
561 UString UString::from(double d)
563 // avoid ever printing -NaN, in JS conceptually there is only one NaN value
571 char *result = kjs_dtoa(d, 0, 0, &decimalPoint, &sign, NULL);
572 int length = strlen(result);
579 if (decimalPoint <= 0 && decimalPoint > -6) {
582 for (int j = decimalPoint; j < 0; j++) {
585 strcpy(buf + i, result);
586 } else if (decimalPoint <= 21 && decimalPoint > 0) {
587 if (length <= decimalPoint) {
588 strcpy(buf + i, result);
590 for (int j = 0; j < decimalPoint - length; j++) {
595 strncpy(buf + i, result, decimalPoint);
598 strcpy(buf + i, result + decimalPoint);
600 } else if (result[0] < '0' || result[0] > '9') {
601 strcpy(buf + i, result);
603 buf[i++] = result[0];
606 strcpy(buf + i, result + 1);
611 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
612 // decimalPoint can't be more than 3 digits decimal given the
613 // nature of float representation
614 int exponential = decimalPoint - 1;
615 if (exponential < 0) {
616 exponential = exponential * -1;
618 if (exponential >= 100) {
619 buf[i++] = '0' + exponential / 100;
621 if (exponential >= 10) {
622 buf[i++] = '0' + (exponential % 100) / 10;
624 buf[i++] = '0' + exponential % 10;
628 kjs_freedtoa(result);
633 UString UString::spliceSubstringsWithSeparators(const Range *substringRanges, int rangeCount, const UString *separators, int separatorCount) const
637 for (int i = 0; i < rangeCount; i++) {
638 totalLength += substringRanges[i].length;
640 for (int i = 0; i < separatorCount; i++) {
641 totalLength += separators[i].size();
644 UChar *buffer = static_cast<UChar *>(fastMalloc(totalLength * sizeof(UChar)));
646 int maxCount = max(rangeCount, separatorCount);
648 for (int i = 0; i < maxCount; i++) {
649 if (i < rangeCount) {
650 memcpy(buffer + bufferPos, data() + substringRanges[i].position, substringRanges[i].length * sizeof(UChar));
651 bufferPos += substringRanges[i].length;
653 if (i < separatorCount) {
654 memcpy(buffer + bufferPos, separators[i].data(), separators[i].size() * sizeof(UChar));
655 bufferPos += separators[i].size();
659 return UString(UString::Rep::create(buffer, totalLength));
664 UString &UString::append(const UString &t)
666 int thisSize = size();
667 int thisOffset = m_rep->offset;
668 int tSize = t.size();
669 int length = thisSize + tSize;
675 } else if (tSize == 0) {
677 } else if (!m_rep->baseString && m_rep->rc == 1) {
678 // this is direct and has refcount of 1 (so we can just alter it directly)
679 expandCapacity(thisOffset + length);
680 memcpy(const_cast<UChar *>(data() + thisSize), t.data(), tSize * sizeof(UChar));
683 } else if (thisOffset + thisSize == usedCapacity()) {
684 // this reaches the end of the buffer - extend it
685 expandCapacity(thisOffset + length);
686 memcpy(const_cast<UChar *>(data() + thisSize), t.data(), tSize * sizeof(UChar));
687 m_rep = Rep::create(m_rep, 0, length);
689 // this is shared with someone using more capacity, gotta make a whole new string
690 int newCapacity = expandedSize(length, 0);
691 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * newCapacity));
692 memcpy(d, data(), thisSize * sizeof(UChar));
693 memcpy(const_cast<UChar *>(d + thisSize), t.data(), tSize * sizeof(UChar));
694 m_rep = Rep::create(d, length);
695 m_rep->capacity = newCapacity;
701 UString &UString::append(const char *t)
703 int thisSize = size();
704 int thisOffset = m_rep->offset;
705 int tSize = strlen(t);
706 int length = thisSize + tSize;
712 } else if (tSize == 0) {
713 // t is empty, we'll just return *this below.
714 } else if (!m_rep->baseString && m_rep->rc == 1) {
715 // this is direct and has refcount of 1 (so we can just alter it directly)
716 expandCapacity(thisOffset + length);
717 UChar *d = const_cast<UChar *>(data());
718 for (int i = 0; i < tSize; ++i)
719 d[thisSize+i] = t[i];
722 } else if (thisOffset + thisSize == usedCapacity()) {
723 // this string reaches the end of the buffer - extend it
724 expandCapacity(thisOffset + length);
725 UChar *d = const_cast<UChar *>(data());
726 for (int i = 0; i < tSize; ++i)
727 d[thisSize+i] = t[i];
728 m_rep = Rep::create(m_rep, 0, length);
730 // this is shared with someone using more capacity, gotta make a whole new string
731 int newCapacity = expandedSize(length, 0);
732 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * newCapacity));
733 memcpy(d, data(), thisSize * sizeof(UChar));
734 for (int i = 0; i < tSize; ++i)
735 d[thisSize+i] = t[i];
736 m_rep = Rep::create(d, length);
737 m_rep->capacity = newCapacity;
743 UString &UString::append(unsigned short c)
745 int thisOffset = m_rep->offset;
750 // this is empty - must make a new m_rep because we don't want to pollute the shared empty one
751 int newCapacity = expandedSize(1, 0);
752 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * newCapacity));
754 m_rep = Rep::create(d, 1);
755 m_rep->capacity = newCapacity;
756 } else if (!m_rep->baseString && m_rep->rc == 1) {
757 // this is direct and has refcount of 1 (so we can just alter it directly)
758 expandCapacity(thisOffset + length + 1);
759 UChar *d = const_cast<UChar *>(data());
761 m_rep->len = length + 1;
763 } else if (thisOffset + length == usedCapacity()) {
764 // this reaches the end of the string - extend it and share
765 expandCapacity(thisOffset + length + 1);
766 UChar *d = const_cast<UChar *>(data());
768 m_rep = Rep::create(m_rep, 0, length + 1);
770 // this is shared with someone using more capacity, gotta make a whole new string
771 int newCapacity = expandedSize((length + 1), 0);
772 UChar *d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * newCapacity));
773 memcpy(d, data(), length * sizeof(UChar));
775 m_rep = Rep::create(d, length);
776 m_rep->capacity = newCapacity;
782 CString UString::cstring() const
787 char *UString::ascii() const
789 // Never make the buffer smaller than normalStatBufferSize.
790 // Thus we almost never need to reallocate.
792 int neededSize = length + 1;
793 if (neededSize < normalStatBufferSize) {
794 neededSize = normalStatBufferSize;
796 if (neededSize != statBufferSize) {
797 delete [] statBuffer;
798 statBuffer = new char [neededSize];
799 statBufferSize = neededSize;
802 const UChar *p = data();
803 char *q = statBuffer;
804 const UChar *limit = p + length;
816 void UString::globalClear()
818 delete [] statBuffer;
824 UString &UString::operator=(const char *c)
826 int l = c ? strlen(c) : 0;
828 if (m_rep->rc == 1 && l <= m_rep->capacity && !m_rep->baseString && m_rep->offset == 0 && m_rep->preCapacity == 0) {
832 d = static_cast<UChar *>(fastMalloc(sizeof(UChar) * l));
833 m_rep = Rep::create(d, l);
835 for (int i = 0; i < l; i++)
841 bool UString::is8Bit() const
843 const UChar *u = data();
844 const UChar *limit = u + size();
854 UChar UString::operator[](int pos) const
861 UCharReference UString::operator[](int pos)
863 /* TODO: boundary check */
864 return UCharReference(this, pos);
867 double UString::toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const
871 // FIXME: If tolerateTrailingJunk is true, then we want to tolerate non-8-bit junk
872 // after the number, so is8Bit is too strict a check.
876 const char *c = ascii();
878 // skip leading white space
884 return tolerateEmptyString ? 0.0 : NaN;
887 if (*c == '0' && (*(c+1) == 'x' || *(c+1) == 'X')) {
891 if (*c >= '0' && *c <= '9')
892 d = d * 16.0 + *c - '0';
893 else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f'))
894 d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0;
901 d = kjs_strtod(c, &end);
902 if ((d != 0.0 || end != c) && d != HUGE_VAL && d != -HUGE_VAL) {
909 else if (*c == '-') {
913 if (strncmp(c, "Infinity", 8) != 0)
920 // allow trailing white space
923 // don't allow anything after - unless tolerant=true
924 if (!tolerateTrailingJunk && *c != '\0')
930 double UString::toDouble(bool tolerateTrailingJunk) const
932 return toDouble(tolerateTrailingJunk, true);
935 double UString::toDouble() const
937 return toDouble(false, true);
940 uint32_t UString::toUInt32(bool *ok) const
942 double d = toDouble();
945 if (d != static_cast<uint32_t>(d)) {
953 return static_cast<uint32_t>(d);
956 uint32_t UString::toUInt32(bool *ok, bool tolerateEmptyString) const
958 double d = toDouble(false, tolerateEmptyString);
961 if (d != static_cast<uint32_t>(d)) {
969 return static_cast<uint32_t>(d);
972 uint32_t UString::toStrictUInt32(bool *ok) const
977 // Empty string is not OK.
978 int len = m_rep->len;
981 const UChar *p = m_rep->data();
982 unsigned short c = p->unicode();
984 // If the first digit is 0, only 0 itself is OK.
991 // Convert to UInt32, checking for overflow.
994 // Process character, turning it into a digit.
995 if (c < '0' || c > '9')
997 const unsigned d = c - '0';
999 // Multiply by 10, checking for overflow out of 32 bits.
1000 if (i > 0xFFFFFFFFU / 10)
1004 // Add in the digit, checking for overflow out of 32 bits.
1005 const unsigned max = 0xFFFFFFFFU - d;
1010 // Handle end of string.
1017 // Get next character.
1018 c = (++p)->unicode();
1022 int UString::find(const UString &f, int pos) const
1032 const UChar *end = data() + sz - fsz;
1033 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1034 const UChar *fdata = f.data();
1035 unsigned short fchar = fdata->uc;
1037 for (const UChar *c = data() + pos; c <= end; c++)
1038 if (c->uc == fchar && !memcmp(c + 1, fdata, fsizeminusone))
1044 int UString::find(UChar ch, int pos) const
1048 const UChar *end = data() + size();
1049 for (const UChar *c = data() + pos; c < end; c++)
1056 int UString::rfind(const UString &f, int pos) const
1068 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1069 const UChar *fdata = f.data();
1070 for (const UChar *c = data() + pos; c >= data(); c--) {
1071 if (*c == *fdata && !memcmp(c + 1, fdata + 1, fsizeminusone))
1078 int UString::rfind(UChar ch, int pos) const
1082 if (pos + 1 >= size())
1084 for (const UChar *c = data() + pos; c >= data(); c--) {
1092 UString UString::substr(int pos, int len) const
1105 if (pos == 0 && len == s)
1108 return UString(Rep::create(m_rep, pos, len));
1111 void UString::copyForWriting()
1113 if (m_rep->rc > 1 || m_rep->baseString) {
1115 UChar *n = static_cast<UChar *>(fastMalloc(sizeof(UChar) * l));
1116 memcpy(n, data(), l * sizeof(UChar));
1117 m_rep = Rep::create(n, l);
1121 bool operator==(const UString& s1, const UString& s2)
1123 if (s1.m_rep->len != s2.m_rep->len)
1126 return (memcmp(s1.m_rep->data(), s2.m_rep->data(),
1127 s1.m_rep->len * sizeof(UChar)) == 0);
1130 bool operator==(const UString& s1, const char *s2)
1133 return s1.isEmpty();
1136 const UChar *u = s1.data();
1137 const UChar *uend = u + s1.size();
1138 while (u != uend && *s2) {
1139 if (u->uc != (unsigned char)*s2)
1145 return u == uend && *s2 == 0;
1148 bool operator<(const UString& s1, const UString& s2)
1150 const int l1 = s1.size();
1151 const int l2 = s2.size();
1152 const int lmin = l1 < l2 ? l1 : l2;
1153 const UChar *c1 = s1.data();
1154 const UChar *c2 = s2.data();
1156 while (l < lmin && *c1 == *c2) {
1162 return (c1->uc < c2->uc);
1167 int compare(const UString& s1, const UString& s2)
1169 const int l1 = s1.size();
1170 const int l2 = s2.size();
1171 const int lmin = l1 < l2 ? l1 : l2;
1172 const UChar *c1 = s1.data();
1173 const UChar *c2 = s2.data();
1175 while (l < lmin && *c1 == *c2) {
1182 return (c1->uc > c2->uc) ? 1 : -1;
1187 return (l1 > l2) ? 1 : -1;
1190 inline int inlineUTF8SequenceLengthNonASCII(char b0)
1192 if ((b0 & 0xC0) != 0xC0)
1194 if ((b0 & 0xE0) == 0xC0)
1196 if ((b0 & 0xF0) == 0xE0)
1198 if ((b0 & 0xF8) == 0xF0)
1203 int UTF8SequenceLengthNonASCII(char b0)
1205 return inlineUTF8SequenceLengthNonASCII(b0);
1208 inline int inlineUTF8SequenceLength(char b0)
1210 return (b0 & 0x80) == 0 ? 1 : UTF8SequenceLengthNonASCII(b0);
1213 // Given a first byte, gives the length of the UTF-8 sequence it begins.
1214 // Returns 0 for bytes that are not legal starts of UTF-8 sequences.
1215 // Only allows sequences of up to 4 bytes, since that works for all Unicode characters (U-00000000 to U-0010FFFF).
1216 int UTF8SequenceLength(char b0)
1218 return (b0 & 0x80) == 0 ? 1 : inlineUTF8SequenceLengthNonASCII(b0);
1221 // Takes a null-terminated C-style string with a UTF-8 sequence in it and converts it to a character.
1222 // Only allows Unicode characters (U-00000000 to U-0010FFFF).
1223 // Returns -1 if the sequence is not valid (including presence of extra bytes).
1224 int decodeUTF8Sequence(const char *sequence)
1226 // Handle 0-byte sequences (never valid).
1227 const unsigned char b0 = sequence[0];
1228 const int length = inlineUTF8SequenceLength(b0);
1232 // Handle 1-byte sequences (plain ASCII).
1233 const unsigned char b1 = sequence[1];
1240 // Handle 2-byte sequences.
1241 if ((b1 & 0xC0) != 0x80)
1243 const unsigned char b2 = sequence[2];
1247 const int c = ((b0 & 0x1F) << 6) | (b1 & 0x3F);
1253 // Handle 3-byte sequences.
1254 if ((b2 & 0xC0) != 0x80)
1256 const unsigned char b3 = sequence[3];
1260 const int c = ((b0 & 0xF) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F);
1263 // UTF-16 surrogates should never appear in UTF-8 data.
1264 if (c >= 0xD800 && c <= 0xDFFF)
1266 // Backwards BOM and U+FFFF should never appear in UTF-8 data.
1267 if (c == 0xFFFE || c == 0xFFFF)
1272 // Handle 4-byte sequences.
1273 if ((b3 & 0xC0) != 0x80)
1275 const unsigned char b4 = sequence[4];
1279 const int c = ((b0 & 0x7) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);
1280 if (c < 0x10000 || c > 0x10FFFF)
1288 CString UString::UTF8String() const
1290 // Allocate a buffer big enough to hold all the characters.
1291 const int length = size();
1292 Vector<char, 1024> buffer(length * 3);
1294 // Convert to runs of 8-bit characters.
1295 char *p = buffer.begin();
1296 const UChar *d = data();
1297 for (int i = 0; i != length; ++i) {
1298 unsigned short c = d[i].unicode();
1301 } else if (c < 0x800) {
1302 *p++ = (char)((c >> 6) | 0xC0); // C0 is the 2-byte flag for UTF-8
1303 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1304 } else if (c >= 0xD800 && c <= 0xDBFF && i < length && d[i+1].uc >= 0xDC00 && d[i+1].uc <= 0xDFFF) {
1305 unsigned sc = 0x10000 + (((c & 0x3FF) << 10) | (d[i+1].uc & 0x3FF));
1306 *p++ = (char)((sc >> 18) | 0xF0); // F0 is the 4-byte flag for UTF-8
1307 *p++ = (char)(((sc >> 12) | 0x80) & 0xBF); // next 6 bits, with high bit set
1308 *p++ = (char)(((sc >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1309 *p++ = (char)((sc | 0x80) & 0xBF); // next 6 bits, with high bit set
1312 *p++ = (char)((c >> 12) | 0xE0); // E0 is the 3-byte flag for UTF-8
1313 *p++ = (char)(((c >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1314 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1318 // Return the result as a C string.
1319 CString result(buffer, p - buffer);