1 // -*- c-basic-offset: 2 -*-
3 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
4 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
23 #ifndef _KJS_USTRING_H_
24 #define _KJS_USTRING_H_
27 #include "collector.h"
29 #include <wtf/Assertions.h>
30 #include <wtf/FastMalloc.h>
31 #include <wtf/PassRefPtr.h>
32 #include <wtf/RefPtr.h>
33 #include <wtf/unicode/Unicode.h>
34 #include <wtf/Vector.h>
47 using WTF::PlacementNewAdoptType;
48 using WTF::PlacementNewAdopt;
50 class IdentifierTable;
54 * @short 8 bit char based string class
58 CString() : data(0), length(0) { }
59 CString(const char *c);
60 CString(const char *c, size_t len);
61 CString(const CString &);
65 static CString adopt(char* c, size_t len); // c should be allocated with new[].
67 CString &append(const CString &);
68 CString &operator=(const char *c);
69 CString &operator=(const CString &);
70 CString &operator+=(const CString &c) { return append(c); }
72 size_t size() const { return length; }
73 const char *c_str() const { return data; }
79 typedef Vector<char, 32> CStringBuffer;
82 * @short Unicode string class
85 friend bool operator==(const UString&, const UString&);
93 static PassRefPtr<Rep> create(UChar *d, int l);
94 static PassRefPtr<Rep> createCopying(const UChar *d, int l);
95 static PassRefPtr<Rep> create(PassRefPtr<Rep> base, int offset, int length);
97 // Constructs a string from a UTF-8 string, using strict conversion (see comments in UTF8.h).
98 // Returns UString::Rep::null for null input or conversion failure.
99 static PassRefPtr<Rep> createFromUTF8(const char*);
103 bool baseIsSelf() const { return baseString == this; }
104 UChar* data() const { return baseString->buf + baseString->preCapacity + offset; }
105 int size() const { return len; }
107 unsigned hash() const { if (_hash == 0) _hash = computeHash(data(), len); return _hash; }
108 unsigned computedHash() const { ASSERT(_hash); return _hash; } // fast path for Identifiers
110 static unsigned computeHash(const UChar *, int length);
111 static unsigned computeHash(const char *);
113 Rep* ref() { ++rc; return this; }
114 ALWAYS_INLINE void deref() { if (--rc == 0) destroy(); }
119 int rc; // For null and empty static strings, this field does not reflect a correct count, because ref/deref are not thread-safe. A special case in destroy() guarantees that these do not get deleted.
120 mutable unsigned _hash;
121 IdentifierTable* identifierTable; // 0 if not an identifier. Since garbage collection can happen on a different thread, there is no other way to get to the table during destruction.
122 UString::Rep* baseString;
124 size_t reportedCost : 31;
126 // potentially shared data
140 * Constructs a null string.
144 * Constructs a string from a classical zero-terminated char string.
146 UString(const char *c);
148 * Constructs a string from an array of Unicode characters of the specified
151 UString(const UChar *c, int length);
153 * If copy is false the string data will be adopted.
154 * That means that the data will NOT be copied and the pointer will
155 * be deleted when the UString object is modified or destroyed.
156 * Behaviour defaults to a deep copy if copy is true.
158 UString(UChar *c, int length, bool copy);
160 * Copy constructor. Makes a shallow copy only.
162 UString(const UString &s) : m_rep(s.m_rep) {}
164 UString(const Vector<UChar>& buffer);
167 * Convenience declaration only ! You'll be on your own to write the
168 * implementation for a construction from DOM::DOMString.
170 * Note: feel free to contact me if you want to see a dummy header for
171 * your favorite FooString class here !
173 UString(const DOM::DOMString&);
175 * Convenience declaration only ! See UString(const DOM::DOMString&).
177 UString(const DOM::AtomicString&);
180 * Concatenation constructor. Makes operator+ more efficient.
182 UString(const UString &, const UString &);
188 // Special constructor for cases where we overwrite an object in place.
189 UString(PlacementNewAdoptType) : m_rep(PlacementNewAdopt) { }
192 * Constructs a string from an int.
194 static UString from(int i);
196 * Constructs a string from an unsigned int.
198 static UString from(unsigned int u);
200 * Constructs a string from a long int.
202 static UString from(long u);
204 * Constructs a string from a double.
206 static UString from(double d);
210 Range(int pos, int len) : position(pos), length(len) {}
216 UString spliceSubstringsWithSeparators(const Range* substringRanges, int rangeCount, const UString* separators, int separatorCount) const;
219 * Append another string.
221 UString& append(const UString&);
222 UString& append(const char*);
223 UString& append(UChar);
224 UString& append(char c) { return append(static_cast<UChar>(static_cast<unsigned char>(c))); }
227 * @return The string converted to the 8-bit string type CString().
228 * Returns false if any character is non-ASCII.
230 bool getCString(CStringBuffer&) const;
233 * Convert the Unicode string to plain ASCII chars chopping off any higher
234 * bytes. This method should only be used for *debugging* purposes as it
235 * is neither Unicode safe nor free from side effects nor thread-safe.
236 * In order not to waste any memory the char buffer is static and *shared*
237 * by all UString instances.
242 * Convert the string to UTF-8, assuming it is UTF-16 encoded.
243 * In non-strict mode, this function is tolerant of badly formed UTF-16, it
244 * can create UTF-8 strings that are invalid because they have characters in
245 * the range U+D800-U+DDFF, U+FFFE, or U+FFFF, but the UTF-8 string is
246 * guaranteed to be otherwise valid.
247 * In strict mode, error is returned as null CString.
249 CString UTF8String(bool strict = false) const;
252 * @see UString(const DOM::DOMString&).
254 DOM::DOMString domString() const;
257 * Assignment operator.
259 UString &operator=(const char *c);
261 * Appends the specified string.
263 UString &operator+=(const UString &s) { return append(s); }
264 UString &operator+=(const char *s) { return append(s); }
267 * @return A pointer to the internal Unicode data.
269 const UChar* data() const { return m_rep->data(); }
271 * @return True if null.
273 bool isNull() const { return (m_rep == &Rep::null); }
275 * @return True if null or zero length.
277 bool isEmpty() const { return (!m_rep->len); }
279 * Use this if you want to make sure that this string is a plain ASCII
280 * string. For example, if you don't want to lose any information when
281 * using cstring() or ascii().
283 * @return True if the string doesn't contain any non-ASCII characters.
287 * @return The length of the string.
289 int size() const { return m_rep->size(); }
291 * Const character at specified position.
293 UChar operator[](int pos) const;
296 * Attempts an conversion to a number. Apart from floating point numbers,
297 * the algorithm will recognize hexadecimal representations (as
298 * indicated by a 0x or 0X prefix) and +/- Infinity.
299 * Returns NaN if the conversion failed.
300 * @param tolerateTrailingJunk if true, toDouble can tolerate garbage after the number.
301 * @param tolerateEmptyString if false, toDouble will turn an empty string into NaN rather than 0.
303 double toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const;
304 double toDouble(bool tolerateTrailingJunk) const;
305 double toDouble() const;
308 * Attempts an conversion to a 32-bit integer. ok will be set
309 * according to the success.
310 * @param tolerateEmptyString if false, toUInt32 will return false for *ok for an empty string.
312 uint32_t toUInt32(bool *ok = 0) const;
313 uint32_t toUInt32(bool *ok, bool tolerateEmptyString) const;
314 uint32_t toStrictUInt32(bool *ok = 0) const;
317 * Attempts an conversion to an array index. The "ok" boolean will be set
318 * to true if it is a valid array index according to the rule from
319 * ECMA 15.2 about what an array index is. It must exactly match the string
320 * form of an unsigned integer, and be less than 2^32 - 1.
322 unsigned toArrayIndex(bool *ok = 0) const;
325 * @return Position of first occurrence of f starting at position pos.
326 * -1 if the search was not successful.
328 int find(const UString &f, int pos = 0) const;
329 int find(UChar, int pos = 0) const;
331 * @return Position of first occurrence of f searching backwards from
333 * -1 if the search was not successful.
335 int rfind(const UString &f, int pos) const;
336 int rfind(UChar, int pos) const;
338 * @return The sub string starting at position pos and length len.
340 UString substr(int pos = 0, int len = -1) const;
342 * Static instance of a null string.
344 static const UString &null();
346 Rep* rep() const { return m_rep.get(); }
347 UString(PassRefPtr<Rep> r) : m_rep(r) { ASSERT(m_rep); }
352 size_t expandedSize(size_t size, size_t otherSize) const;
353 int usedCapacity() const;
354 int usedPreCapacity() const;
355 void expandCapacity(int requiredLength);
356 void expandPreCapacity(int requiredPreCap);
361 bool operator==(const UString& s1, const UString& s2);
362 inline bool operator!=(const UString& s1, const UString& s2) {
363 return !KJS::operator==(s1, s2);
365 bool operator<(const UString& s1, const UString& s2);
366 bool operator==(const UString& s1, const char *s2);
367 inline bool operator!=(const UString& s1, const char *s2) {
368 return !KJS::operator==(s1, s2);
370 inline bool operator==(const char *s1, const UString& s2) {
371 return operator==(s2, s1);
373 inline bool operator!=(const char *s1, const UString& s2) {
374 return !KJS::operator==(s1, s2);
376 bool operator==(const CString& s1, const CString& s2);
377 inline UString operator+(const UString& s1, const UString& s2) {
378 return UString(s1, s2);
381 int compare(const UString &, const UString &);
383 inline UString::UString()
388 // Rule from ECMA 15.2 about what an array index is.
389 // Must exactly match string form of an unsigned integer, and be less than 2^32 - 1.
390 inline unsigned UString::toArrayIndex(bool *ok) const
392 unsigned i = toStrictUInt32(ok);
393 if (ok && i >= 0xFFFFFFFFU)
398 // We'd rather not do shared substring append for small strings, since
399 // this runs too much risk of a tiny initial string holding down a
401 // FIXME: this should be size_t but that would cause warnings until we
402 // fix UString sizes to be size_t instead of int
403 static const int minShareSize = Collector::minExtraCostSize / sizeof(UChar);
405 inline size_t UString::cost() const
407 size_t capacity = (m_rep->baseString->capacity + m_rep->baseString->preCapacity) * sizeof(UChar);
408 size_t reportedCost = m_rep->baseString->reportedCost;
409 ASSERT(capacity >= reportedCost);
411 size_t capacityDelta = capacity - reportedCost;
413 if (capacityDelta < static_cast<size_t>(minShareSize))
417 // MSVC complains about this assignment, since reportedCost is a 31-bit size_t.
418 #pragma warning(push)
419 #pragma warning(disable: 4267)
422 m_rep->baseString->reportedCost = capacity;
428 return capacityDelta;