source: webkit/trunk/JavaScriptCore/runtime/UString.cpp@ 46153

Last change on this file since 46153 was 46153, checked in by [email protected], 16 years ago

Make it harder to misuse try* allocation routines
https://bugs.webkit.org/show_bug.cgi?id=27469

Reviewed Gavin Barraclough

Jump through a few hoops to make it much harder to accidentally
miss null-checking of values returned by the try-* allocation
routines.

  • Property svn:eol-style set to native
File size: 48.7 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2007 Cameron Zwarich ([email protected])
5 * Copyright (C) 2009 Google Inc. All rights reserved.
6 *
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.
11 *
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.
16 *
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.
21 *
22 */
23
24#include "config.h"
25#include "UString.h"
26
27#include "JSGlobalObjectFunctions.h"
28#include "Collector.h"
29#include "dtoa.h"
30#include "Identifier.h"
31#include "Operations.h"
32#include <ctype.h>
33#include <float.h>
34#include <limits.h>
35#include <math.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <wtf/ASCIICType.h>
39#include <wtf/Assertions.h>
40#include <wtf/MathExtras.h>
41#include <wtf/Vector.h>
42#include <wtf/unicode/UTF8.h>
43
44#if HAVE(STRING_H)
45#include <string.h>
46#endif
47#if HAVE(STRINGS_H)
48#include <strings.h>
49#endif
50
51using namespace WTF;
52using namespace WTF::Unicode;
53using namespace std;
54
55// This can be tuned differently per platform by putting platform #ifs right here.
56// If you don't define this macro at all, then copyChars will just call directly
57// to memcpy.
58#define USTRING_COPY_CHARS_INLINE_CUTOFF 20
59
60namespace JSC {
61
62extern const double NaN;
63extern const double Inf;
64
65// This number must be at least 2 to avoid sharing empty, null as well as 1 character strings from SmallStrings.
66static const int minLengthToShare = 10;
67
68static inline size_t overflowIndicator() { return std::numeric_limits<size_t>::max(); }
69static inline size_t maxUChars() { return std::numeric_limits<size_t>::max() / sizeof(UChar); }
70
71static inline PossiblyNull<UChar*> allocChars(size_t length)
72{
73 ASSERT(length);
74 if (length > maxUChars())
75 return 0;
76 return tryFastMalloc(sizeof(UChar) * length);
77}
78
79static inline PossiblyNull<UChar*> reallocChars(UChar* buffer, size_t length)
80{
81 ASSERT(length);
82 if (length > maxUChars())
83 return 0;
84 return tryFastRealloc(buffer, sizeof(UChar) * length);
85}
86
87static inline void copyChars(UChar* destination, const UChar* source, unsigned numCharacters)
88{
89#ifdef USTRING_COPY_CHARS_INLINE_CUTOFF
90 if (numCharacters <= USTRING_COPY_CHARS_INLINE_CUTOFF) {
91 for (unsigned i = 0; i < numCharacters; ++i)
92 destination[i] = source[i];
93 return;
94 }
95#endif
96 memcpy(destination, source, numCharacters * sizeof(UChar));
97}
98
99COMPILE_ASSERT(sizeof(UChar) == 2, uchar_is_2_bytes);
100
101CString::CString(const char* c)
102 : m_length(strlen(c))
103 , m_data(new char[m_length + 1])
104{
105 memcpy(m_data, c, m_length + 1);
106}
107
108CString::CString(const char* c, size_t length)
109 : m_length(length)
110 , m_data(new char[length + 1])
111{
112 memcpy(m_data, c, m_length);
113 m_data[m_length] = 0;
114}
115
116CString::CString(const CString& b)
117{
118 m_length = b.m_length;
119 if (b.m_data) {
120 m_data = new char[m_length + 1];
121 memcpy(m_data, b.m_data, m_length + 1);
122 } else
123 m_data = 0;
124}
125
126CString::~CString()
127{
128 delete [] m_data;
129}
130
131CString CString::adopt(char* c, size_t length)
132{
133 CString s;
134 s.m_data = c;
135 s.m_length = length;
136 return s;
137}
138
139CString& CString::append(const CString& t)
140{
141 char* n;
142 n = new char[m_length + t.m_length + 1];
143 if (m_length)
144 memcpy(n, m_data, m_length);
145 if (t.m_length)
146 memcpy(n + m_length, t.m_data, t.m_length);
147 m_length += t.m_length;
148 n[m_length] = 0;
149
150 delete [] m_data;
151 m_data = n;
152
153 return *this;
154}
155
156CString& CString::operator=(const char* c)
157{
158 if (m_data)
159 delete [] m_data;
160 m_length = strlen(c);
161 m_data = new char[m_length + 1];
162 memcpy(m_data, c, m_length + 1);
163
164 return *this;
165}
166
167CString& CString::operator=(const CString& str)
168{
169 if (this == &str)
170 return *this;
171
172 if (m_data)
173 delete [] m_data;
174 m_length = str.m_length;
175 if (str.m_data) {
176 m_data = new char[m_length + 1];
177 memcpy(m_data, str.m_data, m_length + 1);
178 } else
179 m_data = 0;
180
181 return *this;
182}
183
184bool operator==(const CString& c1, const CString& c2)
185{
186 size_t len = c1.size();
187 return len == c2.size() && (len == 0 || memcmp(c1.c_str(), c2.c_str(), len) == 0);
188}
189
190// These static strings are immutable, except for rc, whose initial value is chosen to
191// reduce the possibility of it becoming zero due to ref/deref not being thread-safe.
192static UChar sharedEmptyChar;
193UString::BaseString* UString::Rep::nullBaseString;
194UString::BaseString* UString::Rep::emptyBaseString;
195UString* UString::nullUString;
196
197static void initializeStaticBaseString(UString::BaseString& base)
198{
199 base.rc = INT_MAX / 2;
200 base.m_identifierTableAndFlags.setFlag(UString::Rep::StaticFlag);
201 base.checkConsistency();
202}
203
204void initializeUString()
205{
206 UString::Rep::nullBaseString = new UString::BaseString(0, 0);
207 initializeStaticBaseString(*UString::Rep::nullBaseString);
208
209 UString::Rep::emptyBaseString = new UString::BaseString(&sharedEmptyChar, 0);
210 initializeStaticBaseString(*UString::Rep::emptyBaseString);
211
212 UString::nullUString = new UString;
213}
214
215static char* statBuffer = 0; // Only used for debugging via UString::ascii().
216
217PassRefPtr<UString::Rep> UString::Rep::createCopying(const UChar* d, int l)
218{
219 UChar* copyD = static_cast<UChar*>(fastMalloc(l * sizeof(UChar)));
220 copyChars(copyD, d, l);
221 return create(copyD, l);
222}
223
224PassRefPtr<UString::Rep> UString::Rep::createFromUTF8(const char* string)
225{
226 if (!string)
227 return &UString::Rep::null();
228
229 size_t length = strlen(string);
230 Vector<UChar, 1024> buffer(length);
231 UChar* p = buffer.data();
232 if (conversionOK != convertUTF8ToUTF16(&string, string + length, &p, p + length))
233 return &UString::Rep::null();
234
235 return UString::Rep::createCopying(buffer.data(), p - buffer.data());
236}
237
238PassRefPtr<UString::Rep> UString::Rep::create(UChar* string, int length, PassRefPtr<UString::SharedUChar> sharedBuffer)
239{
240 PassRefPtr<UString::Rep> rep = create(string, length);
241 rep->baseString()->setSharedBuffer(sharedBuffer);
242 rep->checkConsistency();
243 return rep;
244}
245
246UString::SharedUChar* UString::Rep::sharedBuffer()
247{
248 UString::BaseString* base = baseString();
249 if (len < minLengthToShare)
250 return 0;
251
252 return base->sharedBuffer();
253}
254
255void UString::Rep::destroy()
256{
257 checkConsistency();
258
259 // Static null and empty strings can never be destroyed, but we cannot rely on
260 // reference counting, because ref/deref are not thread-safe.
261 if (!isStatic()) {
262 if (identifierTable())
263 Identifier::remove(this);
264
265 UString::BaseString* base = baseString();
266 if (base == this) {
267 if (m_sharedBuffer)
268 m_sharedBuffer->deref();
269 else
270 fastFree(base->buf);
271 } else
272 base->deref();
273
274 delete this;
275 }
276}
277
278// Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
279// or anything like that.
280const unsigned PHI = 0x9e3779b9U;
281
282// Paul Hsieh's SuperFastHash
283// http://www.azillionmonkeys.com/qed/hash.html
284unsigned UString::Rep::computeHash(const UChar* s, int len)
285{
286 unsigned l = len;
287 uint32_t hash = PHI;
288 uint32_t tmp;
289
290 int rem = l & 1;
291 l >>= 1;
292
293 // Main loop
294 for (; l > 0; l--) {
295 hash += s[0];
296 tmp = (s[1] << 11) ^ hash;
297 hash = (hash << 16) ^ tmp;
298 s += 2;
299 hash += hash >> 11;
300 }
301
302 // Handle end case
303 if (rem) {
304 hash += s[0];
305 hash ^= hash << 11;
306 hash += hash >> 17;
307 }
308
309 // Force "avalanching" of final 127 bits
310 hash ^= hash << 3;
311 hash += hash >> 5;
312 hash ^= hash << 2;
313 hash += hash >> 15;
314 hash ^= hash << 10;
315
316 // this avoids ever returning a hash code of 0, since that is used to
317 // signal "hash not computed yet", using a value that is likely to be
318 // effectively the same as 0 when the low bits are masked
319 if (hash == 0)
320 hash = 0x80000000;
321
322 return hash;
323}
324
325// Paul Hsieh's SuperFastHash
326// http://www.azillionmonkeys.com/qed/hash.html
327unsigned UString::Rep::computeHash(const char* s, int l)
328{
329 // This hash is designed to work on 16-bit chunks at a time. But since the normal case
330 // (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
331 // were 16-bit chunks, which should give matching results
332
333 uint32_t hash = PHI;
334 uint32_t tmp;
335
336 size_t rem = l & 1;
337 l >>= 1;
338
339 // Main loop
340 for (; l > 0; l--) {
341 hash += static_cast<unsigned char>(s[0]);
342 tmp = (static_cast<unsigned char>(s[1]) << 11) ^ hash;
343 hash = (hash << 16) ^ tmp;
344 s += 2;
345 hash += hash >> 11;
346 }
347
348 // Handle end case
349 if (rem) {
350 hash += static_cast<unsigned char>(s[0]);
351 hash ^= hash << 11;
352 hash += hash >> 17;
353 }
354
355 // Force "avalanching" of final 127 bits
356 hash ^= hash << 3;
357 hash += hash >> 5;
358 hash ^= hash << 2;
359 hash += hash >> 15;
360 hash ^= hash << 10;
361
362 // this avoids ever returning a hash code of 0, since that is used to
363 // signal "hash not computed yet", using a value that is likely to be
364 // effectively the same as 0 when the low bits are masked
365 if (hash == 0)
366 hash = 0x80000000;
367
368 return hash;
369}
370
371#ifndef NDEBUG
372void UString::Rep::checkConsistency() const
373{
374 const UString::BaseString* base = baseString();
375
376 // There is no recursion for base strings.
377 ASSERT(base == base->baseString());
378
379 if (isStatic()) {
380 // There are only two static strings: null and empty.
381 ASSERT(!len);
382
383 // Static strings cannot get in identifier tables, because they are globally shared.
384 ASSERT(!identifierTable());
385 }
386
387 // The string fits in buffer.
388 ASSERT(base->usedPreCapacity <= base->preCapacity);
389 ASSERT(base->usedCapacity <= base->capacity);
390 ASSERT(-offset <= base->usedPreCapacity);
391 ASSERT(offset + len <= base->usedCapacity);
392}
393#endif
394
395UString::SharedUChar* UString::BaseString::sharedBuffer()
396{
397 if (!m_sharedBuffer)
398 setSharedBuffer(SharedUChar::create(new OwnFastMallocPtr<UChar>(buf)));
399 return m_sharedBuffer;
400}
401
402void UString::BaseString::setSharedBuffer(PassRefPtr<UString::SharedUChar> sharedBuffer)
403{
404 // The manual steps below are because m_sharedBuffer can't be a RefPtr. m_sharedBuffer
405 // is in a union with another variable to avoid making BaseString any larger.
406 if (m_sharedBuffer)
407 m_sharedBuffer->deref();
408 m_sharedBuffer = sharedBuffer.releaseRef();
409}
410
411bool UString::BaseString::slowIsBufferReadOnly()
412{
413 // The buffer may not be modified as soon as the underlying data has been shared with another class.
414 if (m_sharedBuffer->isShared())
415 return true;
416
417 // At this point, we know it that the underlying buffer isn't shared outside of this base class,
418 // so get rid of m_sharedBuffer.
419 OwnPtr<OwnFastMallocPtr<UChar> > mallocPtr(m_sharedBuffer->release());
420 UChar* unsharedBuf = const_cast<UChar*>(mallocPtr->release());
421 setSharedBuffer(0);
422 preCapacity += (buf - unsharedBuf);
423 buf = unsharedBuf;
424 return false;
425}
426
427// Put these early so they can be inlined.
428static inline size_t expandedSize(size_t capacitySize, size_t precapacitySize)
429{
430 // Combine capacitySize & precapacitySize to produce a single size to allocate,
431 // check that doing so does not result in overflow.
432 size_t size = capacitySize + precapacitySize;
433 if (size < capacitySize)
434 return overflowIndicator();
435
436 // Small Strings (up to 4 pages):
437 // Expand the allocation size to 112.5% of the amount requested. This is largely sicking
438 // to our previous policy, however 112.5% is cheaper to calculate.
439 if (size < 0x4000) {
440 size_t expandedSize = ((size + (size >> 3)) | 15) + 1;
441 // Given the limited range within which we calculate the expansion in this
442 // fashion the above calculation should never overflow.
443 ASSERT(expandedSize >= size);
444 ASSERT(expandedSize < maxUChars());
445 return expandedSize;
446 }
447
448 // Medium Strings (up to 128 pages):
449 // For pages covering multiple pages over-allocation is less of a concern - any unused
450 // space will not be paged in if it is not used, so this is purely a VM overhead. For
451 // these strings allocate 2x the requested size.
452 if (size < 0x80000) {
453 size_t expandedSize = ((size + size) | 0xfff) + 1;
454 // Given the limited range within which we calculate the expansion in this
455 // fashion the above calculation should never overflow.
456 ASSERT(expandedSize >= size);
457 ASSERT(expandedSize < maxUChars());
458 return expandedSize;
459 }
460
461 // Large Strings (to infinity and beyond!):
462 // Revert to our 112.5% policy - probably best to limit the amount of unused VM we allow
463 // any individual string be responsible for.
464 size_t expandedSize = ((size + (size >> 3)) | 0xfff) + 1;
465
466 // Check for overflow - any result that is at least as large as requested (but
467 // still below the limit) is okay.
468 if ((expandedSize >= size) && (expandedSize < maxUChars()))
469 return expandedSize;
470 return overflowIndicator();
471}
472
473static inline bool expandCapacity(UString::Rep* rep, int requiredLength)
474{
475 rep->checkConsistency();
476 ASSERT(!rep->baseString()->isBufferReadOnly());
477
478 UString::BaseString* base = rep->baseString();
479
480 if (requiredLength > base->capacity) {
481 size_t newCapacity = expandedSize(requiredLength, base->preCapacity);
482 UChar* oldBuf = base->buf;
483 if (!reallocChars(base->buf, newCapacity).getValue(base->buf)) {
484 base->buf = oldBuf;
485 return false;
486 }
487 base->capacity = newCapacity - base->preCapacity;
488 }
489 if (requiredLength > base->usedCapacity)
490 base->usedCapacity = requiredLength;
491
492 rep->checkConsistency();
493 return true;
494}
495
496bool UString::Rep::reserveCapacity(int capacity)
497{
498 // If this is an empty string there is no point 'growing' it - just allocate a new one.
499 // If the BaseString is shared with another string that is using more capacity than this
500 // string is, then growing the buffer won't help.
501 // If the BaseString's buffer is readonly, then it isn't allowed to grow.
502 UString::BaseString* base = baseString();
503 if (!base->buf || !base->capacity || (offset + len) != base->usedCapacity || base->isBufferReadOnly())
504 return false;
505
506 // If there is already sufficient capacity, no need to grow!
507 if (capacity <= base->capacity)
508 return true;
509
510 checkConsistency();
511
512 size_t newCapacity = expandedSize(capacity, base->preCapacity);
513 UChar* oldBuf = base->buf;
514 if (!reallocChars(base->buf, newCapacity).getValue(base->buf)) {
515 base->buf = oldBuf;
516 return false;
517 }
518 base->capacity = newCapacity - base->preCapacity;
519
520 checkConsistency();
521 return true;
522}
523
524void UString::expandCapacity(int requiredLength)
525{
526 if (!JSC::expandCapacity(m_rep.get(), requiredLength))
527 makeNull();
528}
529
530void UString::expandPreCapacity(int requiredPreCap)
531{
532 m_rep->checkConsistency();
533 ASSERT(!m_rep->baseString()->isBufferReadOnly());
534
535 BaseString* base = m_rep->baseString();
536
537 if (requiredPreCap > base->preCapacity) {
538 size_t newCapacity = expandedSize(requiredPreCap, base->capacity);
539 int delta = newCapacity - base->capacity - base->preCapacity;
540
541 UChar* newBuf;
542 if (!allocChars(newCapacity).getValue(newBuf)) {
543 makeNull();
544 return;
545 }
546 copyChars(newBuf + delta, base->buf, base->capacity + base->preCapacity);
547 fastFree(base->buf);
548 base->buf = newBuf;
549
550 base->preCapacity = newCapacity - base->capacity;
551 }
552 if (requiredPreCap > base->usedPreCapacity)
553 base->usedPreCapacity = requiredPreCap;
554
555 m_rep->checkConsistency();
556}
557
558static PassRefPtr<UString::Rep> createRep(const char* c)
559{
560 if (!c)
561 return &UString::Rep::null();
562
563 if (!c[0])
564 return &UString::Rep::empty();
565
566 size_t length = strlen(c);
567 UChar* d;
568 if (!allocChars(length).getValue(d))
569 return &UString::Rep::null();
570 else {
571 for (size_t i = 0; i < length; i++)
572 d[i] = static_cast<unsigned char>(c[i]); // use unsigned char to zero-extend instead of sign-extend
573 return UString::Rep::create(d, static_cast<int>(length));
574 }
575
576}
577
578UString::UString(const char* c)
579 : m_rep(createRep(c))
580{
581}
582
583UString::UString(const UChar* c, int length)
584{
585 if (length == 0)
586 m_rep = &Rep::empty();
587 else
588 m_rep = Rep::createCopying(c, length);
589}
590
591UString::UString(UChar* c, int length, bool copy)
592{
593 if (length == 0)
594 m_rep = &Rep::empty();
595 else if (copy)
596 m_rep = Rep::createCopying(c, length);
597 else
598 m_rep = Rep::create(c, length);
599}
600
601UString::UString(const Vector<UChar>& buffer)
602{
603 if (!buffer.size())
604 m_rep = &Rep::empty();
605 else
606 m_rep = Rep::createCopying(buffer.data(), buffer.size());
607}
608
609static ALWAYS_INLINE int newCapacityWithOverflowCheck(const int currentCapacity, const int extendLength, const bool plusOne = false)
610{
611 ASSERT_WITH_MESSAGE(extendLength >= 0, "extendedLength = %d", extendLength);
612
613 const int plusLength = plusOne ? 1 : 0;
614 if (currentCapacity > std::numeric_limits<int>::max() - extendLength - plusLength)
615 CRASH();
616
617 return currentCapacity + extendLength + plusLength;
618}
619
620static ALWAYS_INLINE PassRefPtr<UString::Rep> concatenate(PassRefPtr<UString::Rep> r, const UChar* tData, int tSize)
621{
622 RefPtr<UString::Rep> rep = r;
623
624 rep->checkConsistency();
625
626 int thisSize = rep->size();
627 int thisOffset = rep->offset;
628 int length = thisSize + tSize;
629 UString::BaseString* base = rep->baseString();
630
631 // possible cases:
632 if (tSize == 0) {
633 // t is empty
634 } else if (thisSize == 0) {
635 // this is empty
636 rep = UString::Rep::createCopying(tData, tSize);
637 } else if (rep == base && !base->isShared()) {
638 // this is direct and has refcount of 1 (so we can just alter it directly)
639 if (!expandCapacity(rep.get(), newCapacityWithOverflowCheck(thisOffset, length)))
640 rep = &UString::Rep::null();
641 if (rep->data()) {
642 copyChars(rep->data() + thisSize, tData, tSize);
643 rep->len = length;
644 rep->_hash = 0;
645 }
646 } else if (thisOffset + thisSize == base->usedCapacity && thisSize >= minShareSize && !base->isBufferReadOnly()) {
647 // this reaches the end of the buffer - extend it if it's long enough to append to
648 if (!expandCapacity(rep.get(), newCapacityWithOverflowCheck(thisOffset, length)))
649 rep = &UString::Rep::null();
650 if (rep->data()) {
651 copyChars(rep->data() + thisSize, tData, tSize);
652 rep = UString::Rep::create(rep, 0, length);
653 }
654 } else {
655 // This is shared in some way that prevents us from modifying base, so we must make a whole new string.
656 size_t newCapacity = expandedSize(length, 0);
657 UChar* d;
658 if (!allocChars(newCapacity).getValue(d))
659 rep = &UString::Rep::null();
660 else {
661 copyChars(d, rep->data(), thisSize);
662 copyChars(d + thisSize, tData, tSize);
663 rep = UString::Rep::create(d, length);
664 rep->baseString()->capacity = newCapacity;
665 }
666 }
667
668 rep->checkConsistency();
669
670 return rep.release();
671}
672
673static ALWAYS_INLINE PassRefPtr<UString::Rep> concatenate(PassRefPtr<UString::Rep> r, const char* t)
674{
675 RefPtr<UString::Rep> rep = r;
676
677 rep->checkConsistency();
678
679 int thisSize = rep->size();
680 int thisOffset = rep->offset;
681 int tSize = static_cast<int>(strlen(t));
682 int length = thisSize + tSize;
683 UString::BaseString* base = rep->baseString();
684
685 // possible cases:
686 if (thisSize == 0) {
687 // this is empty
688 rep = createRep(t);
689 } else if (tSize == 0) {
690 // t is empty, we'll just return *this below.
691 } else if (rep == base && !base->isShared()) {
692 // this is direct and has refcount of 1 (so we can just alter it directly)
693 expandCapacity(rep.get(), newCapacityWithOverflowCheck(thisOffset, length));
694 UChar* d = rep->data();
695 if (d) {
696 for (int i = 0; i < tSize; ++i)
697 d[thisSize + i] = static_cast<unsigned char>(t[i]); // use unsigned char to zero-extend instead of sign-extend
698 rep->len = length;
699 rep->_hash = 0;
700 }
701 } else if (thisOffset + thisSize == base->usedCapacity && thisSize >= minShareSize && !base->isBufferReadOnly()) {
702 // this string reaches the end of the buffer - extend it
703 expandCapacity(rep.get(), newCapacityWithOverflowCheck(thisOffset, length));
704 UChar* d = rep->data();
705 if (d) {
706 for (int i = 0; i < tSize; ++i)
707 d[thisSize + i] = static_cast<unsigned char>(t[i]); // use unsigned char to zero-extend instead of sign-extend
708 rep = UString::Rep::create(rep, 0, length);
709 }
710 } else {
711 // This is shared in some way that prevents us from modifying base, so we must make a whole new string.
712 size_t newCapacity = expandedSize(length, 0);
713 UChar* d;
714 if (!allocChars(newCapacity).getValue(d))
715 rep = &UString::Rep::null();
716 else {
717 copyChars(d, rep->data(), thisSize);
718 for (int i = 0; i < tSize; ++i)
719 d[thisSize + i] = static_cast<unsigned char>(t[i]); // use unsigned char to zero-extend instead of sign-extend
720 rep = UString::Rep::create(d, length);
721 rep->baseString()->capacity = newCapacity;
722 }
723 }
724
725 rep->checkConsistency();
726
727 return rep.release();
728}
729
730PassRefPtr<UString::Rep> concatenate(UString::Rep* a, UString::Rep* b)
731{
732 a->checkConsistency();
733 b->checkConsistency();
734
735 int aSize = a->size();
736 int bSize = b->size();
737 int aOffset = a->offset;
738
739 // possible cases:
740
741 UString::BaseString* aBase = a->baseString();
742 if (bSize == 1 && aOffset + aSize == aBase->usedCapacity && aOffset + aSize < aBase->capacity && !aBase->isBufferReadOnly()) {
743 // b is a single character (common fast case)
744 ++aBase->usedCapacity;
745 a->data()[aSize] = b->data()[0];
746 return UString::Rep::create(a, 0, aSize + 1);
747 }
748
749 // a is empty
750 if (aSize == 0)
751 return b;
752 // b is empty
753 if (bSize == 0)
754 return a;
755
756 int bOffset = b->offset;
757 int length = aSize + bSize;
758
759 UString::BaseString* bBase = b->baseString();
760 if (aOffset + aSize == aBase->usedCapacity && aSize >= minShareSize && 4 * aSize >= bSize
761 && (-bOffset != bBase->usedPreCapacity || aSize >= bSize) && !aBase->isBufferReadOnly()) {
762 // - a reaches the end of its buffer so it qualifies for shared append
763 // - also, it's at least a quarter the length of b - appending to a much shorter
764 // string does more harm than good
765 // - however, if b qualifies for prepend and is longer than a, we'd rather prepend
766
767 UString x(a);
768 x.expandCapacity(newCapacityWithOverflowCheck(aOffset, length));
769 if (!a->data() || !x.data())
770 return 0;
771 copyChars(a->data() + aSize, b->data(), bSize);
772 PassRefPtr<UString::Rep> result = UString::Rep::create(a, 0, length);
773
774 a->checkConsistency();
775 b->checkConsistency();
776 result->checkConsistency();
777
778 return result;
779 }
780
781 if (-bOffset == bBase->usedPreCapacity && bSize >= minShareSize && 4 * bSize >= aSize && !bBase->isBufferReadOnly()) {
782 // - b reaches the beginning of its buffer so it qualifies for shared prepend
783 // - also, it's at least a quarter the length of a - prepending to a much shorter
784 // string does more harm than good
785 UString y(b);
786 y.expandPreCapacity(-bOffset + aSize);
787 if (!b->data() || !y.data())
788 return 0;
789 copyChars(b->data() - aSize, a->data(), aSize);
790 PassRefPtr<UString::Rep> result = UString::Rep::create(b, -aSize, length);
791
792 a->checkConsistency();
793 b->checkConsistency();
794 result->checkConsistency();
795
796 return result;
797 }
798
799 // a does not qualify for append, and b does not qualify for prepend, gotta make a whole new string
800 size_t newCapacity = expandedSize(length, 0);
801 UChar* d;
802 if (!allocChars(newCapacity).getValue(d))
803 return 0;
804 copyChars(d, a->data(), aSize);
805 copyChars(d + aSize, b->data(), bSize);
806 PassRefPtr<UString::Rep> result = UString::Rep::create(d, length);
807 result->baseString()->capacity = newCapacity;
808
809 a->checkConsistency();
810 b->checkConsistency();
811 result->checkConsistency();
812
813 return result;
814}
815
816PassRefPtr<UString::Rep> concatenate(UString::Rep* rep, int i)
817{
818 UChar buf[1 + sizeof(i) * 3];
819 UChar* end = buf + sizeof(buf) / sizeof(UChar);
820 UChar* p = end;
821
822 if (i == 0)
823 *--p = '0';
824 else if (i == INT_MIN) {
825 char minBuf[1 + sizeof(i) * 3];
826 sprintf(minBuf, "%d", INT_MIN);
827 return concatenate(rep, minBuf);
828 } else {
829 bool negative = false;
830 if (i < 0) {
831 negative = true;
832 i = -i;
833 }
834 while (i) {
835 *--p = static_cast<unsigned short>((i % 10) + '0');
836 i /= 10;
837 }
838 if (negative)
839 *--p = '-';
840 }
841
842 return concatenate(rep, p, static_cast<int>(end - p));
843
844}
845
846PassRefPtr<UString::Rep> concatenate(UString::Rep* rep, double d)
847{
848 // avoid ever printing -NaN, in JS conceptually there is only one NaN value
849 if (isnan(d))
850 return concatenate(rep, "NaN");
851
852 if (d == 0.0) // stringify -0 as 0
853 d = 0.0;
854
855 char buf[80];
856 int decimalPoint;
857 int sign;
858
859 char result[80];
860 WTF::dtoa(result, d, 0, &decimalPoint, &sign, NULL);
861 int length = static_cast<int>(strlen(result));
862
863 int i = 0;
864 if (sign)
865 buf[i++] = '-';
866
867 if (decimalPoint <= 0 && decimalPoint > -6) {
868 buf[i++] = '0';
869 buf[i++] = '.';
870 for (int j = decimalPoint; j < 0; j++)
871 buf[i++] = '0';
872 strcpy(buf + i, result);
873 } else if (decimalPoint <= 21 && decimalPoint > 0) {
874 if (length <= decimalPoint) {
875 strcpy(buf + i, result);
876 i += length;
877 for (int j = 0; j < decimalPoint - length; j++)
878 buf[i++] = '0';
879 buf[i] = '\0';
880 } else {
881 strncpy(buf + i, result, decimalPoint);
882 i += decimalPoint;
883 buf[i++] = '.';
884 strcpy(buf + i, result + decimalPoint);
885 }
886 } else if (result[0] < '0' || result[0] > '9')
887 strcpy(buf + i, result);
888 else {
889 buf[i++] = result[0];
890 if (length > 1) {
891 buf[i++] = '.';
892 strcpy(buf + i, result + 1);
893 i += length - 1;
894 }
895
896 buf[i++] = 'e';
897 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
898 // decimalPoint can't be more than 3 digits decimal given the
899 // nature of float representation
900 int exponential = decimalPoint - 1;
901 if (exponential < 0)
902 exponential = -exponential;
903 if (exponential >= 100)
904 buf[i++] = static_cast<char>('0' + exponential / 100);
905 if (exponential >= 10)
906 buf[i++] = static_cast<char>('0' + (exponential % 100) / 10);
907 buf[i++] = static_cast<char>('0' + exponential % 10);
908 buf[i++] = '\0';
909 }
910
911 return concatenate(rep, buf);
912}
913
914UString UString::from(int i)
915{
916 UChar buf[1 + sizeof(i) * 3];
917 UChar* end = buf + sizeof(buf) / sizeof(UChar);
918 UChar* p = end;
919
920 if (i == 0)
921 *--p = '0';
922 else if (i == INT_MIN) {
923 char minBuf[1 + sizeof(i) * 3];
924 sprintf(minBuf, "%d", INT_MIN);
925 return UString(minBuf);
926 } else {
927 bool negative = false;
928 if (i < 0) {
929 negative = true;
930 i = -i;
931 }
932 while (i) {
933 *--p = static_cast<unsigned short>((i % 10) + '0');
934 i /= 10;
935 }
936 if (negative)
937 *--p = '-';
938 }
939
940 return UString(p, static_cast<int>(end - p));
941}
942
943UString UString::from(unsigned int u)
944{
945 UChar buf[sizeof(u) * 3];
946 UChar* end = buf + sizeof(buf) / sizeof(UChar);
947 UChar* p = end;
948
949 if (u == 0)
950 *--p = '0';
951 else {
952 while (u) {
953 *--p = static_cast<unsigned short>((u % 10) + '0');
954 u /= 10;
955 }
956 }
957
958 return UString(p, static_cast<int>(end - p));
959}
960
961UString UString::from(long l)
962{
963 UChar buf[1 + sizeof(l) * 3];
964 UChar* end = buf + sizeof(buf) / sizeof(UChar);
965 UChar* p = end;
966
967 if (l == 0)
968 *--p = '0';
969 else if (l == LONG_MIN) {
970 char minBuf[1 + sizeof(l) * 3];
971 sprintf(minBuf, "%ld", LONG_MIN);
972 return UString(minBuf);
973 } else {
974 bool negative = false;
975 if (l < 0) {
976 negative = true;
977 l = -l;
978 }
979 while (l) {
980 *--p = static_cast<unsigned short>((l % 10) + '0');
981 l /= 10;
982 }
983 if (negative)
984 *--p = '-';
985 }
986
987 return UString(p, static_cast<int>(end - p));
988}
989
990UString UString::from(double d)
991{
992 // avoid ever printing -NaN, in JS conceptually there is only one NaN value
993 if (isnan(d))
994 return "NaN";
995
996 char buf[80];
997 int decimalPoint;
998 int sign;
999
1000 char result[80];
1001 WTF::dtoa(result, d, 0, &decimalPoint, &sign, NULL);
1002 int length = static_cast<int>(strlen(result));
1003
1004 int i = 0;
1005 if (sign)
1006 buf[i++] = '-';
1007
1008 if (decimalPoint <= 0 && decimalPoint > -6) {
1009 buf[i++] = '0';
1010 buf[i++] = '.';
1011 for (int j = decimalPoint; j < 0; j++)
1012 buf[i++] = '0';
1013 strcpy(buf + i, result);
1014 } else if (decimalPoint <= 21 && decimalPoint > 0) {
1015 if (length <= decimalPoint) {
1016 strcpy(buf + i, result);
1017 i += length;
1018 for (int j = 0; j < decimalPoint - length; j++)
1019 buf[i++] = '0';
1020 buf[i] = '\0';
1021 } else {
1022 strncpy(buf + i, result, decimalPoint);
1023 i += decimalPoint;
1024 buf[i++] = '.';
1025 strcpy(buf + i, result + decimalPoint);
1026 }
1027 } else if (result[0] < '0' || result[0] > '9')
1028 strcpy(buf + i, result);
1029 else {
1030 buf[i++] = result[0];
1031 if (length > 1) {
1032 buf[i++] = '.';
1033 strcpy(buf + i, result + 1);
1034 i += length - 1;
1035 }
1036
1037 buf[i++] = 'e';
1038 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
1039 // decimalPoint can't be more than 3 digits decimal given the
1040 // nature of float representation
1041 int exponential = decimalPoint - 1;
1042 if (exponential < 0)
1043 exponential = -exponential;
1044 if (exponential >= 100)
1045 buf[i++] = static_cast<char>('0' + exponential / 100);
1046 if (exponential >= 10)
1047 buf[i++] = static_cast<char>('0' + (exponential % 100) / 10);
1048 buf[i++] = static_cast<char>('0' + exponential % 10);
1049 buf[i++] = '\0';
1050 }
1051
1052 return UString(buf);
1053}
1054
1055UString UString::spliceSubstringsWithSeparators(const Range* substringRanges, int rangeCount, const UString* separators, int separatorCount) const
1056{
1057 m_rep->checkConsistency();
1058
1059 if (rangeCount == 1 && separatorCount == 0) {
1060 int thisSize = size();
1061 int position = substringRanges[0].position;
1062 int length = substringRanges[0].length;
1063 if (position <= 0 && length >= thisSize)
1064 return *this;
1065 return UString::Rep::create(m_rep, max(0, position), min(thisSize, length));
1066 }
1067
1068 int totalLength = 0;
1069 for (int i = 0; i < rangeCount; i++)
1070 totalLength += substringRanges[i].length;
1071 for (int i = 0; i < separatorCount; i++)
1072 totalLength += separators[i].size();
1073
1074 if (totalLength == 0)
1075 return "";
1076
1077 UChar* buffer;
1078 if (!allocChars(totalLength).getValue(buffer))
1079 return null();
1080
1081 int maxCount = max(rangeCount, separatorCount);
1082 int bufferPos = 0;
1083 for (int i = 0; i < maxCount; i++) {
1084 if (i < rangeCount) {
1085 copyChars(buffer + bufferPos, data() + substringRanges[i].position, substringRanges[i].length);
1086 bufferPos += substringRanges[i].length;
1087 }
1088 if (i < separatorCount) {
1089 copyChars(buffer + bufferPos, separators[i].data(), separators[i].size());
1090 bufferPos += separators[i].size();
1091 }
1092 }
1093
1094 return UString::Rep::create(buffer, totalLength);
1095}
1096
1097UString UString::replaceRange(int rangeStart, int rangeLength, const UString& replacement) const
1098{
1099 m_rep->checkConsistency();
1100
1101 int replacementLength = replacement.size();
1102 int totalLength = size() - rangeLength + replacementLength;
1103 if (totalLength == 0)
1104 return "";
1105
1106 UChar* buffer;
1107 if (!allocChars(totalLength).getValue(buffer))
1108 return null();
1109
1110 copyChars(buffer, data(), rangeStart);
1111 copyChars(buffer + rangeStart, replacement.data(), replacementLength);
1112 int rangeEnd = rangeStart + rangeLength;
1113 copyChars(buffer + rangeStart + replacementLength, data() + rangeEnd, size() - rangeEnd);
1114
1115 return UString::Rep::create(buffer, totalLength);
1116}
1117
1118
1119UString& UString::append(const UString &t)
1120{
1121 m_rep->checkConsistency();
1122 t.rep()->checkConsistency();
1123
1124 int thisSize = size();
1125 int thisOffset = m_rep->offset;
1126 int tSize = t.size();
1127 int length = thisSize + tSize;
1128 BaseString* base = m_rep->baseString();
1129
1130 // possible cases:
1131 if (thisSize == 0) {
1132 // this is empty
1133 *this = t;
1134 } else if (tSize == 0) {
1135 // t is empty
1136 } else if (m_rep == base && !base->isShared()) {
1137 // this is direct and has refcount of 1 (so we can just alter it directly)
1138 expandCapacity(newCapacityWithOverflowCheck(thisOffset, length));
1139 if (data()) {
1140 copyChars(m_rep->data() + thisSize, t.data(), tSize);
1141 m_rep->len = length;
1142 m_rep->_hash = 0;
1143 }
1144 } else if (thisOffset + thisSize == base->usedCapacity && thisSize >= minShareSize && !base->isBufferReadOnly()) {
1145 // this reaches the end of the buffer - extend it if it's long enough to append to
1146 expandCapacity(newCapacityWithOverflowCheck(thisOffset, length));
1147 if (data()) {
1148 copyChars(m_rep->data() + thisSize, t.data(), tSize);
1149 m_rep = Rep::create(m_rep, 0, length);
1150 }
1151 } else {
1152 // This is shared in some way that prevents us from modifying base, so we must make a whole new string.
1153 size_t newCapacity = expandedSize(length, 0);
1154 UChar* d;
1155 if (!allocChars(newCapacity).getValue(d))
1156 makeNull();
1157 else {
1158 copyChars(d, data(), thisSize);
1159 copyChars(d + thisSize, t.data(), tSize);
1160 m_rep = Rep::create(d, length);
1161 m_rep->baseString()->capacity = newCapacity;
1162 }
1163 }
1164
1165 m_rep->checkConsistency();
1166 t.rep()->checkConsistency();
1167
1168 return *this;
1169}
1170
1171UString& UString::append(const UChar* tData, int tSize)
1172{
1173 m_rep = concatenate(m_rep.release(), tData, tSize);
1174 return *this;
1175}
1176
1177UString& UString::appendNumeric(int i)
1178{
1179 m_rep = concatenate(rep(), i);
1180 return *this;
1181}
1182
1183UString& UString::appendNumeric(double d)
1184{
1185 m_rep = concatenate(rep(), d);
1186 return *this;
1187}
1188
1189UString& UString::append(const char* t)
1190{
1191 m_rep = concatenate(m_rep.release(), t);
1192 return *this;
1193}
1194
1195UString& UString::append(UChar c)
1196{
1197 m_rep->checkConsistency();
1198
1199 int thisOffset = m_rep->offset;
1200 int length = size();
1201 BaseString* base = m_rep->baseString();
1202
1203 // possible cases:
1204 if (length == 0) {
1205 // this is empty - must make a new m_rep because we don't want to pollute the shared empty one
1206 size_t newCapacity = expandedSize(1, 0);
1207 UChar* d;
1208 if (!allocChars(newCapacity).getValue(d))
1209 makeNull();
1210 else {
1211 d[0] = c;
1212 m_rep = Rep::create(d, 1);
1213 m_rep->baseString()->capacity = newCapacity;
1214 }
1215 } else if (m_rep == base && !base->isShared()) {
1216 // this is direct and has refcount of 1 (so we can just alter it directly)
1217 expandCapacity(newCapacityWithOverflowCheck(thisOffset, length, true));
1218 UChar* d = m_rep->data();
1219 if (d) {
1220 d[length] = c;
1221 m_rep->len = length + 1;
1222 m_rep->_hash = 0;
1223 }
1224 } else if (thisOffset + length == base->usedCapacity && length >= minShareSize && !base->isBufferReadOnly()) {
1225 // this reaches the end of the string - extend it and share
1226 expandCapacity(newCapacityWithOverflowCheck(thisOffset, length, true));
1227 UChar* d = m_rep->data();
1228 if (d) {
1229 d[length] = c;
1230 m_rep = Rep::create(m_rep, 0, length + 1);
1231 }
1232 } else {
1233 // This is shared in some way that prevents us from modifying base, so we must make a whole new string.
1234 size_t newCapacity = expandedSize(length + 1, 0);
1235 UChar* d;
1236 if (!allocChars(newCapacity).getValue(d))
1237 makeNull();
1238 else {
1239 copyChars(d, data(), length);
1240 d[length] = c;
1241 m_rep = Rep::create(d, length + 1);
1242 m_rep->baseString()->capacity = newCapacity;
1243 }
1244 }
1245
1246 m_rep->checkConsistency();
1247
1248 return *this;
1249}
1250
1251bool UString::getCString(CStringBuffer& buffer) const
1252{
1253 int length = size();
1254 int neededSize = length + 1;
1255 buffer.resize(neededSize);
1256 char* buf = buffer.data();
1257
1258 UChar ored = 0;
1259 const UChar* p = data();
1260 char* q = buf;
1261 const UChar* limit = p + length;
1262 while (p != limit) {
1263 UChar c = p[0];
1264 ored |= c;
1265 *q = static_cast<char>(c);
1266 ++p;
1267 ++q;
1268 }
1269 *q = '\0';
1270
1271 return !(ored & 0xFF00);
1272}
1273
1274char* UString::ascii() const
1275{
1276 int length = size();
1277 int neededSize = length + 1;
1278 delete[] statBuffer;
1279 statBuffer = new char[neededSize];
1280
1281 const UChar* p = data();
1282 char* q = statBuffer;
1283 const UChar* limit = p + length;
1284 while (p != limit) {
1285 *q = static_cast<char>(p[0]);
1286 ++p;
1287 ++q;
1288 }
1289 *q = '\0';
1290
1291 return statBuffer;
1292}
1293
1294UString& UString::operator=(const char* c)
1295{
1296 if (!c) {
1297 m_rep = &Rep::null();
1298 return *this;
1299 }
1300
1301 if (!c[0]) {
1302 m_rep = &Rep::empty();
1303 return *this;
1304 }
1305
1306 int l = static_cast<int>(strlen(c));
1307 UChar* d;
1308 BaseString* base = m_rep->baseString();
1309 if (!base->isShared() && l <= base->capacity && m_rep == base && m_rep->offset == 0 && base->preCapacity == 0) {
1310 d = base->buf;
1311 m_rep->_hash = 0;
1312 m_rep->len = l;
1313 } else {
1314 if (!allocChars(l).getValue(d)) {
1315 makeNull();
1316 return *this;
1317 }
1318 m_rep = Rep::create(d, l);
1319 }
1320 for (int i = 0; i < l; i++)
1321 d[i] = static_cast<unsigned char>(c[i]); // use unsigned char to zero-extend instead of sign-extend
1322
1323 return *this;
1324}
1325
1326bool UString::is8Bit() const
1327{
1328 const UChar* u = data();
1329 const UChar* limit = u + size();
1330 while (u < limit) {
1331 if (u[0] > 0xFF)
1332 return false;
1333 ++u;
1334 }
1335
1336 return true;
1337}
1338
1339UChar UString::operator[](int pos) const
1340{
1341 if (pos >= size())
1342 return '\0';
1343 return data()[pos];
1344}
1345
1346double UString::toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const
1347{
1348 if (size() == 1) {
1349 UChar c = data()[0];
1350 if (isASCIIDigit(c))
1351 return c - '0';
1352 if (isASCIISpace(c) && tolerateEmptyString)
1353 return 0;
1354 return NaN;
1355 }
1356
1357 // FIXME: If tolerateTrailingJunk is true, then we want to tolerate non-8-bit junk
1358 // after the number, so this is too strict a check.
1359 CStringBuffer s;
1360 if (!getCString(s))
1361 return NaN;
1362 const char* c = s.data();
1363
1364 // skip leading white space
1365 while (isASCIISpace(*c))
1366 c++;
1367
1368 // empty string ?
1369 if (*c == '\0')
1370 return tolerateEmptyString ? 0.0 : NaN;
1371
1372 double d;
1373
1374 // hex number ?
1375 if (*c == '0' && (*(c + 1) == 'x' || *(c + 1) == 'X')) {
1376 const char* firstDigitPosition = c + 2;
1377 c++;
1378 d = 0.0;
1379 while (*(++c)) {
1380 if (*c >= '0' && *c <= '9')
1381 d = d * 16.0 + *c - '0';
1382 else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f'))
1383 d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0;
1384 else
1385 break;
1386 }
1387
1388 if (d >= mantissaOverflowLowerBound)
1389 d = parseIntOverflow(firstDigitPosition, c - firstDigitPosition, 16);
1390 } else {
1391 // regular number ?
1392 char* end;
1393 d = WTF::strtod(c, &end);
1394 if ((d != 0.0 || end != c) && d != Inf && d != -Inf) {
1395 c = end;
1396 } else {
1397 double sign = 1.0;
1398
1399 if (*c == '+')
1400 c++;
1401 else if (*c == '-') {
1402 sign = -1.0;
1403 c++;
1404 }
1405
1406 // We used strtod() to do the conversion. However, strtod() handles
1407 // infinite values slightly differently than JavaScript in that it
1408 // converts the string "inf" with any capitalization to infinity,
1409 // whereas the ECMA spec requires that it be converted to NaN.
1410
1411 if (c[0] == 'I' && c[1] == 'n' && c[2] == 'f' && c[3] == 'i' && c[4] == 'n' && c[5] == 'i' && c[6] == 't' && c[7] == 'y') {
1412 d = sign * Inf;
1413 c += 8;
1414 } else if ((d == Inf || d == -Inf) && *c != 'I' && *c != 'i')
1415 c = end;
1416 else
1417 return NaN;
1418 }
1419 }
1420
1421 // allow trailing white space
1422 while (isASCIISpace(*c))
1423 c++;
1424 // don't allow anything after - unless tolerant=true
1425 if (!tolerateTrailingJunk && *c != '\0')
1426 d = NaN;
1427
1428 return d;
1429}
1430
1431double UString::toDouble(bool tolerateTrailingJunk) const
1432{
1433 return toDouble(tolerateTrailingJunk, true);
1434}
1435
1436double UString::toDouble() const
1437{
1438 return toDouble(false, true);
1439}
1440
1441uint32_t UString::toUInt32(bool* ok) const
1442{
1443 double d = toDouble();
1444 bool b = true;
1445
1446 if (d != static_cast<uint32_t>(d)) {
1447 b = false;
1448 d = 0;
1449 }
1450
1451 if (ok)
1452 *ok = b;
1453
1454 return static_cast<uint32_t>(d);
1455}
1456
1457uint32_t UString::toUInt32(bool* ok, bool tolerateEmptyString) const
1458{
1459 double d = toDouble(false, tolerateEmptyString);
1460 bool b = true;
1461
1462 if (d != static_cast<uint32_t>(d)) {
1463 b = false;
1464 d = 0;
1465 }
1466
1467 if (ok)
1468 *ok = b;
1469
1470 return static_cast<uint32_t>(d);
1471}
1472
1473uint32_t UString::toStrictUInt32(bool* ok) const
1474{
1475 if (ok)
1476 *ok = false;
1477
1478 // Empty string is not OK.
1479 int len = m_rep->len;
1480 if (len == 0)
1481 return 0;
1482 const UChar* p = m_rep->data();
1483 unsigned short c = p[0];
1484
1485 // If the first digit is 0, only 0 itself is OK.
1486 if (c == '0') {
1487 if (len == 1 && ok)
1488 *ok = true;
1489 return 0;
1490 }
1491
1492 // Convert to UInt32, checking for overflow.
1493 uint32_t i = 0;
1494 while (1) {
1495 // Process character, turning it into a digit.
1496 if (c < '0' || c > '9')
1497 return 0;
1498 const unsigned d = c - '0';
1499
1500 // Multiply by 10, checking for overflow out of 32 bits.
1501 if (i > 0xFFFFFFFFU / 10)
1502 return 0;
1503 i *= 10;
1504
1505 // Add in the digit, checking for overflow out of 32 bits.
1506 const unsigned max = 0xFFFFFFFFU - d;
1507 if (i > max)
1508 return 0;
1509 i += d;
1510
1511 // Handle end of string.
1512 if (--len == 0) {
1513 if (ok)
1514 *ok = true;
1515 return i;
1516 }
1517
1518 // Get next character.
1519 c = *(++p);
1520 }
1521}
1522
1523int UString::find(const UString& f, int pos) const
1524{
1525 int fsz = f.size();
1526
1527 if (pos < 0)
1528 pos = 0;
1529
1530 if (fsz == 1) {
1531 UChar ch = f[0];
1532 const UChar* end = data() + size();
1533 for (const UChar* c = data() + pos; c < end; c++) {
1534 if (*c == ch)
1535 return static_cast<int>(c - data());
1536 }
1537 return -1;
1538 }
1539
1540 int sz = size();
1541 if (sz < fsz)
1542 return -1;
1543 if (fsz == 0)
1544 return pos;
1545 const UChar* end = data() + sz - fsz;
1546 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1547 const UChar* fdata = f.data();
1548 unsigned short fchar = fdata[0];
1549 ++fdata;
1550 for (const UChar* c = data() + pos; c <= end; c++) {
1551 if (c[0] == fchar && !memcmp(c + 1, fdata, fsizeminusone))
1552 return static_cast<int>(c - data());
1553 }
1554
1555 return -1;
1556}
1557
1558int UString::find(UChar ch, int pos) const
1559{
1560 if (pos < 0)
1561 pos = 0;
1562 const UChar* end = data() + size();
1563 for (const UChar* c = data() + pos; c < end; c++) {
1564 if (*c == ch)
1565 return static_cast<int>(c - data());
1566 }
1567
1568 return -1;
1569}
1570
1571int UString::rfind(const UString& f, int pos) const
1572{
1573 int sz = size();
1574 int fsz = f.size();
1575 if (sz < fsz)
1576 return -1;
1577 if (pos < 0)
1578 pos = 0;
1579 if (pos > sz - fsz)
1580 pos = sz - fsz;
1581 if (fsz == 0)
1582 return pos;
1583 int fsizeminusone = (fsz - 1) * sizeof(UChar);
1584 const UChar* fdata = f.data();
1585 for (const UChar* c = data() + pos; c >= data(); c--) {
1586 if (*c == *fdata && !memcmp(c + 1, fdata + 1, fsizeminusone))
1587 return static_cast<int>(c - data());
1588 }
1589
1590 return -1;
1591}
1592
1593int UString::rfind(UChar ch, int pos) const
1594{
1595 if (isEmpty())
1596 return -1;
1597 if (pos + 1 >= size())
1598 pos = size() - 1;
1599 for (const UChar* c = data() + pos; c >= data(); c--) {
1600 if (*c == ch)
1601 return static_cast<int>(c - data());
1602 }
1603
1604 return -1;
1605}
1606
1607UString UString::substr(int pos, int len) const
1608{
1609 int s = size();
1610
1611 if (pos < 0)
1612 pos = 0;
1613 else if (pos >= s)
1614 pos = s;
1615 if (len < 0)
1616 len = s;
1617 if (pos + len >= s)
1618 len = s - pos;
1619
1620 if (pos == 0 && len == s)
1621 return *this;
1622
1623 return UString(Rep::create(m_rep, pos, len));
1624}
1625
1626bool operator==(const UString& s1, const char *s2)
1627{
1628 if (s2 == 0)
1629 return s1.isEmpty();
1630
1631 const UChar* u = s1.data();
1632 const UChar* uend = u + s1.size();
1633 while (u != uend && *s2) {
1634 if (u[0] != (unsigned char)*s2)
1635 return false;
1636 s2++;
1637 u++;
1638 }
1639
1640 return u == uend && *s2 == 0;
1641}
1642
1643bool operator<(const UString& s1, const UString& s2)
1644{
1645 const int l1 = s1.size();
1646 const int l2 = s2.size();
1647 const int lmin = l1 < l2 ? l1 : l2;
1648 const UChar* c1 = s1.data();
1649 const UChar* c2 = s2.data();
1650 int l = 0;
1651 while (l < lmin && *c1 == *c2) {
1652 c1++;
1653 c2++;
1654 l++;
1655 }
1656 if (l < lmin)
1657 return (c1[0] < c2[0]);
1658
1659 return (l1 < l2);
1660}
1661
1662bool operator>(const UString& s1, const UString& s2)
1663{
1664 const int l1 = s1.size();
1665 const int l2 = s2.size();
1666 const int lmin = l1 < l2 ? l1 : l2;
1667 const UChar* c1 = s1.data();
1668 const UChar* c2 = s2.data();
1669 int l = 0;
1670 while (l < lmin && *c1 == *c2) {
1671 c1++;
1672 c2++;
1673 l++;
1674 }
1675 if (l < lmin)
1676 return (c1[0] > c2[0]);
1677
1678 return (l1 > l2);
1679}
1680
1681int compare(const UString& s1, const UString& s2)
1682{
1683 const int l1 = s1.size();
1684 const int l2 = s2.size();
1685 const int lmin = l1 < l2 ? l1 : l2;
1686 const UChar* c1 = s1.data();
1687 const UChar* c2 = s2.data();
1688 int l = 0;
1689 while (l < lmin && *c1 == *c2) {
1690 c1++;
1691 c2++;
1692 l++;
1693 }
1694
1695 if (l < lmin)
1696 return (c1[0] > c2[0]) ? 1 : -1;
1697
1698 if (l1 == l2)
1699 return 0;
1700
1701 return (l1 > l2) ? 1 : -1;
1702}
1703
1704bool equal(const UString::Rep* r, const UString::Rep* b)
1705{
1706 int length = r->len;
1707 if (length != b->len)
1708 return false;
1709 const UChar* d = r->data();
1710 const UChar* s = b->data();
1711 for (int i = 0; i != length; ++i) {
1712 if (d[i] != s[i])
1713 return false;
1714 }
1715 return true;
1716}
1717
1718CString UString::UTF8String(bool strict) const
1719{
1720 // Allocate a buffer big enough to hold all the characters.
1721 const int length = size();
1722 Vector<char, 1024> buffer(length * 3);
1723
1724 // Convert to runs of 8-bit characters.
1725 char* p = buffer.data();
1726 const UChar* d = reinterpret_cast<const UChar*>(&data()[0]);
1727 ConversionResult result = convertUTF16ToUTF8(&d, d + length, &p, p + buffer.size(), strict);
1728 if (result != conversionOK)
1729 return CString();
1730
1731 return CString(buffer.data(), p - buffer.data());
1732}
1733
1734// For use in error handling code paths -- having this not be inlined helps avoid PIC branches to fetch the global on Mac OS X.
1735NEVER_INLINE void UString::makeNull()
1736{
1737 m_rep = &Rep::null();
1738}
1739
1740// For use in error handling code paths -- having this not be inlined helps avoid PIC branches to fetch the global on Mac OS X.
1741NEVER_INLINE UString::Rep* UString::nullRep()
1742{
1743 return &Rep::null();
1744}
1745
1746} // namespace JSC
Note: See TracBrowser for help on using the repository browser.