2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2013 Apple Inc. All rights reserved.
4 * Copyright (C) 2009 Google 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.
27 #include <wtf/ASCIICType.h>
28 #include <wtf/Forward.h>
29 #include <wtf/StdLibExtras.h>
30 #include <wtf/StringHasher.h>
31 #include <wtf/Vector.h>
32 #include <wtf/unicode/Unicode.h>
39 typedef const struct __CFString * CFStringRef;
46 #if PLATFORM(BLACKBERRY)
47 #include <BlackBerryPlatformString.h>
50 // FIXME: This is a temporary layering violation while we move string code to WTF.
51 // Landing the file moves in one patch, will follow on with patches to change the namespaces.
53 struct IdentifierASCIIStringTranslator;
54 namespace LLInt { class Data; }
55 class LLIntOffsetsExtractor;
56 template <typename T> struct IdentifierCharBufferTranslator;
57 struct IdentifierLCharFromUCharTranslator;
62 struct CStringTranslator;
63 template<typename CharacterType> struct HashAndCharactersTranslator;
64 struct HashAndUTF8CharactersTranslator;
65 struct LCharBufferTranslator;
66 struct CharBufferFromLiteralDataTranslator;
67 struct SubstringTranslator;
68 struct UCharBufferTranslator;
69 template<typename> class RetainPtr;
71 enum TextCaseSensitivity { TextCaseSensitive, TextCaseInsensitive };
73 typedef bool (*CharacterMatchFunctionPtr)(UChar);
74 typedef bool (*IsWhiteSpaceFunctionPtr)(UChar);
76 // Define STRING_STATS to turn on run time statistics of string sizes and memory usage
81 inline void add8BitString(unsigned length, bool isSubString = false)
83 ++m_totalNumberStrings;
84 ++m_number8BitStrings;
86 m_total8BitData += length;
89 inline void add16BitString(unsigned length, bool isSubString = false)
91 ++m_totalNumberStrings;
92 ++m_number16BitStrings;
94 m_total16BitData += length;
97 inline void addUpconvertedString(unsigned length)
99 ++m_numberUpconvertedStrings;
100 m_totalUpconvertedData += length;
103 void removeString(StringImpl*);
106 static const unsigned s_printStringStatsFrequency = 5000;
107 static unsigned s_stringRemovesTillPrintStats;
109 unsigned m_totalNumberStrings;
110 unsigned m_number8BitStrings;
111 unsigned m_number16BitStrings;
112 unsigned m_numberUpconvertedStrings;
113 unsigned long long m_total8BitData;
114 unsigned long long m_total16BitData;
115 unsigned long long m_totalUpconvertedData;
118 #define STRING_STATS_ADD_8BIT_STRING(length) StringImpl::stringStats().add8BitString(length)
119 #define STRING_STATS_ADD_8BIT_STRING2(length, isSubString) StringImpl::stringStats().add8BitString(length, isSubString)
120 #define STRING_STATS_ADD_16BIT_STRING(length) StringImpl::stringStats().add16BitString(length)
121 #define STRING_STATS_ADD_16BIT_STRING2(length, isSubString) StringImpl::stringStats().add16BitString(length, isSubString)
122 #define STRING_STATS_ADD_UPCONVERTED_STRING(length) StringImpl::stringStats().addUpconvertedString(length)
123 #define STRING_STATS_REMOVE_STRING(string) StringImpl::stringStats().removeString(string)
125 #define STRING_STATS_ADD_8BIT_STRING(length) ((void)0)
126 #define STRING_STATS_ADD_8BIT_STRING2(length, isSubString) ((void)0)
127 #define STRING_STATS_ADD_16BIT_STRING(length) ((void)0)
128 #define STRING_STATS_ADD_16BIT_STRING2(length, isSubString) ((void)0)
129 #define STRING_STATS_ADD_UPCONVERTED_STRING(length) ((void)0)
130 #define STRING_STATS_REMOVE_STRING(string) ((void)0)
134 WTF_MAKE_NONCOPYABLE(StringImpl); WTF_MAKE_FAST_ALLOCATED;
135 friend struct JSC::IdentifierASCIIStringTranslator;
136 friend struct JSC::IdentifierCharBufferTranslator<LChar>;
137 friend struct JSC::IdentifierCharBufferTranslator<UChar>;
138 friend struct JSC::IdentifierLCharFromUCharTranslator;
139 friend struct WTF::CStringTranslator;
140 template<typename CharacterType> friend struct WTF::HashAndCharactersTranslator;
141 friend struct WTF::HashAndUTF8CharactersTranslator;
142 friend struct WTF::CharBufferFromLiteralDataTranslator;
143 friend struct WTF::LCharBufferTranslator;
144 friend struct WTF::SubstringTranslator;
145 friend struct WTF::UCharBufferTranslator;
146 friend class AtomicStringImpl;
147 friend class JSC::LLInt::Data;
148 friend class JSC::LLIntOffsetsExtractor;
151 enum BufferOwnership {
158 // NOTE: Adding more ownership types needs to extend m_hashAndFlags as we're at capacity
161 // Used to construct static strings, which have an special refCount that can never hit zero.
162 // This means that the static string will never be destroyed, which is important because
163 // static strings will be shared across threads & ref-counted in a non-threadsafe manner.
164 enum ConstructStaticStringTag { ConstructStaticString };
165 StringImpl(const UChar* characters, unsigned length, ConstructStaticStringTag)
166 : m_refCount(s_refCountFlagIsStaticString)
168 , m_data16(characters)
170 , m_hashAndFlags(s_hashFlagIsIdentifier | BufferOwned)
172 // Ensure that the hash is computed so that AtomicStringHash can call existingHash()
173 // with impunity. The empty string is special because it is never entered into
174 // AtomicString's HashKey, but still needs to compare correctly.
175 STRING_STATS_ADD_16BIT_STRING(m_length);
180 // Used to construct static strings, which have an special refCount that can never hit zero.
181 // This means that the static string will never be destroyed, which is important because
182 // static strings will be shared across threads & ref-counted in a non-threadsafe manner.
183 StringImpl(const LChar* characters, unsigned length, ConstructStaticStringTag)
184 : m_refCount(s_refCountFlagIsStaticString)
186 , m_data8(characters)
188 , m_hashAndFlags(s_hashFlag8BitBuffer | s_hashFlagIsIdentifier | BufferOwned)
190 // Ensure that the hash is computed so that AtomicStringHash can call existingHash()
191 // with impunity. The empty string is special because it is never entered into
192 // AtomicString's HashKey, but still needs to compare correctly.
193 STRING_STATS_ADD_8BIT_STRING(m_length);
198 // FIXME: there has to be a less hacky way to do this.
199 enum Force8Bit { Force8BitConstructor };
200 // Create a normal 8-bit string with internal storage (BufferInternal)
201 StringImpl(unsigned length, Force8Bit)
202 : m_refCount(s_refCountIncrement)
204 , m_data8(reinterpret_cast<const LChar*>(this + 1))
206 , m_hashAndFlags(s_hashFlag8BitBuffer | BufferInternal)
211 STRING_STATS_ADD_8BIT_STRING(m_length);
214 // Create a normal 16-bit string with internal storage (BufferInternal)
215 StringImpl(unsigned length)
216 : m_refCount(s_refCountIncrement)
218 , m_data16(reinterpret_cast<const UChar*>(this + 1))
220 , m_hashAndFlags(BufferInternal)
225 STRING_STATS_ADD_16BIT_STRING(m_length);
228 // Create a StringImpl adopting ownership of the provided buffer (BufferOwned)
229 StringImpl(const LChar* characters, unsigned length)
230 : m_refCount(s_refCountIncrement)
232 , m_data8(characters)
234 , m_hashAndFlags(s_hashFlag8BitBuffer | BufferOwned)
239 STRING_STATS_ADD_8BIT_STRING(m_length);
242 enum ConstructFromLiteralTag { ConstructFromLiteral };
243 StringImpl(const char* characters, unsigned length, ConstructFromLiteralTag)
244 : m_refCount(s_refCountIncrement)
246 , m_data8(reinterpret_cast<const LChar*>(characters))
248 , m_hashAndFlags(s_hashFlag8BitBuffer | BufferInternal | s_hashFlagHasTerminatingNullCharacter)
252 ASSERT(!characters[length]);
254 STRING_STATS_ADD_8BIT_STRING(0);
257 // Create a StringImpl adopting ownership of the provided buffer (BufferOwned)
258 StringImpl(const UChar* characters, unsigned length)
259 : m_refCount(s_refCountIncrement)
261 , m_data16(characters)
263 , m_hashAndFlags(BufferOwned)
268 STRING_STATS_ADD_16BIT_STRING(m_length);
271 // Used to create new strings that are a substring of an existing 8-bit StringImpl (BufferSubstring)
272 StringImpl(const LChar* characters, unsigned length, PassRefPtr<StringImpl> base)
273 : m_refCount(s_refCountIncrement)
275 , m_data8(characters)
276 , m_substringBuffer(base.leakRef())
277 , m_hashAndFlags(s_hashFlag8BitBuffer | BufferSubstring)
282 ASSERT(m_substringBuffer->bufferOwnership() != BufferSubstring);
284 STRING_STATS_ADD_8BIT_STRING2(m_length, true);
287 // Used to create new strings that are a substring of an existing 16-bit StringImpl (BufferSubstring)
288 StringImpl(const UChar* characters, unsigned length, PassRefPtr<StringImpl> base)
289 : m_refCount(s_refCountIncrement)
291 , m_data16(characters)
292 , m_substringBuffer(base.leakRef())
293 , m_hashAndFlags(BufferSubstring)
298 ASSERT(m_substringBuffer->bufferOwnership() != BufferSubstring);
300 STRING_STATS_ADD_16BIT_STRING2(m_length, true);
303 enum CreateEmptyUnique_T { CreateEmptyUnique };
304 StringImpl(CreateEmptyUnique_T)
305 : m_refCount(s_refCountIncrement)
307 , m_data16(reinterpret_cast<const UChar*>(1))
311 // Set the hash early, so that all empty unique StringImpls have a hash,
312 // and don't use the normal hashing algorithm - the unique nature of these
313 // keys means that we don't need them to match any other string (in fact,
314 // that's exactly the oposite of what we want!), and teh normal hash would
315 // lead to lots of conflicts.
316 unsigned hash = reinterpret_cast<uintptr_t>(this);
317 hash <<= s_flagCount;
319 hash = 1 << s_flagCount;
320 m_hashAndFlags = hash | BufferInternal;
322 STRING_STATS_ADD_16BIT_STRING(m_length);
326 // Used to create new strings that adopt an existing QString's data
327 enum ConstructAdoptedQStringTag { ConstructAdoptedQString };
328 StringImpl(QStringData* qStringData, ConstructAdoptedQStringTag)
329 : m_refCount(s_refCountIncrement)
330 , m_length(qStringData->size)
332 , m_qStringData(qStringData)
333 , m_hashAndFlags(BufferAdoptedQString)
337 // We ref the string-data to ensure it will be valid for the lifetime of
338 // this string. We then deref it in the destructor, so that the string
339 // data can eventually be freed.
340 m_qStringData->ref.ref();
342 // Now that we have a ref we can safely reference the string data
343 m_data16 = reinterpret_cast_ptr<const UChar*>(qStringData->data());
346 STRING_STATS_ADD_16BIT_STRING(m_length);
352 WTF_EXPORT_STRING_API static void destroy(StringImpl*);
354 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> create(const UChar*, unsigned length);
355 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> create(const LChar*, unsigned length);
356 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> create8BitIfPossible(const UChar*, unsigned length);
357 template<size_t inlineCapacity>
358 static PassRefPtr<StringImpl> create8BitIfPossible(const Vector<UChar, inlineCapacity>& vector)
360 return create8BitIfPossible(vector.data(), vector.size());
363 ALWAYS_INLINE static PassRefPtr<StringImpl> create(const char* s, unsigned length) { return create(reinterpret_cast<const LChar*>(s), length); }
364 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> create(const LChar*);
365 ALWAYS_INLINE static PassRefPtr<StringImpl> create(const char* s) { return create(reinterpret_cast<const LChar*>(s)); }
367 static ALWAYS_INLINE PassRefPtr<StringImpl> create8(PassRefPtr<StringImpl> rep, unsigned offset, unsigned length)
370 ASSERT(length <= rep->length());
375 ASSERT(rep->is8Bit());
376 StringImpl* ownerRep = (rep->bufferOwnership() == BufferSubstring) ? rep->m_substringBuffer : rep.get();
377 return adoptRef(new StringImpl(rep->m_data8 + offset, length, ownerRep));
380 static ALWAYS_INLINE PassRefPtr<StringImpl> create(PassRefPtr<StringImpl> rep, unsigned offset, unsigned length)
383 ASSERT(length <= rep->length());
388 StringImpl* ownerRep = (rep->bufferOwnership() == BufferSubstring) ? rep->m_substringBuffer : rep.get();
390 return adoptRef(new StringImpl(rep->m_data8 + offset, length, ownerRep));
391 return adoptRef(new StringImpl(rep->m_data16 + offset, length, ownerRep));
394 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> createFromLiteral(const char* characters, unsigned length);
395 template<unsigned charactersCount>
396 ALWAYS_INLINE static PassRefPtr<StringImpl> createFromLiteral(const char (&characters)[charactersCount])
398 COMPILE_ASSERT(charactersCount > 1, StringImplFromLiteralNotEmpty);
399 COMPILE_ASSERT((charactersCount - 1 <= ((unsigned(~0) - sizeof(StringImpl)) / sizeof(LChar))), StringImplFromLiteralCannotOverflow);
401 return createFromLiteral(characters, charactersCount - 1);
403 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> createFromLiteral(const char* characters);
405 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> createUninitialized(unsigned length, LChar*& data);
406 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> createUninitialized(unsigned length, UChar*& data);
407 template <typename T> static ALWAYS_INLINE PassRefPtr<StringImpl> tryCreateUninitialized(unsigned length, T*& output)
414 if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(T))) {
418 StringImpl* resultImpl;
419 if (!tryFastMalloc(sizeof(T) * length + sizeof(StringImpl)).getValue(resultImpl)) {
423 output = reinterpret_cast<T*>(resultImpl + 1);
425 if (sizeof(T) == sizeof(char))
426 return adoptRef(new (NotNull, resultImpl) StringImpl(length, Force8BitConstructor));
428 return adoptRef(new (NotNull, resultImpl) StringImpl(length));
431 static PassRefPtr<StringImpl> createEmptyUnique()
433 return adoptRef(new StringImpl(CreateEmptyUnique));
436 // Reallocate the StringImpl. The originalString must be only owned by the PassRefPtr,
437 // and the buffer ownership must be BufferInternal. Just like the input pointer of realloc(),
438 // the originalString can't be used after this function.
439 static PassRefPtr<StringImpl> reallocate(PassRefPtr<StringImpl> originalString, unsigned length, LChar*& data);
440 static PassRefPtr<StringImpl> reallocate(PassRefPtr<StringImpl> originalString, unsigned length, UChar*& data);
442 static unsigned flagsOffset() { return OBJECT_OFFSETOF(StringImpl, m_hashAndFlags); }
443 static unsigned flagIs8Bit() { return s_hashFlag8BitBuffer; }
444 static unsigned dataOffset() { return OBJECT_OFFSETOF(StringImpl, m_data8); }
445 static PassRefPtr<StringImpl> createWithTerminatingNullCharacter(const StringImpl&);
447 template<typename CharType, size_t inlineCapacity, typename OverflowHandler>
448 static PassRefPtr<StringImpl> adopt(Vector<CharType, inlineCapacity, OverflowHandler>& vector)
450 if (size_t size = vector.size()) {
451 ASSERT(vector.data());
452 if (size > std::numeric_limits<unsigned>::max())
454 return adoptRef(new StringImpl(vector.releaseBuffer(), size));
459 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> adopt(StringBuffer<UChar>&);
460 WTF_EXPORT_STRING_API static PassRefPtr<StringImpl> adopt(StringBuffer<LChar>&);
463 static PassRefPtr<StringImpl> adopt(QStringData*);
466 unsigned length() const { return m_length; }
467 bool is8Bit() const { return m_hashAndFlags & s_hashFlag8BitBuffer; }
468 bool hasInternalBuffer() const { return bufferOwnership() == BufferInternal; }
469 bool hasOwnedBuffer() const { return bufferOwnership() == BufferOwned; }
470 StringImpl* baseString() const { return bufferOwnership() == BufferSubstring ? m_substringBuffer : 0; }
472 // FIXME: Remove all unnecessary usages of characters()
473 ALWAYS_INLINE const LChar* characters8() const { ASSERT(is8Bit()); return m_data8; }
474 ALWAYS_INLINE const UChar* characters16() const { ASSERT(!is8Bit()); return m_data16; }
475 ALWAYS_INLINE const UChar* characters() const
480 return getData16SlowCase();
483 template <typename CharType>
484 ALWAYS_INLINE const CharType * getCharacters() const;
488 // For substrings, return the cost of the base string.
489 if (bufferOwnership() == BufferSubstring)
490 return m_substringBuffer->cost();
492 if (m_hashAndFlags & s_hashFlagDidReportCost)
495 m_hashAndFlags |= s_hashFlagDidReportCost;
499 WTF_EXPORT_STRING_API size_t sizeInBytes() const;
501 bool has16BitShadow() const { return m_hashAndFlags & s_hashFlagHas16BitShadow; }
502 WTF_EXPORT_STRING_API void upconvertCharacters(unsigned, unsigned) const;
503 bool isIdentifier() const { return m_hashAndFlags & s_hashFlagIsIdentifier; }
504 void setIsIdentifier(bool isIdentifier)
508 m_hashAndFlags |= s_hashFlagIsIdentifier;
510 m_hashAndFlags &= ~s_hashFlagIsIdentifier;
513 bool isEmptyUnique() const
515 return !length() && !isStatic();
518 bool hasTerminatingNullCharacter() const { return m_hashAndFlags & s_hashFlagHasTerminatingNullCharacter; }
520 bool isAtomic() const { return m_hashAndFlags & s_hashFlagIsAtomic; }
521 void setIsAtomic(bool isAtomic)
525 m_hashAndFlags |= s_hashFlagIsAtomic;
527 m_hashAndFlags &= ~s_hashFlagIsAtomic;
531 bool isSubString() const { return bufferOwnership() == BufferSubstring; }
535 QStringData* qStringData() { return bufferOwnership() == BufferAdoptedQString ? m_qStringData : 0; }
539 // The high bits of 'hash' are always empty, but we prefer to store our flags
540 // in the low bits because it makes them slightly more efficient to access.
541 // So, we shift left and right when setting and getting our hash code.
542 void setHash(unsigned hash) const
545 // Multiple clients assume that StringHasher is the canonical string hash function.
546 ASSERT(hash == (is8Bit() ? StringHasher::computeHashAndMaskTop8Bits(m_data8, m_length) : StringHasher::computeHashAndMaskTop8Bits(m_data16, m_length)));
547 ASSERT(!(hash & (s_flagMask << (8 * sizeof(hash) - s_flagCount)))); // Verify that enough high bits are empty.
549 hash <<= s_flagCount;
550 ASSERT(!(hash & m_hashAndFlags)); // Verify that enough low bits are empty after shift.
551 ASSERT(hash); // Verify that 0 is a valid sentinel hash value.
553 m_hashAndFlags |= hash; // Store hash with flags in low bits.
556 unsigned rawHash() const
558 return m_hashAndFlags >> s_flagCount;
564 return rawHash() != 0;
567 unsigned existingHash() const
573 unsigned hash() const
576 return existingHash();
577 return hashSlowCase();
580 inline bool hasOneRef() const
582 return m_refCount == s_refCountIncrement;
587 m_refCount += s_refCountIncrement;
592 unsigned tempRefCount = m_refCount - s_refCountIncrement;
594 StringImpl::destroy(this);
597 m_refCount = tempRefCount;
600 WTF_EXPORT_PRIVATE static StringImpl* empty();
602 // FIXME: Does this really belong in StringImpl?
603 template <typename T> static void copyChars(T* destination, const T* source, unsigned numCharacters)
605 if (numCharacters == 1) {
606 *destination = *source;
610 if (numCharacters <= s_copyCharsInlineCutOff) {
612 #if (CPU(X86) || CPU(X86_64))
613 const unsigned charsPerInt = sizeof(uint32_t) / sizeof(T);
615 if (numCharacters > charsPerInt) {
616 unsigned stopCount = numCharacters & ~(charsPerInt - 1);
618 const uint32_t* srcCharacters = reinterpret_cast<const uint32_t*>(source);
619 uint32_t* destCharacters = reinterpret_cast<uint32_t*>(destination);
620 for (unsigned j = 0; i < stopCount; i += charsPerInt, ++j)
621 destCharacters[j] = srcCharacters[j];
624 for (; i < numCharacters; ++i)
625 destination[i] = source[i];
627 memcpy(destination, source, numCharacters * sizeof(T));
630 ALWAYS_INLINE static void copyChars(UChar* destination, const LChar* source, unsigned numCharacters)
632 for (unsigned i = 0; i < numCharacters; ++i)
633 destination[i] = source[i];
636 // Some string features, like refcounting and the atomicity flag, are not
637 // thread-safe. We achieve thread safety by isolation, giving each thread
638 // its own copy of the string.
639 PassRefPtr<StringImpl> isolatedCopy() const;
641 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> substring(unsigned pos, unsigned len = UINT_MAX);
643 UChar operator[](unsigned i) const
645 ASSERT_WITH_SECURITY_IMPLICATION(i < m_length);
650 WTF_EXPORT_STRING_API UChar32 characterStartingAt(unsigned);
652 WTF_EXPORT_STRING_API bool containsOnlyWhitespace();
654 int toIntStrict(bool* ok = 0, int base = 10);
655 unsigned toUIntStrict(bool* ok = 0, int base = 10);
656 int64_t toInt64Strict(bool* ok = 0, int base = 10);
657 uint64_t toUInt64Strict(bool* ok = 0, int base = 10);
658 intptr_t toIntPtrStrict(bool* ok = 0, int base = 10);
660 WTF_EXPORT_STRING_API int toInt(bool* ok = 0); // ignores trailing garbage
661 unsigned toUInt(bool* ok = 0); // ignores trailing garbage
662 int64_t toInt64(bool* ok = 0); // ignores trailing garbage
663 uint64_t toUInt64(bool* ok = 0); // ignores trailing garbage
664 intptr_t toIntPtr(bool* ok = 0); // ignores trailing garbage
666 // FIXME: Like the strict functions above, these give false for "ok" when there is trailing garbage.
667 // Like the non-strict functions above, these return the value when there is trailing garbage.
668 // It would be better if these were more consistent with the above functions instead.
669 double toDouble(bool* ok = 0);
670 float toFloat(bool* ok = 0);
672 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> lower();
673 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> upper();
675 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> fill(UChar);
676 // FIXME: Do we need fill(char) or can we just do the right thing if UChar is ASCII?
677 PassRefPtr<StringImpl> foldCase();
679 PassRefPtr<StringImpl> stripWhiteSpace();
680 PassRefPtr<StringImpl> stripWhiteSpace(IsWhiteSpaceFunctionPtr);
681 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> simplifyWhiteSpace();
682 PassRefPtr<StringImpl> simplifyWhiteSpace(IsWhiteSpaceFunctionPtr);
684 PassRefPtr<StringImpl> removeCharacters(CharacterMatchFunctionPtr);
685 template <typename CharType>
686 ALWAYS_INLINE PassRefPtr<StringImpl> removeCharacters(const CharType* characters, CharacterMatchFunctionPtr);
688 size_t find(LChar character, unsigned start = 0);
689 size_t find(char character, unsigned start = 0);
690 size_t find(UChar character, unsigned start = 0);
691 WTF_EXPORT_STRING_API size_t find(CharacterMatchFunctionPtr, unsigned index = 0);
692 size_t find(const LChar*, unsigned index = 0);
693 ALWAYS_INLINE size_t find(const char* s, unsigned index = 0) { return find(reinterpret_cast<const LChar*>(s), index); }
694 WTF_EXPORT_STRING_API size_t find(StringImpl*);
695 WTF_EXPORT_STRING_API size_t find(StringImpl*, unsigned index);
696 size_t findIgnoringCase(const LChar*, unsigned index = 0);
697 ALWAYS_INLINE size_t findIgnoringCase(const char* s, unsigned index = 0) { return findIgnoringCase(reinterpret_cast<const LChar*>(s), index); }
698 WTF_EXPORT_STRING_API size_t findIgnoringCase(StringImpl*, unsigned index = 0);
700 WTF_EXPORT_STRING_API size_t findNextLineStart(unsigned index = UINT_MAX);
702 WTF_EXPORT_STRING_API size_t reverseFind(UChar, unsigned index = UINT_MAX);
703 WTF_EXPORT_STRING_API size_t reverseFind(StringImpl*, unsigned index = UINT_MAX);
704 WTF_EXPORT_STRING_API size_t reverseFindIgnoringCase(StringImpl*, unsigned index = UINT_MAX);
706 bool startsWith(StringImpl* str, bool caseSensitive = true) { return (caseSensitive ? reverseFind(str, 0) : reverseFindIgnoringCase(str, 0)) == 0; }
707 WTF_EXPORT_STRING_API bool startsWith(UChar) const;
708 WTF_EXPORT_STRING_API bool startsWith(const char*, unsigned matchLength, bool caseSensitive) const;
709 template<unsigned matchLength>
710 bool startsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return startsWith(prefix, matchLength - 1, caseSensitive); }
712 WTF_EXPORT_STRING_API bool endsWith(StringImpl*, bool caseSensitive = true);
713 WTF_EXPORT_STRING_API bool endsWith(UChar) const;
714 WTF_EXPORT_STRING_API bool endsWith(const char*, unsigned matchLength, bool caseSensitive) const;
715 template<unsigned matchLength>
716 bool endsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return endsWith(prefix, matchLength - 1, caseSensitive); }
718 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> replace(UChar, UChar);
719 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> replace(UChar, StringImpl*);
720 ALWAYS_INLINE PassRefPtr<StringImpl> replace(UChar pattern, const char* replacement, unsigned replacementLength) { return replace(pattern, reinterpret_cast<const LChar*>(replacement), replacementLength); }
721 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> replace(UChar, const LChar*, unsigned replacementLength);
722 PassRefPtr<StringImpl> replace(UChar, const UChar*, unsigned replacementLength);
723 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> replace(StringImpl*, StringImpl*);
724 WTF_EXPORT_STRING_API PassRefPtr<StringImpl> replace(unsigned index, unsigned len, StringImpl*);
726 WTF_EXPORT_STRING_API WTF::Unicode::Direction defaultWritingDirection(bool* hasStrongDirectionality = 0);
729 RetainPtr<CFStringRef> createCFString();
732 operator NSString*();
736 ALWAYS_INLINE static StringStats& stringStats() { return m_stringStats; }
741 bool isASCIILiteral() const
743 return is8Bit() && hasInternalBuffer() && reinterpret_cast<const void*>(m_data8) != reinterpret_cast<const void*>(this + 1);
746 // This number must be at least 2 to avoid sharing empty, null as well as 1 character strings from SmallStrings.
747 static const unsigned s_copyCharsInlineCutOff = 20;
749 BufferOwnership bufferOwnership() const { return static_cast<BufferOwnership>(m_hashAndFlags & s_hashMaskBufferOwnership); }
750 bool isStatic() const { return m_refCount & s_refCountFlagIsStaticString; }
751 template <class UCharPredicate> PassRefPtr<StringImpl> stripMatchedCharacters(UCharPredicate);
752 template <typename CharType, class UCharPredicate> PassRefPtr<StringImpl> simplifyMatchedCharactersToSpace(UCharPredicate);
753 WTF_EXPORT_STRING_API NEVER_INLINE const UChar* getData16SlowCase() const;
754 WTF_EXPORT_PRIVATE NEVER_INLINE unsigned hashSlowCase() const;
756 // The bottom bit in the ref count indicates a static (immortal) string.
757 static const unsigned s_refCountFlagIsStaticString = 0x1;
758 static const unsigned s_refCountIncrement = 0x2; // This allows us to ref / deref without disturbing the static string flag.
760 // The bottom 8 bits in the hash are flags.
761 static const unsigned s_flagCount = 8;
762 static const unsigned s_flagMask = (1u << s_flagCount) - 1;
763 COMPILE_ASSERT(s_flagCount == StringHasher::flagCount, StringHasher_reserves_enough_bits_for_StringImpl_flags);
765 static const unsigned s_hashFlagHas16BitShadow = 1u << 7;
766 static const unsigned s_hashFlag8BitBuffer = 1u << 6;
767 static const unsigned s_hashFlagHasTerminatingNullCharacter = 1u << 5;
768 static const unsigned s_hashFlagIsAtomic = 1u << 4;
769 static const unsigned s_hashFlagDidReportCost = 1u << 3;
770 static const unsigned s_hashFlagIsIdentifier = 1u << 2;
771 static const unsigned s_hashMaskBufferOwnership = 1u | (1u << 1);
774 WTF_EXPORTDATA static StringStats m_stringStats;
778 struct StaticASCIILiteral {
779 // These member variables must match the layout of StringImpl.
782 const LChar* m_data8;
784 unsigned m_hashAndFlags;
786 // These values mimic ConstructFromLiteral.
787 static const unsigned s_initialRefCount = s_refCountIncrement;
788 static const unsigned s_initialFlags = s_hashFlag8BitBuffer | BufferInternal | s_hashFlagHasTerminatingNullCharacter;
789 static const unsigned s_hashShift = s_flagCount;
793 void assertHashIsCorrect()
796 ASSERT(existingHash() == StringHasher::computeHashAndMaskTop8Bits(characters8(), length()));
801 // These member variables must match the layout of StaticASCIILiteral.
805 const LChar* m_data8;
806 const UChar* m_data16;
810 StringImpl* m_substringBuffer;
811 mutable UChar* m_copyData16;
813 QStringData* m_qStringData;
816 mutable unsigned m_hashAndFlags;
819 COMPILE_ASSERT(sizeof(StringImpl) == sizeof(StringImpl::StaticASCIILiteral), StringImpl_should_match_its_StaticASCIILiteral);
822 // StringImpls created from StaticASCIILiteral will ASSERT
823 // in the generic ValueCheck<T>::checkConsistency
824 // as they are not allocated by fastMalloc.
825 // We don't currently have any way to detect that case
826 // so we ignore the consistency check for all StringImpl*.
828 ValueCheck<StringImpl*> {
829 static void checkConsistency(const StringImpl*) { }
834 ALWAYS_INLINE const LChar* StringImpl::getCharacters<LChar>() const { return characters8(); }
837 ALWAYS_INLINE const UChar* StringImpl::getCharacters<UChar>() const { return characters(); }
839 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const StringImpl*);
840 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const LChar*);
841 inline bool equal(const StringImpl* a, const char* b) { return equal(a, reinterpret_cast<const LChar*>(b)); }
842 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const LChar*, unsigned);
843 inline bool equal(const StringImpl* a, const char* b, unsigned length) { return equal(a, reinterpret_cast<const LChar*>(b), length); }
844 inline bool equal(const LChar* a, StringImpl* b) { return equal(b, a); }
845 inline bool equal(const char* a, StringImpl* b) { return equal(b, reinterpret_cast<const LChar*>(a)); }
846 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const UChar*, unsigned);
847 WTF_EXPORT_STRING_API bool equalNonNull(const StringImpl* a, const StringImpl* b);
849 // Do comparisons 8 or 4 bytes-at-a-time on architectures where it's safe.
851 ALWAYS_INLINE bool equal(const LChar* a, const LChar* b, unsigned length)
853 unsigned dwordLength = length >> 3;
856 const uint64_t* aDWordCharacters = reinterpret_cast<const uint64_t*>(a);
857 const uint64_t* bDWordCharacters = reinterpret_cast<const uint64_t*>(b);
859 for (unsigned i = 0; i != dwordLength; ++i) {
860 if (*aDWordCharacters++ != *bDWordCharacters++)
864 a = reinterpret_cast<const LChar*>(aDWordCharacters);
865 b = reinterpret_cast<const LChar*>(bDWordCharacters);
869 if (*reinterpret_cast<const uint32_t*>(a) != *reinterpret_cast<const uint32_t*>(b))
877 if (*reinterpret_cast<const uint16_t*>(a) != *reinterpret_cast<const uint16_t*>(b))
884 if (length & 1 && (*a != *b))
890 ALWAYS_INLINE bool equal(const UChar* a, const UChar* b, unsigned length)
892 unsigned dwordLength = length >> 2;
895 const uint64_t* aDWordCharacters = reinterpret_cast<const uint64_t*>(a);
896 const uint64_t* bDWordCharacters = reinterpret_cast<const uint64_t*>(b);
898 for (unsigned i = 0; i != dwordLength; ++i) {
899 if (*aDWordCharacters++ != *bDWordCharacters++)
903 a = reinterpret_cast<const UChar*>(aDWordCharacters);
904 b = reinterpret_cast<const UChar*>(bDWordCharacters);
908 if (*reinterpret_cast<const uint32_t*>(a) != *reinterpret_cast<const uint32_t*>(b))
915 if (length & 1 && (*a != *b))
921 ALWAYS_INLINE bool equal(const LChar* a, const LChar* b, unsigned length)
923 const uint32_t* aCharacters = reinterpret_cast<const uint32_t*>(a);
924 const uint32_t* bCharacters = reinterpret_cast<const uint32_t*>(b);
926 unsigned wordLength = length >> 2;
927 for (unsigned i = 0; i != wordLength; ++i) {
928 if (*aCharacters++ != *bCharacters++)
935 const LChar* aRemainder = reinterpret_cast<const LChar*>(aCharacters);
936 const LChar* bRemainder = reinterpret_cast<const LChar*>(bCharacters);
938 for (unsigned i = 0; i < length; ++i) {
939 if (aRemainder[i] != bRemainder[i])
947 ALWAYS_INLINE bool equal(const UChar* a, const UChar* b, unsigned length)
949 const uint32_t* aCharacters = reinterpret_cast<const uint32_t*>(a);
950 const uint32_t* bCharacters = reinterpret_cast<const uint32_t*>(b);
952 unsigned wordLength = length >> 1;
953 for (unsigned i = 0; i != wordLength; ++i) {
954 if (*aCharacters++ != *bCharacters++)
958 if (length & 1 && *reinterpret_cast<const UChar*>(aCharacters) != *reinterpret_cast<const UChar*>(bCharacters))
963 #elif PLATFORM(IOS) && WTF_ARM_ARCH_AT_LEAST(7)
964 ALWAYS_INLINE bool equal(const LChar* a, const LChar* b, unsigned length)
966 bool isEqual = false;
969 asm("subs %[length], #4\n"
972 "0:\n" // Label 0 = Start of loop over 32 bits.
973 "ldr %[aValue], [%[a]], #4\n"
974 "ldr %[bValue], [%[b]], #4\n"
975 "cmp %[aValue], %[bValue]\n"
977 "subs %[length], #4\n"
980 // At this point, length can be:
981 // -0: 00000000000000000000000000000000 (0 bytes left)
982 // -1: 11111111111111111111111111111111 (3 bytes left)
983 // -2: 11111111111111111111111111111110 (2 bytes left)
984 // -3: 11111111111111111111111111111101 (1 byte left)
985 // -4: 11111111111111111111111111111100 (length was 0)
986 // The pointers are at the correct position.
987 "2:\n" // Label 2 = End of loop over 32 bits, check for pair of characters.
988 "tst %[length], #2\n"
990 "ldrh %[aValue], [%[a]], #2\n"
991 "ldrh %[bValue], [%[b]], #2\n"
992 "cmp %[aValue], %[bValue]\n"
995 "1:\n" // Label 1 = Check for a single character left.
996 "tst %[length], #1\n"
998 "ldrb %[aValue], [%[a]]\n"
999 "ldrb %[bValue], [%[b]]\n"
1000 "cmp %[aValue], %[bValue]\n"
1003 "42:\n" // Label 42 = Success.
1004 "mov %[isEqual], #1\n"
1005 "66:\n" // Label 66 = End without changing isEqual to 1.
1006 : [length]"+r"(length), [isEqual]"+r"(isEqual), [a]"+r"(a), [b]"+r"(b), [aValue]"+r"(aValue), [bValue]"+r"(bValue)
1013 ALWAYS_INLINE bool equal(const UChar* a, const UChar* b, unsigned length)
1015 bool isEqual = false;
1018 asm("subs %[length], #2\n"
1021 "0:\n" // Label 0 = Start of loop over 32 bits.
1022 "ldr %[aValue], [%[a]], #4\n"
1023 "ldr %[bValue], [%[b]], #4\n"
1024 "cmp %[aValue], %[bValue]\n"
1026 "subs %[length], #2\n"
1029 // At this point, length can be:
1030 // -0: 00000000000000000000000000000000 (0 bytes left)
1031 // -1: 11111111111111111111111111111111 (1 character left, 2 bytes)
1032 // -2: 11111111111111111111111111111110 (length was zero)
1033 // The pointers are at the correct position.
1034 "1:\n" // Label 1 = Check for a single character left.
1035 "tst %[length], #1\n"
1037 "ldrh %[aValue], [%[a]]\n"
1038 "ldrh %[bValue], [%[b]]\n"
1039 "cmp %[aValue], %[bValue]\n"
1042 "42:\n" // Label 42 = Success.
1043 "mov %[isEqual], #1\n"
1044 "66:\n" // Label 66 = End without changing isEqual to 1.
1045 : [length]"+r"(length), [isEqual]"+r"(isEqual), [a]"+r"(a), [b]"+r"(b), [aValue]"+r"(aValue), [bValue]"+r"(bValue)
1052 ALWAYS_INLINE bool equal(const LChar* a, const LChar* b, unsigned length)
1054 for (unsigned i = 0; i != length; ++i) {
1062 ALWAYS_INLINE bool equal(const UChar* a, const UChar* b, unsigned length)
1064 for (unsigned i = 0; i != length; ++i) {
1073 ALWAYS_INLINE bool equal(const LChar* a, const UChar* b, unsigned length)
1075 for (unsigned i = 0; i != length; ++i) {
1083 ALWAYS_INLINE bool equal(const UChar* a, const LChar* b, unsigned length)
1085 for (unsigned i = 0; i != length; ++i) {
1093 WTF_EXPORT_STRING_API bool equalIgnoringCase(const StringImpl*, const StringImpl*);
1094 WTF_EXPORT_STRING_API bool equalIgnoringCase(const StringImpl*, const LChar*);
1095 inline bool equalIgnoringCase(const LChar* a, const StringImpl* b) { return equalIgnoringCase(b, a); }
1096 WTF_EXPORT_STRING_API bool equalIgnoringCase(const LChar*, const LChar*, unsigned);
1097 WTF_EXPORT_STRING_API bool equalIgnoringCase(const UChar*, const LChar*, unsigned);
1098 inline bool equalIgnoringCase(const UChar* a, const char* b, unsigned length) { return equalIgnoringCase(a, reinterpret_cast<const LChar*>(b), length); }
1099 inline bool equalIgnoringCase(const LChar* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, a, length); }
1100 inline bool equalIgnoringCase(const char* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
1101 inline bool equalIgnoringCase(const char* a, const LChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
1102 inline bool equalIgnoringCase(const UChar* a, const UChar* b, int length)
1104 ASSERT(length >= 0);
1105 return !Unicode::umemcasecmp(a, b, length);
1107 WTF_EXPORT_STRING_API bool equalIgnoringCaseNonNull(const StringImpl*, const StringImpl*);
1109 WTF_EXPORT_STRING_API bool equalIgnoringNullity(StringImpl*, StringImpl*);
1111 template<typename CharacterType>
1112 inline size_t find(const CharacterType* characters, unsigned length, CharacterType matchCharacter, unsigned index = 0)
1114 while (index < length) {
1115 if (characters[index] == matchCharacter)
1122 ALWAYS_INLINE size_t find(const UChar* characters, unsigned length, LChar matchCharacter, unsigned index = 0)
1124 return find(characters, length, static_cast<UChar>(matchCharacter), index);
1127 inline size_t find(const LChar* characters, unsigned length, UChar matchCharacter, unsigned index = 0)
1129 if (matchCharacter & ~0xFF)
1131 return find(characters, length, static_cast<LChar>(matchCharacter), index);
1134 inline size_t find(const LChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
1136 while (index < length) {
1137 if (matchFunction(characters[index]))
1144 inline size_t find(const UChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
1146 while (index < length) {
1147 if (matchFunction(characters[index]))
1154 template<typename CharacterType>
1155 inline size_t findNextLineStart(const CharacterType* characters, unsigned length, unsigned index = 0)
1157 while (index < length) {
1158 CharacterType c = characters[index++];
1159 if ((c != '\n') && (c != '\r'))
1162 // There can only be a start of a new line if there are more characters
1163 // beyond the current character.
1164 if (index < length) {
1165 // The 3 common types of line terminators are 1. \r\n (Windows),
1166 // 2. \r (old MacOS) and 3. \n (Unix'es).
1169 return index; // Case 3: just \n.
1171 CharacterType c2 = characters[index];
1173 return index; // Case 2: just \r.
1176 // But, there's only a start of a new line if there are more
1177 // characters beyond the \r\n.
1178 if (++index < length)
1185 template<typename CharacterType>
1186 inline size_t reverseFindLineTerminator(const CharacterType* characters, unsigned length, unsigned index = UINT_MAX)
1190 if (index >= length)
1192 CharacterType c = characters[index];
1193 while ((c != '\n') && (c != '\r')) {
1196 c = characters[index];
1201 template<typename CharacterType>
1202 inline size_t reverseFind(const CharacterType* characters, unsigned length, CharacterType matchCharacter, unsigned index = UINT_MAX)
1206 if (index >= length)
1208 while (characters[index] != matchCharacter) {
1215 ALWAYS_INLINE size_t reverseFind(const UChar* characters, unsigned length, LChar matchCharacter, unsigned index = UINT_MAX)
1217 return reverseFind(characters, length, static_cast<UChar>(matchCharacter), index);
1220 inline size_t reverseFind(const LChar* characters, unsigned length, UChar matchCharacter, unsigned index = UINT_MAX)
1222 if (matchCharacter & ~0xFF)
1224 return reverseFind(characters, length, static_cast<LChar>(matchCharacter), index);
1227 inline size_t StringImpl::find(LChar character, unsigned start)
1230 return WTF::find(characters8(), m_length, character, start);
1231 return WTF::find(characters16(), m_length, character, start);
1234 ALWAYS_INLINE size_t StringImpl::find(char character, unsigned start)
1236 return find(static_cast<LChar>(character), start);
1239 inline size_t StringImpl::find(UChar character, unsigned start)
1242 return WTF::find(characters8(), m_length, character, start);
1243 return WTF::find(characters16(), m_length, character, start);
1246 template<size_t inlineCapacity>
1247 bool equalIgnoringNullity(const Vector<UChar, inlineCapacity>& a, StringImpl* b)
1251 if (a.size() != b->length())
1253 return !memcmp(a.data(), b->characters(), b->length() * sizeof(UChar));
1256 template<typename CharacterType1, typename CharacterType2>
1257 static inline int codePointCompare(unsigned l1, unsigned l2, const CharacterType1* c1, const CharacterType2* c2)
1259 const unsigned lmin = l1 < l2 ? l1 : l2;
1261 while (pos < lmin && *c1 == *c2) {
1268 return (c1[0] > c2[0]) ? 1 : -1;
1273 return (l1 > l2) ? 1 : -1;
1276 static inline int codePointCompare8(const StringImpl* string1, const StringImpl* string2)
1278 return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters8());
1281 static inline int codePointCompare16(const StringImpl* string1, const StringImpl* string2)
1283 return codePointCompare(string1->length(), string2->length(), string1->characters16(), string2->characters16());
1286 static inline int codePointCompare8To16(const StringImpl* string1, const StringImpl* string2)
1288 return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters16());
1291 static inline int codePointCompare(const StringImpl* string1, const StringImpl* string2)
1294 return (string2 && string2->length()) ? -1 : 0;
1297 return string1->length() ? 1 : 0;
1299 bool string1Is8Bit = string1->is8Bit();
1300 bool string2Is8Bit = string2->is8Bit();
1301 if (string1Is8Bit) {
1303 return codePointCompare8(string1, string2);
1304 return codePointCompare8To16(string1, string2);
1307 return -codePointCompare8To16(string2, string1);
1308 return codePointCompare16(string1, string2);
1311 static inline bool isSpaceOrNewline(UChar c)
1313 // Use isASCIISpace() for basic Latin-1.
1314 // This will include newlines, which aren't included in Unicode DirWS.
1315 return c <= 0x7F ? WTF::isASCIISpace(c) : WTF::Unicode::direction(c) == WTF::Unicode::WhiteSpaceNeutral;
1318 inline PassRefPtr<StringImpl> StringImpl::isolatedCopy() const
1320 if (isASCIILiteral())
1321 return StringImpl::createFromLiteral(reinterpret_cast<const char*>(m_data8), m_length);
1323 return create(m_data8, m_length);
1324 return create(m_data16, m_length);
1329 // StringHash is the default hash for StringImpl* and RefPtr<StringImpl>
1330 template<typename T> struct DefaultHash;
1331 template<> struct DefaultHash<StringImpl*> {
1332 typedef StringHash Hash;
1334 template<> struct DefaultHash<RefPtr<StringImpl> > {
1335 typedef StringHash Hash;
1340 using WTF::StringImpl;
1342 using WTF::equalNonNull;
1343 using WTF::TextCaseSensitivity;
1344 using WTF::TextCaseSensitive;
1345 using WTF::TextCaseInsensitive;