1 // -*- c-basic-offset: 2 -*-
3 * This file is part of the KDE libraries
4 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
5 * Copyright (C) 2004 Apple Computer, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
24 #ifndef _KJS_USTRING_H_
25 #define _KJS_USTRING_H_
28 #include "collector.h"
30 #include <wtf/Assertions.h>
31 #include <wtf/FastMalloc.h>
32 #include <wtf/PassRefPtr.h>
33 #include <wtf/RefPtr.h>
35 /* On ARM some versions of GCC don't pack structures by default so sizeof(UChar)
36 will end up being != 2 which causes crashes since the code depends on that. */
37 #if COMPILER(GCC) && PLATFORM(ARM)
38 #define PACK_STRUCT __attribute__((packed))
57 * @short Unicode character.
59 * UChar represents a 16 bit Unicode character. It's internal data
60 * representation is compatible to XChar2b and QChar. It's therefore
61 * possible to exchange data with X and Qt with shallow copies.
65 * Construct a character with uninitialized value.
69 * Construct a character with the value denoted by the arguments.
70 * @param h higher byte
73 UChar(unsigned char h , unsigned char l);
75 * Construct a character with the given value.
76 * @param u 16 bit Unicode value
79 UChar(unsigned char u);
80 UChar(unsigned short u);
82 * @return The higher byte of the character.
84 unsigned char high() const { return static_cast<unsigned char>(uc >> 8); }
86 * @return The lower byte of the character.
88 unsigned char low() const { return static_cast<unsigned char>(uc); }
90 * @return the 16 bit Unicode value of the character
92 unsigned short unicode() const { return uc; }
97 inline UChar::UChar() { }
98 inline UChar::UChar(unsigned char h , unsigned char l) : uc(h << 8 | l) { }
99 inline UChar::UChar(char u) : uc((unsigned char)u) { }
100 inline UChar::UChar(unsigned char u) : uc(u) { }
101 inline UChar::UChar(unsigned short u) : uc(u) { }
104 * @short 8 bit char based string class
108 CString() : data(0), length(0) { }
109 CString(const char *c);
110 CString(const char *c, size_t len);
111 CString(const CString &);
115 CString &append(const CString &);
116 CString &operator=(const char *c);
117 CString &operator=(const CString &);
118 CString &operator+=(const CString &c) { return append(c); }
120 size_t size() const { return length; }
121 const char *c_str() const { return data; }
128 * @short Unicode string class
131 friend bool operator==(const UString&, const UString&);
139 static PassRefPtr<Rep> create(UChar *d, int l);
140 static PassRefPtr<Rep> createCopying(const UChar *d, int l);
141 static PassRefPtr<Rep> create(PassRefPtr<Rep> base, int offset, int length);
145 bool baseIsSelf() const { return baseString == this; }
146 UChar* data() const { return baseString->buf + baseString->preCapacity + offset; }
147 int size() const { return len; }
149 unsigned hash() const { if (_hash == 0) _hash = computeHash(data(), len); return _hash; }
150 static unsigned computeHash(const UChar *, int length);
151 static unsigned computeHash(const char *);
153 Rep* ref() { ASSERT(JSLock::lockCount() > 0); ++rc; return this; }
154 void deref() { ASSERT(JSLock::lockCount() > 0); if (--rc == 0) destroy(); }
160 mutable unsigned _hash;
162 UString::Rep* baseString;
164 // potentially shared data
178 * Constructs a null string.
182 * Constructs a string from a classical zero-terminated char string.
184 UString(const char *c);
186 * Constructs a string from an array of Unicode characters of the specified
189 UString(const UChar *c, int length);
191 * If copy is false the string data will be adopted.
192 * That means that the data will NOT be copied and the pointer will
193 * be deleted when the UString object is modified or destroyed.
194 * Behaviour defaults to a deep copy if copy is true.
196 UString(UChar *c, int length, bool copy);
198 * Copy constructor. Makes a shallow copy only.
200 UString(const UString &s) : m_rep(s.m_rep) {}
202 * Convenience declaration only ! You'll be on your own to write the
203 * implementation for a construction from DOM::DOMString.
205 * Note: feel free to contact me if you want to see a dummy header for
206 * your favorite FooString class here !
208 UString(const DOM::DOMString&);
210 * Convenience declaration only ! See UString(const DOM::DOMString&).
212 UString(const DOM::AtomicString&);
215 * Concatenation constructor. Makes operator+ more efficient.
217 UString(const UString &, const UString &);
224 * Constructs a string from an int.
226 static UString from(int i);
228 * Constructs a string from an unsigned int.
230 static UString from(unsigned int u);
232 * Constructs a string from a long int.
234 static UString from(long u);
236 * Constructs a string from a double.
238 static UString from(double d);
242 Range(int pos, int len) : position(pos), length(len) {}
248 UString spliceSubstringsWithSeparators(const Range *substringRanges, int rangeCount, const UString *separators, int separatorCount) const;
251 * Append another string.
253 UString &append(const UString &);
254 UString &append(const char *);
255 UString &append(unsigned short);
256 UString &append(char c) { return append(static_cast<unsigned short>(static_cast<unsigned char>(c))); }
257 UString &append(UChar c) { return append(c.uc); }
260 * @return The string converted to the 8-bit string type CString().
262 CString cstring() const;
264 * Convert the Unicode string to plain ASCII chars chopping of any higher
265 * bytes. This method should only be used for *debugging* purposes as it
266 * is neither Unicode safe nor free from side effects. In order not to
267 * waste any memory the char buffer is static and *shared* by all UString
273 * Convert the string to UTF-8, assuming it is UTF-16 encoded.
274 * Since this function is tolerant of badly formed UTF-16, it can create UTF-8
275 * strings that are invalid because they have characters in the range
276 * U+D800-U+DDFF, U+FFFE, or U+FFFF, but the UTF-8 string is guaranteed to
277 * be otherwise valid.
279 CString UTF8String() const;
282 * @see UString(const DOM::DOMString&).
284 DOM::DOMString domString() const;
287 * Assignment operator.
289 UString &operator=(const char *c);
291 * Appends the specified string.
293 UString &operator+=(const UString &s) { return append(s); }
294 UString &operator+=(const char *s) { return append(s); }
297 * @return A pointer to the internal Unicode data.
299 const UChar* data() const { return m_rep->data(); }
301 * @return True if null.
303 bool isNull() const { return (m_rep == &Rep::null); }
305 * @return True if null or zero length.
307 bool isEmpty() const { return (!m_rep->len); }
309 * Use this if you want to make sure that this string is a plain ASCII
310 * string. For example, if you don't want to lose any information when
311 * using cstring() or ascii().
313 * @return True if the string doesn't contain any non-ASCII characters.
317 * @return The length of the string.
319 int size() const { return m_rep->size(); }
321 * Const character at specified position.
323 const UChar operator[](int pos) const;
326 * Attempts an conversion to a number. Apart from floating point numbers,
327 * the algorithm will recognize hexadecimal representations (as
328 * indicated by a 0x or 0X prefix) and +/- Infinity.
329 * Returns NaN if the conversion failed.
330 * @param tolerateTrailingJunk if true, toDouble can tolerate garbage after the number.
331 * @param tolerateEmptyString if false, toDouble will turn an empty string into NaN rather than 0.
333 double toDouble(bool tolerateTrailingJunk, bool tolerateEmptyString) const;
334 double toDouble(bool tolerateTrailingJunk) const;
335 double toDouble() const;
338 * Attempts an conversion to a 32-bit integer. ok will be set
339 * according to the success.
340 * @param tolerateEmptyString if false, toUInt32 will return false for *ok for an empty string.
342 uint32_t toUInt32(bool *ok = 0) const;
343 uint32_t toUInt32(bool *ok, bool tolerateEmptyString) const;
344 uint32_t toStrictUInt32(bool *ok = 0) const;
347 * Attempts an conversion to an array index. The "ok" boolean will be set
348 * to true if it is a valid array index according to the rule from
349 * ECMA 15.2 about what an array index is. It must exactly match the string
350 * form of an unsigned integer, and be less than 2^32 - 1.
352 unsigned toArrayIndex(bool *ok = 0) const;
355 * @return Position of first occurrence of f starting at position pos.
356 * -1 if the search was not successful.
358 int find(const UString &f, int pos = 0) const;
359 int find(UChar, int pos = 0) const;
361 * @return Position of first occurrence of f searching backwards from
363 * -1 if the search was not successful.
365 int rfind(const UString &f, int pos) const;
366 int rfind(UChar, int pos) const;
368 * @return The sub string starting at position pos and length len.
370 UString substr(int pos = 0, int len = -1) const;
372 * Static instance of a null string.
374 static const UString &null();
377 * Clear statically allocated resources.
379 static void globalClear();
382 Rep* rep() const { return m_rep.get(); }
383 UString(PassRefPtr<Rep> r) : m_rep(r) { ASSERT(m_rep); }
388 size_t expandedSize(size_t size, size_t otherSize) const;
389 int usedCapacity() const;
390 int usedPreCapacity() const;
391 void expandCapacity(int requiredLength);
392 void expandPreCapacity(int requiredPreCap);
397 inline bool operator==(const UChar &c1, const UChar &c2) {
398 return (c1.uc == c2.uc);
400 bool operator==(const UString& s1, const UString& s2);
401 inline bool operator!=(const UString& s1, const UString& s2) {
402 return !KJS::operator==(s1, s2);
404 bool operator<(const UString& s1, const UString& s2);
405 bool operator==(const UString& s1, const char *s2);
406 inline bool operator!=(const UString& s1, const char *s2) {
407 return !KJS::operator==(s1, s2);
409 inline bool operator==(const char *s1, const UString& s2) {
410 return operator==(s2, s1);
412 inline bool operator!=(const char *s1, const UString& s2) {
413 return !KJS::operator==(s1, s2);
415 bool operator==(const CString& s1, const CString& s2);
416 inline UString operator+(const UString& s1, const UString& s2) {
417 return UString(s1, s2);
420 int compare(const UString &, const UString &);
422 // Given a first byte, gives the length of the UTF-8 sequence it begins.
423 // Returns 0 for bytes that are not legal starts of UTF-8 sequences.
424 // Only allows sequences of up to 4 bytes, since that works for all Unicode characters (U-00000000 to U-0010FFFF).
425 int UTF8SequenceLength(char);
427 // Takes a null-terminated C-style string with a UTF-8 sequence in it and converts it to a character.
428 // Only allows Unicode characters (U-00000000 to U-0010FFFF).
429 // Returns -1 if the sequence is not valid (including presence of extra bytes).
430 int decodeUTF8Sequence(const char *);
432 inline UString::UString()
437 // Rule from ECMA 15.2 about what an array index is.
438 // Must exactly match string form of an unsigned integer, and be less than 2^32 - 1.
439 inline unsigned UString::toArrayIndex(bool *ok) const
441 unsigned i = toStrictUInt32(ok);
442 if (ok && i >= 0xFFFFFFFFU)
447 inline size_t UString::cost() const
449 // If this string is sharing with a base, then don't count any cost. We will never share
450 // with a base that wasn't already big enough to register extra cost, so a string holding that
451 // buffer has already paid extra cost at some point; and if we just
452 // enlarged it by a huge amount, it must have been by appending a string
453 // that itself paid extra cost, or a huge number of small strings. Either way, GC will come
456 // If we didn't do this, the shared substring optimization would result
457 // in constantly garbage collecting when sharing with one big string.
459 if (!m_rep->baseIsSelf())
462 return (m_rep->capacity + m_rep->preCapacity) * sizeof(UChar);