source: webkit/trunk/JavaScriptCore/kjs/ustring.cpp@ 10412

Last change on this file since 10412 was 10265, checked in by darin, 20 years ago

Reviewed by Maciej.

  • kjs/identifier.h: Add a new global nullIdentifier and make Identifier::null a function that returns it.
  • kjs/identifier.cpp: (KJS::Identifier::init): Initialize a global for the null identifier as well as all the other globals for special identifiers.
  • kjs/ustring.h: (KJS::UString::UString): Make this empty constructor inline.
  • kjs/ustring.cpp: Remove the old non-inline version.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.5 KB
Line 
1// -*- c-basic-offset: 2 -*-
2/*
3 * This file is part of the KDE libraries
4 * Copyright (C) 1999-2000 Harri Porten ([email protected])
5 * Copyright (C) 2004 Apple Computer, Inc.
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 Steet, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
21 *
22 */
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <stdlib.h>
29#include <stdio.h>
30#include <ctype.h>
31#ifdef HAVE_STRING_H
32#include <string.h>
33#endif
34#ifdef HAVE_STRINGS_H
35#include <strings.h>
36#endif
37
38#include "fast_malloc.h"
39#include "ustring.h"
40#include "operations.h"
41#include "identifier.h"
42#include <math.h>
43#include "dtoa.h"
44
45#include <algorithm>
46
47using std::max;
48
49#include <unicode/uchar.h>
50
51namespace KJS {
52
53extern const double NaN;
54extern const double Inf;
55
56CString::CString(const char *c)
57{
58 length = strlen(c);
59 data = new char[length+1];
60 memcpy(data, c, length + 1);
61}
62
63CString::CString(const char *c, int len)
64{
65 length = len;
66 data = new char[len+1];
67 memcpy(data, c, len);
68 data[len] = 0;
69}
70
71CString::CString(const CString &b)
72{
73 length = b.length;
74 if (length > 0 && b.data) {
75 data = new char[length+1];
76 memcpy(data, b.data, length + 1);
77 }
78 else {
79 data = 0;
80 }
81}
82
83CString::~CString()
84{
85 delete [] data;
86}
87
88CString &CString::append(const CString &t)
89{
90 char *n;
91 n = new char[length+t.length+1];
92 if (length)
93 memcpy(n, data, length);
94 if (t.length)
95 memcpy(n+length, t.data, t.length);
96 length += t.length;
97 n[length] = 0;
98
99 delete [] data;
100 data = n;
101
102 return *this;
103}
104
105CString &CString::operator=(const char *c)
106{
107 if (data)
108 delete [] data;
109 length = strlen(c);
110 data = new char[length+1];
111 memcpy(data, c, length + 1);
112
113 return *this;
114}
115
116CString &CString::operator=(const CString &str)
117{
118 if (this == &str)
119 return *this;
120
121 if (data)
122 delete [] data;
123 length = str.length;
124 if (length > 0 && str.data) {
125 data = new char[length + 1];
126 memcpy(data, str.data, length + 1);
127 }
128 else {
129 data = 0;
130 }
131
132 return *this;
133}
134
135bool operator==(const CString& c1, const CString& c2)
136{
137 int len = c1.size();
138 return len == c2.size() && (len == 0 || memcmp(c1.c_str(), c2.c_str(), len) == 0);
139}
140
141// Hack here to avoid a global with a constructor; point to an unsigned short instead of a UChar.
142static unsigned short almostUChar;
143static UChar *const nonNullUCharPointer = reinterpret_cast<UChar *>(&almostUChar);
144UString::Rep UString::Rep::null = { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
145UString::Rep UString::Rep::empty = { 0, 0, 1, 0, 0, 0, nonNullUCharPointer, 0, 0, 0, 0 };
146const int normalStatBufferSize = 4096;
147static char *statBuffer = 0;
148static int statBufferSize = 0;
149
150UChar UChar::toLower() const
151{
152 return static_cast<unsigned short>(u_tolower(uc));
153}
154
155UChar UChar::toUpper() const
156{
157 return static_cast<unsigned short>(u_toupper(uc));
158}
159
160UCharReference& UCharReference::operator=(UChar c)
161{
162 str->detach();
163 if (offset < str->rep->len)
164 *(str->rep->data() + offset) = c;
165 /* TODO: lengthen string ? */
166 return *this;
167}
168
169UChar& UCharReference::ref() const
170{
171 if (offset < str->rep->len)
172 return *(str->rep->data() + offset);
173 else {
174 static UChar callerBetterNotModifyThis('\0');
175 return callerBetterNotModifyThis;
176 }
177}
178
179UString::Rep *UString::Rep::createCopying(const UChar *d, int l)
180{
181 int sizeInBytes = l * sizeof(UChar);
182 UChar *copyD = static_cast<UChar *>(kjs_fast_malloc(sizeInBytes));
183 memcpy(copyD, d, sizeInBytes);
184
185 return create(copyD, l);
186}
187
188UString::Rep *UString::Rep::create(UChar *d, int l)
189{
190 Rep *r = new Rep;
191 r->offset = 0;
192 r->len = l;
193 r->rc = 1;
194 r->_hash = 0;
195 r->isIdentifier = 0;
196 r->baseString = 0;
197 r->buf = d;
198 r->usedCapacity = l;
199 r->capacity = l;
200 r->usedPreCapacity = 0;
201 r->preCapacity = 0;
202 return r;
203}
204
205UString::Rep *UString::Rep::create(Rep *base, int offset, int length)
206{
207 assert(base);
208
209 int baseOffset = base->offset;
210
211 if (base->baseString) {
212 base = base->baseString;
213 }
214
215 assert(-(offset + baseOffset) <= base->usedPreCapacity);
216 assert(offset + baseOffset + length <= base->usedCapacity);
217
218 Rep *r = new Rep;
219 r->offset = baseOffset + offset;
220 r->len = length;
221 r->rc = 1;
222 r->_hash = 0;
223 r->isIdentifier = 0;
224 r->baseString = base;
225 base->ref();
226 r->buf = 0;
227 r->usedCapacity = 0;
228 r->capacity = 0;
229 r->usedPreCapacity = 0;
230 r->preCapacity = 0;
231 return r;
232}
233
234void UString::Rep::destroy()
235{
236 if (isIdentifier)
237 Identifier::remove(this);
238 if (baseString) {
239 baseString->deref();
240 } else {
241 kjs_fast_free(buf);
242 }
243 delete this;
244}
245
246// Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
247// or anything like that.
248const unsigned PHI = 0x9e3779b9U;
249
250// Paul Hsieh's SuperFastHash
251// http://www.azillionmonkeys.com/qed/hash.html
252unsigned UString::Rep::computeHash(const UChar *s, int len)
253{
254 unsigned l = len;
255 uint32_t hash = PHI;
256 uint32_t tmp;
257
258 int rem = l & 1;
259 l >>= 1;
260
261 // Main loop
262 for (; l > 0; l--) {
263 hash += s[0].uc;
264 tmp = (s[1].uc << 11) ^ hash;
265 hash = (hash << 16) ^ tmp;
266 s += 2;
267 hash += hash >> 11;
268 }
269
270 // Handle end case
271 if (rem) {
272 hash += s[0].uc;
273 hash ^= hash << 11;
274 hash += hash >> 17;
275 }
276
277 // Force "avalanching" of final 127 bits
278 hash ^= hash << 3;
279 hash += hash >> 5;
280 hash ^= hash << 2;
281 hash += hash >> 15;
282 hash ^= hash << 10;
283
284 // this avoids ever returning a hash code of 0, since that is used to
285 // signal "hash not computed yet", using a value that is likely to be
286 // effectively the same as 0 when the low bits are masked
287 if (hash == 0)
288 hash = 0x80000000;
289
290 return hash;
291}
292
293// Paul Hsieh's SuperFastHash
294// http://www.azillionmonkeys.com/qed/hash.html
295unsigned UString::Rep::computeHash(const char *s)
296{
297 // This hash is designed to work on 16-bit chunks at a time. But since the normal case
298 // (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
299 // were 16-bit chunks, which should give matching results
300
301 uint32_t hash = PHI;
302 uint32_t tmp;
303 unsigned l = strlen(s);
304
305 int rem = l & 1;
306 l >>= 1;
307
308 // Main loop
309 for (; l > 0; l--) {
310 hash += (unsigned char)s[0];
311 tmp = ((unsigned char)s[1] << 11) ^ hash;
312 hash = (hash << 16) ^ tmp;
313 s += 2;
314 hash += hash >> 11;
315 }
316
317 // Handle end case
318 if (rem) {
319 hash += (unsigned char)s[0];
320 hash ^= hash << 11;
321 hash += hash >> 17;
322 }
323
324 // Force "avalanching" of final 127 bits
325 hash ^= hash << 3;
326 hash += hash >> 5;
327 hash ^= hash << 2;
328 hash += hash >> 15;
329 hash ^= hash << 10;
330
331 // this avoids ever returning a hash code of 0, since that is used to
332 // signal "hash not computed yet", using a value that is likely to be
333 // effectively the same as 0 when the low bits are masked
334 if (hash == 0)
335 hash = 0x80000000;
336
337 return hash;
338}
339
340// put these early so they can be inlined
341inline int UString::expandedSize(int size, int otherSize) const
342{
343 int s = (size * 11 / 10) + 1 + otherSize;
344 return s;
345}
346
347inline int UString::usedCapacity() const
348{
349 return rep->baseString ? rep->baseString->usedCapacity : rep->usedCapacity;
350}
351
352inline int UString::usedPreCapacity() const
353{
354 return rep->baseString ? rep->baseString->usedPreCapacity : rep->usedPreCapacity;
355}
356
357void UString::expandCapacity(int requiredLength)
358{
359 Rep *r = rep->baseString ? rep->baseString : rep;
360
361 if (requiredLength > r->capacity) {
362 int newCapacity = expandedSize(requiredLength, r->preCapacity);
363 r->buf = static_cast<UChar *>(kjs_fast_realloc(r->buf, newCapacity * sizeof(UChar)));
364 r->capacity = newCapacity - r->preCapacity;
365 }
366 if (requiredLength > r->usedCapacity) {
367 r->usedCapacity = requiredLength;
368 }
369}
370
371void UString::expandPreCapacity(int requiredPreCap)
372{
373 Rep *r = rep->baseString ? rep->baseString : rep;
374
375 if (requiredPreCap > r->preCapacity) {
376 int newCapacity = expandedSize(requiredPreCap, r->capacity);
377 int delta = newCapacity - r->capacity - r->preCapacity;
378
379 UChar *newBuf = static_cast<UChar *>(kjs_fast_malloc(newCapacity * sizeof(UChar)));
380 memcpy(newBuf + delta, r->buf, (r->capacity + r->preCapacity) * sizeof(UChar));
381 kjs_fast_free(r->buf);
382 r->buf = newBuf;
383
384 r->preCapacity = newCapacity - r->capacity;
385 }
386 if (requiredPreCap > r->usedPreCapacity) {
387 r->usedPreCapacity = requiredPreCap;
388 }
389}
390
391
392UString::UString(char c)
393{
394 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar)));
395 d[0] = c;
396 rep = Rep::create(d, 1);
397}
398
399UString::UString(const char *c)
400{
401 if (!c) {
402 attach(&Rep::null);
403 return;
404 }
405 int length = strlen(c);
406 if (length == 0) {
407 attach(&Rep::empty);
408 return;
409 }
410 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * length));
411 for (int i = 0; i < length; i++)
412 d[i].uc = c[i];
413 rep = Rep::create(d, length);
414}
415
416UString::UString(const UChar *c, int length)
417{
418 if (length == 0) {
419 attach(&Rep::empty);
420 return;
421 }
422 rep = Rep::createCopying(c, length);
423}
424
425UString::UString(UChar *c, int length, bool copy)
426{
427 if (length == 0) {
428 attach(&Rep::empty);
429 return;
430 }
431 if (copy) {
432 rep = Rep::createCopying(c, length);
433 } else {
434 rep = Rep::create(c, length);
435 }
436}
437
438UString::UString(const UString &a, const UString &b)
439{
440 int aSize = a.size();
441 int aOffset = a.rep->offset;
442 int bSize = b.size();
443 int bOffset = b.rep->offset;
444 int length = aSize + bSize;
445
446 // possible cases:
447
448 if (aSize == 0) {
449 // a is empty
450 attach(b.rep);
451 } else if (bSize == 0) {
452 // b is empty
453 attach(a.rep);
454 } else if (aOffset + aSize == a.usedCapacity() && 4 * aSize >= bSize &&
455 (-bOffset != b.usedPreCapacity() || aSize >= bSize)) {
456 // - a reaches the end of its buffer so it qualifies for shared append
457 // - also, it's at least a quarter the length of b - appending to a much shorter
458 // string does more harm than good
459 // - however, if b qualifies for prepend and is longer than a, we'd rather prepend
460 UString x(a);
461 x.expandCapacity(aOffset + length);
462 memcpy(const_cast<UChar *>(a.data() + aSize), b.data(), bSize * sizeof(UChar));
463 rep = Rep::create(a.rep, 0, length);
464 } else if (-bOffset == b.usedPreCapacity() && 4 * bSize >= aSize) {
465 // - b reaches the beginning of its buffer so it qualifies for shared prepend
466 // - also, it's at least a quarter the length of a - prepending to a much shorter
467 // string does more harm than good
468 UString y(b);
469 y.expandPreCapacity(-bOffset + aSize);
470 memcpy(const_cast<UChar *>(b.data() - aSize), a.data(), aSize * sizeof(UChar));
471 rep = Rep::create(b.rep, -aSize, length);
472 } else {
473 // a does not qualify for append, and b does not qualify for prepend, gotta make a whole new string
474 int newCapacity = expandedSize(length, 0);
475 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * newCapacity));
476 memcpy(d, a.data(), aSize * sizeof(UChar));
477 memcpy(d + aSize, b.data(), bSize * sizeof(UChar));
478 rep = Rep::create(d, length);
479 rep->capacity = newCapacity;
480 }
481}
482
483const UString &UString::null()
484{
485 static UString n;
486 return n;
487}
488
489UString UString::from(int i)
490{
491 return from((long)i);
492}
493
494UString UString::from(unsigned int u)
495{
496 UChar buf[20];
497 UChar *end = buf + 20;
498 UChar *p = end;
499
500 if (u == 0) {
501 *--p = '0';
502 } else {
503 while (u) {
504 *--p = (unsigned short)((u % 10) + '0');
505 u /= 10;
506 }
507 }
508
509 return UString(p, end - p);
510}
511
512UString UString::from(long l)
513{
514 UChar buf[20];
515 UChar *end = buf + 20;
516 UChar *p = end;
517
518 if (l == 0) {
519 *--p = '0';
520 } else if (l == LONG_MIN) {
521 char minBuf[20];
522 sprintf(minBuf, "%ld", LONG_MIN);
523 return UString(minBuf);
524 } else {
525 bool negative = false;
526 if (l < 0) {
527 negative = true;
528 l = -l;
529 }
530 while (l) {
531 *--p = (unsigned short)((l % 10) + '0');
532 l /= 10;
533 }
534 if (negative) {
535 *--p = '-';
536 }
537 }
538
539 return UString(p, end - p);
540}
541
542UString UString::from(double d)
543{
544 char buf[80];
545 int decimalPoint;
546 int sign;
547
548 char *result = kjs_dtoa(d, 0, 0, &decimalPoint, &sign, NULL);
549 int length = strlen(result);
550
551 int i = 0;
552 if (sign) {
553 buf[i++] = '-';
554 }
555
556 if (decimalPoint <= 0 && decimalPoint > -6) {
557 buf[i++] = '0';
558 buf[i++] = '.';
559 for (int j = decimalPoint; j < 0; j++) {
560 buf[i++] = '0';
561 }
562 strcpy(buf + i, result);
563 } else if (decimalPoint <= 21 && decimalPoint > 0) {
564 if (length <= decimalPoint) {
565 strcpy(buf + i, result);
566 i += length;
567 for (int j = 0; j < decimalPoint - length; j++) {
568 buf[i++] = '0';
569 }
570 buf[i] = '\0';
571 } else {
572 strncpy(buf + i, result, decimalPoint);
573 i += decimalPoint;
574 buf[i++] = '.';
575 strcpy(buf + i, result + decimalPoint);
576 }
577 } else if (result[0] < '0' || result[0] > '9') {
578 strcpy(buf + i, result);
579 } else {
580 buf[i++] = result[0];
581 if (length > 1) {
582 buf[i++] = '.';
583 strcpy(buf + i, result + 1);
584 i += length - 1;
585 }
586
587 buf[i++] = 'e';
588 buf[i++] = (decimalPoint >= 0) ? '+' : '-';
589 // decimalPoint can't be more than 3 digits decimal given the
590 // nature of float representation
591 int exponential = decimalPoint - 1;
592 if (exponential < 0) {
593 exponential = exponential * -1;
594 }
595 if (exponential >= 100) {
596 buf[i++] = '0' + exponential / 100;
597 }
598 if (exponential >= 10) {
599 buf[i++] = '0' + (exponential % 100) / 10;
600 }
601 buf[i++] = '0' + exponential % 10;
602 buf[i++] = '\0';
603 }
604
605 kjs_freedtoa(result);
606
607 return UString(buf);
608}
609
610UString UString::spliceSubstringsWithSeparators(const Range *substringRanges, int rangeCount, const UString *separators, int separatorCount) const
611{
612 int totalLength = 0;
613
614 for (int i = 0; i < rangeCount; i++) {
615 totalLength += substringRanges[i].length;
616 }
617 for (int i = 0; i < separatorCount; i++) {
618 totalLength += separators[i].size();
619 }
620
621 UChar *buffer = static_cast<UChar *>(kjs_fast_malloc(totalLength * sizeof(UChar)));
622
623 int maxCount = max(rangeCount, separatorCount);
624 int bufferPos = 0;
625 for (int i = 0; i < maxCount; i++) {
626 if (i < rangeCount) {
627 memcpy(buffer + bufferPos, data() + substringRanges[i].position, substringRanges[i].length * sizeof(UChar));
628 bufferPos += substringRanges[i].length;
629 }
630 if (i < separatorCount) {
631 memcpy(buffer + bufferPos, separators[i].data(), separators[i].size() * sizeof(UChar));
632 bufferPos += separators[i].size();
633 }
634 }
635
636 UString::Rep *rep = UString::Rep::create(buffer, totalLength);
637 UString result = UString(rep);
638 rep->deref();
639
640 return result;
641}
642
643
644
645UString &UString::append(const UString &t)
646{
647 int thisSize = size();
648 int thisOffset = rep->offset;
649 int tSize = t.size();
650 int length = thisSize + tSize;
651
652 // possible cases:
653 if (thisSize == 0) {
654 // this is empty
655 *this = t;
656 } else if (tSize == 0) {
657 // t is empty
658 } else if (!rep->baseString && rep->rc == 1) {
659 // this is direct and has refcount of 1 (so we can just alter it directly)
660 expandCapacity(thisOffset + length);
661 memcpy(const_cast<UChar *>(data() + thisSize), t.data(), tSize * sizeof(UChar));
662 rep->len = length;
663 rep->_hash = 0;
664 } else if (thisOffset + thisSize == usedCapacity()) {
665 // this reaches the end of the buffer - extend it
666 expandCapacity(thisOffset + length);
667 memcpy(const_cast<UChar *>(data() + thisSize), t.data(), tSize * sizeof(UChar));
668 Rep *newRep = Rep::create(rep, 0, length);
669 release();
670 rep = newRep;
671 } else {
672 // this is shared with someone using more capacity, gotta make a whole new string
673 int newCapacity = expandedSize(length, 0);
674 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * newCapacity));
675 memcpy(d, data(), thisSize * sizeof(UChar));
676 memcpy(const_cast<UChar *>(d + thisSize), t.data(), tSize * sizeof(UChar));
677 release();
678 rep = Rep::create(d, length);
679 rep->capacity = newCapacity;
680 }
681
682 return *this;
683}
684
685UString &UString::append(const char *t)
686{
687 int thisSize = size();
688 int thisOffset = rep->offset;
689 int tSize = strlen(t);
690 int length = thisSize + tSize;
691
692 // possible cases:
693 if (thisSize == 0) {
694 // this is empty
695 *this = t;
696 } else if (tSize == 0) {
697 // t is empty, we'll just return *this below.
698 } else if (!rep->baseString && rep->rc == 1) {
699 // this is direct and has refcount of 1 (so we can just alter it directly)
700 expandCapacity(thisOffset + length);
701 UChar *d = const_cast<UChar *>(data());
702 for (int i = 0; i < tSize; ++i)
703 d[thisSize+i] = t[i];
704 rep->len = length;
705 rep->_hash = 0;
706 } else if (thisOffset + thisSize == usedCapacity()) {
707 // this string reaches the end of the buffer - extend it
708 expandCapacity(thisOffset + length);
709 UChar *d = const_cast<UChar *>(data());
710 for (int i = 0; i < tSize; ++i)
711 d[thisSize+i] = t[i];
712 Rep *newRep = Rep::create(rep, 0, length);
713 release();
714 rep = newRep;
715 } else {
716 // this is shared with someone using more capacity, gotta make a whole new string
717 int newCapacity = expandedSize(length, 0);
718 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * newCapacity));
719 memcpy(d, data(), thisSize * sizeof(UChar));
720 for (int i = 0; i < tSize; ++i)
721 d[thisSize+i] = t[i];
722 release();
723 rep = Rep::create(d, length);
724 rep->capacity = newCapacity;
725 }
726
727 return *this;
728}
729
730UString &UString::append(unsigned short c)
731{
732 int thisOffset = rep->offset;
733 int length = size();
734
735 // possible cases:
736 if (length == 0) {
737 // this is empty - must make a new rep because we don't want to pollute the shared empty one
738 int newCapacity = expandedSize(1, 0);
739 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * newCapacity));
740 d[0] = c;
741 release();
742 rep = Rep::create(d, 1);
743 rep->capacity = newCapacity;
744 } else if (!rep->baseString && rep->rc == 1) {
745 // this is direct and has refcount of 1 (so we can just alter it directly)
746 expandCapacity(thisOffset + length + 1);
747 UChar *d = const_cast<UChar *>(data());
748 d[length] = c;
749 rep->len = length + 1;
750 rep->_hash = 0;
751 } else if (thisOffset + length == usedCapacity()) {
752 // this reaches the end of the string - extend it and share
753 expandCapacity(thisOffset + length + 1);
754 UChar *d = const_cast<UChar *>(data());
755 d[length] = c;
756 Rep *newRep = Rep::create(rep, 0, length + 1);
757 release();
758 rep = newRep;
759 } else {
760 // this is shared with someone using more capacity, gotta make a whole new string
761 int newCapacity = expandedSize((length + 1), 0);
762 UChar *d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * newCapacity));
763 memcpy(d, data(), length * sizeof(UChar));
764 d[length] = c;
765 release();
766 rep = Rep::create(d, length);
767 rep->capacity = newCapacity;
768 }
769
770 return *this;
771}
772
773CString UString::cstring() const
774{
775 return ascii();
776}
777
778char *UString::ascii() const
779{
780 // Never make the buffer smaller than normalStatBufferSize.
781 // Thus we almost never need to reallocate.
782 int length = size();
783 int neededSize = length + 1;
784 if (neededSize < normalStatBufferSize) {
785 neededSize = normalStatBufferSize;
786 }
787 if (neededSize != statBufferSize) {
788 delete [] statBuffer;
789 statBuffer = new char [neededSize];
790 statBufferSize = neededSize;
791 }
792
793 const UChar *p = data();
794 char *q = statBuffer;
795 const UChar *limit = p + length;
796 while (p != limit) {
797 *q = p->uc;
798 ++p;
799 ++q;
800 }
801 *q = '\0';
802
803 return statBuffer;
804}
805
806#ifdef KJS_DEBUG_MEM
807void UString::globalClear()
808{
809 delete [] statBuffer;
810 statBuffer = 0;
811 statBufferSize = 0;
812}
813#endif
814
815UString &UString::operator=(const char *c)
816{
817 int l = c ? strlen(c) : 0;
818 UChar *d;
819 if (rep->rc == 1 && l <= rep->capacity && !rep->baseString && rep->offset == 0 && rep->preCapacity == 0) {
820 d = rep->buf;
821 rep->_hash = 0;
822 } else {
823 release();
824 d = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * l));
825 rep = Rep::create(d, l);
826 }
827 for (int i = 0; i < l; i++)
828 d[i].uc = c[i];
829
830 return *this;
831}
832
833UString &UString::operator=(const UString &str)
834{
835 str.rep->ref();
836 release();
837 rep = str.rep;
838
839 return *this;
840}
841
842bool UString::is8Bit() const
843{
844 const UChar *u = data();
845 const UChar *limit = u + size();
846 while (u < limit) {
847 if (u->uc > 0xFF)
848 return false;
849 ++u;
850 }
851
852 return true;
853}
854
855UChar UString::operator[](int pos) const
856{
857 if (pos >= size())
858 return '\0';
859 return data()[pos];
860}
861
862UCharReference UString::operator[](int pos)
863{
864 /* TODO: boundary check */
865 return UCharReference(this, pos);
866}
867
868double UString::toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const
869{
870 double d;
871
872 // FIXME: If tolerateTrailingJunk is true, then we want to tolerate non-8-bit junk
873 // after the number, so is8Bit is too strict a check.
874 if (!is8Bit())
875 return NaN;
876
877 const char *c = ascii();
878
879 // skip leading white space
880 while (isspace(*c))
881 c++;
882
883 // empty string ?
884 if (*c == '\0')
885 return tolerateEmptyString ? 0.0 : NaN;
886
887 // hex number ?
888 if (*c == '0' && (*(c+1) == 'x' || *(c+1) == 'X')) {
889 c++;
890 d = 0.0;
891 while (*(++c)) {
892 if (*c >= '0' && *c <= '9')
893 d = d * 16.0 + *c - '0';
894 else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f'))
895 d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0;
896 else
897 break;
898 }
899 } else {
900 // regular number ?
901 char *end;
902 d = kjs_strtod(c, &end);
903 if ((d != 0.0 || end != c) && d != HUGE_VAL && d != -HUGE_VAL) {
904 c = end;
905 } else {
906 // infinity ?
907 d = 1.0;
908 if (*c == '+')
909 c++;
910 else if (*c == '-') {
911 d = -1.0;
912 c++;
913 }
914 if (strncmp(c, "Infinity", 8) != 0)
915 return NaN;
916 d = d * Inf;
917 c += 8;
918 }
919 }
920
921 // allow trailing white space
922 while (isspace(*c))
923 c++;
924 // don't allow anything after - unless tolerant=true
925 if (!tolerateTrailingJunk && *c != '\0')
926 d = NaN;
927
928 return d;
929}
930
931double UString::toDouble(bool tolerateTrailingJunk) const
932{
933 return toDouble(tolerateTrailingJunk, true);
934}
935
936double UString::toDouble() const
937{
938 return toDouble(false, true);
939}
940
941unsigned long UString::toULong(bool *ok, bool tolerateEmptyString) const
942{
943 double d = toDouble(false, tolerateEmptyString);
944 bool b = true;
945
946 if (isNaN(d) || d != static_cast<unsigned long>(d)) {
947 b = false;
948 d = 0;
949 }
950
951 if (ok)
952 *ok = b;
953
954 return static_cast<unsigned long>(d);
955}
956
957unsigned long UString::toULong(bool *ok) const
958{
959 return toULong(ok, true);
960}
961
962uint32_t UString::toUInt32(bool *ok) const
963{
964 double d = toDouble();
965 bool b = true;
966
967 if (isNaN(d) || d != static_cast<uint32_t>(d)) {
968 b = false;
969 d = 0;
970 }
971
972 if (ok)
973 *ok = b;
974
975 return static_cast<uint32_t>(d);
976}
977
978uint32_t UString::toStrictUInt32(bool *ok) const
979{
980 if (ok)
981 *ok = false;
982
983 // Empty string is not OK.
984 int len = rep->len;
985 if (len == 0)
986 return 0;
987 const UChar *p = rep->data();
988 unsigned short c = p->unicode();
989
990 // If the first digit is 0, only 0 itself is OK.
991 if (c == '0') {
992 if (len == 1 && ok)
993 *ok = true;
994 return 0;
995 }
996
997 // Convert to UInt32, checking for overflow.
998 uint32_t i = 0;
999 while (1) {
1000 // Process character, turning it into a digit.
1001 if (c < '0' || c > '9')
1002 return 0;
1003 const unsigned d = c - '0';
1004
1005 // Multiply by 10, checking for overflow out of 32 bits.
1006 if (i > 0xFFFFFFFFU / 10)
1007 return 0;
1008 i *= 10;
1009
1010 // Add in the digit, checking for overflow out of 32 bits.
1011 const unsigned max = 0xFFFFFFFFU - d;
1012 if (i > max)
1013 return 0;
1014 i += d;
1015
1016 // Handle end of string.
1017 if (--len == 0) {
1018 if (ok)
1019 *ok = true;
1020 return i;
1021 }
1022
1023 // Get next character.
1024 c = (++p)->unicode();
1025 }
1026}
1027
1028// Rule from ECMA 15.2 about what an array index is.
1029// Must exactly match string form of an unsigned integer, and be less than 2^32 - 1.
1030unsigned UString::toArrayIndex(bool *ok) const
1031{
1032 unsigned i = toStrictUInt32(ok);
1033 if (i >= 0xFFFFFFFFU && ok)
1034 *ok = false;
1035 return i;
1036}
1037
1038int UString::find(const UString &f, int pos) const
1039{
1040 int sz = size();
1041 int fsz = f.size();
1042 if (sz < fsz)
1043 return -1;
1044 if (pos < 0)
1045 pos = 0;
1046 if (fsz == 0)
1047 return pos;
1048 const UChar *end = data() + sz - fsz;
1049 long fsizeminusone = (fsz - 1) * sizeof(UChar);
1050 const UChar *fdata = f.data();
1051 unsigned short fchar = fdata->uc;
1052 ++fdata;
1053 for (const UChar *c = data() + pos; c <= end; c++)
1054 if (c->uc == fchar && !memcmp(c + 1, fdata, fsizeminusone))
1055 return (c-data());
1056
1057 return -1;
1058}
1059
1060int UString::find(UChar ch, int pos) const
1061{
1062 if (pos < 0)
1063 pos = 0;
1064 const UChar *end = data() + size();
1065 for (const UChar *c = data() + pos; c < end; c++)
1066 if (*c == ch)
1067 return (c-data());
1068
1069 return -1;
1070}
1071
1072int UString::rfind(const UString &f, int pos) const
1073{
1074 int sz = size();
1075 int fsz = f.size();
1076 if (sz < fsz)
1077 return -1;
1078 if (pos < 0)
1079 pos = 0;
1080 if (pos > sz - fsz)
1081 pos = sz - fsz;
1082 if (fsz == 0)
1083 return pos;
1084 long fsizeminusone = (fsz - 1) * sizeof(UChar);
1085 const UChar *fdata = f.data();
1086 for (const UChar *c = data() + pos; c >= data(); c--) {
1087 if (*c == *fdata && !memcmp(c + 1, fdata + 1, fsizeminusone))
1088 return (c-data());
1089 }
1090
1091 return -1;
1092}
1093
1094int UString::rfind(UChar ch, int pos) const
1095{
1096 if (isEmpty())
1097 return -1;
1098 if (pos + 1 >= size())
1099 pos = size() - 1;
1100 for (const UChar *c = data() + pos; c >= data(); c--) {
1101 if (*c == ch)
1102 return (c-data());
1103 }
1104
1105 return -1;
1106}
1107
1108UString UString::substr(int pos, int len) const
1109{
1110 int s = size();
1111
1112 if (pos < 0)
1113 pos = 0;
1114 else if (pos >= s)
1115 pos = s;
1116 if (len < 0)
1117 len = s;
1118 if (pos + len >= s)
1119 len = s - pos;
1120
1121 if (pos == 0 && len == s)
1122 return *this;
1123
1124 Rep *newRep = Rep::create(rep, pos, len);
1125 UString result(newRep);
1126 newRep->deref();
1127
1128 return result;
1129}
1130
1131void UString::detach()
1132{
1133 if (rep->rc > 1 || rep->baseString) {
1134 int l = size();
1135 UChar *n = static_cast<UChar *>(kjs_fast_malloc(sizeof(UChar) * l));
1136 memcpy(n, data(), l * sizeof(UChar));
1137 release();
1138 rep = Rep::create(n, l);
1139 }
1140}
1141
1142bool operator==(const UString& s1, const UString& s2)
1143{
1144 if (s1.rep->len != s2.rep->len)
1145 return false;
1146
1147 return (memcmp(s1.rep->data(), s2.rep->data(),
1148 s1.rep->len * sizeof(UChar)) == 0);
1149}
1150
1151bool operator==(const UString& s1, const char *s2)
1152{
1153 if (s2 == 0) {
1154 return s1.isEmpty();
1155 }
1156
1157 const UChar *u = s1.data();
1158 const UChar *uend = u + s1.size();
1159 while (u != uend && *s2) {
1160 if (u->uc != (unsigned char)*s2)
1161 return false;
1162 s2++;
1163 u++;
1164 }
1165
1166 return u == uend && *s2 == 0;
1167}
1168
1169bool operator<(const UString& s1, const UString& s2)
1170{
1171 const int l1 = s1.size();
1172 const int l2 = s2.size();
1173 const int lmin = l1 < l2 ? l1 : l2;
1174 const UChar *c1 = s1.data();
1175 const UChar *c2 = s2.data();
1176 int l = 0;
1177 while (l < lmin && *c1 == *c2) {
1178 c1++;
1179 c2++;
1180 l++;
1181 }
1182 if (l < lmin)
1183 return (c1->uc < c2->uc);
1184
1185 return (l1 < l2);
1186}
1187
1188int compare(const UString& s1, const UString& s2)
1189{
1190 const int l1 = s1.size();
1191 const int l2 = s2.size();
1192 const int lmin = l1 < l2 ? l1 : l2;
1193 const UChar *c1 = s1.data();
1194 const UChar *c2 = s2.data();
1195 int l = 0;
1196 while (l < lmin && *c1 == *c2) {
1197 c1++;
1198 c2++;
1199 l++;
1200 }
1201 if (l < lmin)
1202 return (c1->uc > c2->uc) ? 1 : -1;
1203
1204 if (l1 == l2) {
1205 return 0;
1206 }
1207 return (l1 < l2) ? 1 : -1;
1208}
1209
1210inline int inlineUTF8SequenceLengthNonASCII(char b0)
1211{
1212 if ((b0 & 0xC0) != 0xC0)
1213 return 0;
1214 if ((b0 & 0xE0) == 0xC0)
1215 return 2;
1216 if ((b0 & 0xF0) == 0xE0)
1217 return 3;
1218 if ((b0 & 0xF8) == 0xF0)
1219 return 4;
1220 return 0;
1221}
1222
1223int UTF8SequenceLengthNonASCII(char b0)
1224{
1225 return inlineUTF8SequenceLengthNonASCII(b0);
1226}
1227
1228inline int inlineUTF8SequenceLength(char b0)
1229{
1230 return (b0 & 0x80) == 0 ? 1 : UTF8SequenceLengthNonASCII(b0);
1231}
1232
1233// Given a first byte, gives the length of the UTF-8 sequence it begins.
1234// Returns 0 for bytes that are not legal starts of UTF-8 sequences.
1235// Only allows sequences of up to 4 bytes, since that works for all Unicode characters (U-00000000 to U-0010FFFF).
1236int UTF8SequenceLength(char b0)
1237{
1238 return (b0 & 0x80) == 0 ? 1 : inlineUTF8SequenceLengthNonASCII(b0);
1239}
1240
1241// Takes a null-terminated C-style string with a UTF-8 sequence in it and converts it to a character.
1242// Only allows Unicode characters (U-00000000 to U-0010FFFF).
1243// Returns -1 if the sequence is not valid (including presence of extra bytes).
1244int decodeUTF8Sequence(const char *sequence)
1245{
1246 // Handle 0-byte sequences (never valid).
1247 const unsigned char b0 = sequence[0];
1248 const int length = inlineUTF8SequenceLength(b0);
1249 if (length == 0)
1250 return -1;
1251
1252 // Handle 1-byte sequences (plain ASCII).
1253 const unsigned char b1 = sequence[1];
1254 if (length == 1) {
1255 if (b1)
1256 return -1;
1257 return b0;
1258 }
1259
1260 // Handle 2-byte sequences.
1261 if ((b1 & 0xC0) != 0x80)
1262 return -1;
1263 const unsigned char b2 = sequence[2];
1264 if (length == 2) {
1265 if (b2)
1266 return -1;
1267 const int c = ((b0 & 0x1F) << 6) | (b1 & 0x3F);
1268 if (c < 0x80)
1269 return -1;
1270 return c;
1271 }
1272
1273 // Handle 3-byte sequences.
1274 if ((b2 & 0xC0) != 0x80)
1275 return -1;
1276 const unsigned char b3 = sequence[3];
1277 if (length == 3) {
1278 if (b3)
1279 return -1;
1280 const int c = ((b0 & 0xF) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F);
1281 if (c < 0x800)
1282 return -1;
1283 // UTF-16 surrogates should never appear in UTF-8 data.
1284 if (c >= 0xD800 && c <= 0xDFFF)
1285 return -1;
1286 // Backwards BOM and U+FFFF should never appear in UTF-8 data.
1287 if (c == 0xFFFE || c == 0xFFFF)
1288 return -1;
1289 return c;
1290 }
1291
1292 // Handle 4-byte sequences.
1293 if ((b3 & 0xC0) != 0x80)
1294 return -1;
1295 const unsigned char b4 = sequence[4];
1296 if (length == 4) {
1297 if (b4)
1298 return -1;
1299 const int c = ((b0 & 0x7) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);
1300 if (c < 0x10000 || c > 0x10FFFF)
1301 return -1;
1302 return c;
1303 }
1304
1305 return -1;
1306}
1307
1308CString UString::UTF8String() const
1309{
1310 // Allocate a buffer big enough to hold all the characters.
1311 const int length = size();
1312 const unsigned bufferSize = length * 3;
1313 char fixedSizeBuffer[1024];
1314 char *buffer;
1315 if (bufferSize > sizeof(fixedSizeBuffer)) {
1316 buffer = new char [bufferSize];
1317 } else {
1318 buffer = fixedSizeBuffer;
1319 }
1320
1321 // Convert to runs of 8-bit characters.
1322 char *p = buffer;
1323 const UChar *d = data();
1324 for (int i = 0; i != length; ++i) {
1325 unsigned short c = d[i].unicode();
1326 if (c < 0x80) {
1327 *p++ = (char)c;
1328 } else if (c < 0x800) {
1329 *p++ = (char)((c >> 6) | 0xC0); // C0 is the 2-byte flag for UTF-8
1330 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1331 } else if (c >= 0xD800 && c <= 0xDBFF && i < length && d[i+1].uc >= 0xDC00 && d[i+1].uc <= 0xDFFF) {
1332 unsigned sc = 0x10000 + (((c & 0x3FF) << 10) | (d[i+1].uc & 0x3FF));
1333 *p++ = (char)((sc >> 18) | 0xF0); // F0 is the 4-byte flag for UTF-8
1334 *p++ = (char)(((sc >> 12) | 0x80) & 0xBF); // next 6 bits, with high bit set
1335 *p++ = (char)(((sc >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1336 *p++ = (char)((sc | 0x80) & 0xBF); // next 6 bits, with high bit set
1337 ++i;
1338 } else {
1339 *p++ = (char)((c >> 12) | 0xE0); // E0 is the 3-byte flag for UTF-8
1340 *p++ = (char)(((c >> 6) | 0x80) & 0xBF); // next 6 bits, with high bit set
1341 *p++ = (char)((c | 0x80) & 0xBF); // next 6 bits, with high bit set
1342 }
1343 }
1344
1345 // Return the result as a C string.
1346 CString result(buffer, p - buffer);
1347 if (buffer != fixedSizeBuffer) {
1348 delete [] buffer;
1349 }
1350 return result;
1351}
1352
1353} // namespace KJS
Note: See TracBrowser for help on using the repository browser.