2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2005-2010, 2013-2014 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 <unicode/uchar.h>
28 #include <unicode/ustring.h>
29 #include <wtf/ASCIICType.h>
30 #include <wtf/Forward.h>
31 #include <wtf/MathExtras.h>
32 #include <wtf/StdLibExtras.h>
33 #include <wtf/StringHasher.h>
34 #include <wtf/Vector.h>
35 #include <wtf/text/ConversionMode.h>
36 #include <wtf/text/StringCommon.h>
39 typedef const struct __CFString * CFStringRef;
47 namespace LLInt { class Data; }
48 class LLIntOffsetsExtractor;
53 struct CStringTranslator;
54 template<typename CharacterType> struct HashAndCharactersTranslator;
55 struct HashAndUTF8CharactersTranslator;
56 struct LCharBufferTranslator;
57 struct CharBufferFromLiteralDataTranslator;
58 struct SubstringTranslator;
59 struct UCharBufferTranslator;
60 template<typename> class RetainPtr;
64 enum TextCaseSensitivity {
69 typedef bool (*CharacterMatchFunctionPtr)(UChar);
70 typedef bool (*IsWhiteSpaceFunctionPtr)(UChar);
72 // Define STRING_STATS to 1 turn on run time statistics of string sizes and memory usage
73 #define STRING_STATS 0
77 inline void add8BitString(unsigned length, bool isSubString = false)
79 ++m_totalNumberStrings;
80 ++m_number8BitStrings;
82 m_total8BitData += length;
85 inline void add16BitString(unsigned length, bool isSubString = false)
87 ++m_totalNumberStrings;
88 ++m_number16BitStrings;
90 m_total16BitData += length;
93 void removeString(StringImpl&);
96 static const unsigned s_printStringStatsFrequency = 5000;
97 static std::atomic<unsigned> s_stringRemovesTillPrintStats;
99 std::atomic<unsigned> m_refCalls;
100 std::atomic<unsigned> m_derefCalls;
102 std::atomic<unsigned> m_totalNumberStrings;
103 std::atomic<unsigned> m_number8BitStrings;
104 std::atomic<unsigned> m_number16BitStrings;
105 std::atomic<unsigned long long> m_total8BitData;
106 std::atomic<unsigned long long> m_total16BitData;
109 #define STRING_STATS_ADD_8BIT_STRING(length) StringImpl::stringStats().add8BitString(length)
110 #define STRING_STATS_ADD_8BIT_STRING2(length, isSubString) StringImpl::stringStats().add8BitString(length, isSubString)
111 #define STRING_STATS_ADD_16BIT_STRING(length) StringImpl::stringStats().add16BitString(length)
112 #define STRING_STATS_ADD_16BIT_STRING2(length, isSubString) StringImpl::stringStats().add16BitString(length, isSubString)
113 #define STRING_STATS_REMOVE_STRING(string) StringImpl::stringStats().removeString(string)
114 #define STRING_STATS_REF_STRING(string) ++StringImpl::stringStats().m_refCalls;
115 #define STRING_STATS_DEREF_STRING(string) ++StringImpl::stringStats().m_derefCalls;
117 #define STRING_STATS_ADD_8BIT_STRING(length) ((void)0)
118 #define STRING_STATS_ADD_8BIT_STRING2(length, isSubString) ((void)0)
119 #define STRING_STATS_ADD_16BIT_STRING(length) ((void)0)
120 #define STRING_STATS_ADD_16BIT_STRING2(length, isSubString) ((void)0)
121 #define STRING_STATS_ADD_UPCONVERTED_STRING(length) ((void)0)
122 #define STRING_STATS_REMOVE_STRING(string) ((void)0)
123 #define STRING_STATS_REF_STRING(string) ((void)0)
124 #define STRING_STATS_DEREF_STRING(string) ((void)0)
128 WTF_MAKE_NONCOPYABLE(StringImpl); WTF_MAKE_FAST_ALLOCATED;
129 friend struct WTF::CStringTranslator;
130 template<typename CharacterType> friend struct WTF::HashAndCharactersTranslator;
131 friend struct WTF::HashAndUTF8CharactersTranslator;
132 friend struct WTF::CharBufferFromLiteralDataTranslator;
133 friend struct WTF::LCharBufferTranslator;
134 friend struct WTF::SubstringTranslator;
135 friend struct WTF::UCharBufferTranslator;
136 friend class JSC::LLInt::Data;
137 friend class JSC::LLIntOffsetsExtractor;
140 enum BufferOwnership {
146 // The bottom 6 bits in the hash are flags.
147 static const unsigned s_flagCount = 6;
148 static const unsigned s_flagMask = (1u << s_flagCount) - 1;
149 COMPILE_ASSERT(s_flagCount <= StringHasher::flagCount, StringHasher_reserves_enough_bits_for_StringImpl_flags);
150 static const unsigned s_flagStringKindCount = 4;
152 static const unsigned s_hashFlagStringKindIsAtomic = 1u << (s_flagStringKindCount);
153 static const unsigned s_hashFlagStringKindIsSymbol = 1u << (s_flagStringKindCount + 1);
154 static const unsigned s_hashMaskStringKind = s_hashFlagStringKindIsAtomic | s_hashFlagStringKindIsSymbol;
155 static const unsigned s_hashFlag8BitBuffer = 1u << 3;
156 static const unsigned s_hashFlagDidReportCost = 1u << 2;
157 static const unsigned s_hashMaskBufferOwnership = (1u << 0) | (1u << 1);
160 StringNormal = 0u, // non-symbol, non-atomic
161 StringAtomic = s_hashFlagStringKindIsAtomic, // non-symbol, atomic
162 StringSymbol = s_hashFlagStringKindIsSymbol, // symbol, non-atomic
165 // Used to construct static strings, which have an special refCount that can never hit zero.
166 // This means that the static string will never be destroyed, which is important because
167 // static strings will be shared across threads & ref-counted in a non-threadsafe manner.
168 friend class NeverDestroyed<StringImpl>;
169 enum ConstructEmptyStringTag { ConstructEmptyString };
170 StringImpl(ConstructEmptyStringTag)
171 : m_refCount(s_refCountFlagIsStaticString)
173 , m_data8(reinterpret_cast<const LChar*>(&m_length))
174 , m_hashAndFlags(s_hashFlag8BitBuffer | StringAtomic | BufferOwned)
176 // Ensure that the hash is computed so that AtomicStringHash can call existingHash()
177 // with impunity. The empty string is special because it is never entered into
178 // AtomicString's HashKey, but still needs to compare correctly.
179 STRING_STATS_ADD_8BIT_STRING(m_length);
184 // FIXME: there has to be a less hacky way to do this.
185 enum Force8Bit { Force8BitConstructor };
186 // Create a normal 8-bit string with internal storage (BufferInternal)
187 StringImpl(unsigned length, Force8Bit)
188 : m_refCount(s_refCountIncrement)
190 , m_data8(tailPointer<LChar>())
191 , m_hashAndFlags(s_hashFlag8BitBuffer | StringNormal | BufferInternal)
196 STRING_STATS_ADD_8BIT_STRING(m_length);
199 // Create a normal 16-bit string with internal storage (BufferInternal)
200 StringImpl(unsigned length)
201 : m_refCount(s_refCountIncrement)
203 , m_data16(tailPointer<UChar>())
204 , m_hashAndFlags(StringNormal | BufferInternal)
209 STRING_STATS_ADD_16BIT_STRING(m_length);
212 // Create a StringImpl adopting ownership of the provided buffer (BufferOwned)
213 StringImpl(MallocPtr<LChar> characters, unsigned length)
214 : m_refCount(s_refCountIncrement)
216 , m_data8(characters.leakPtr())
217 , m_hashAndFlags(s_hashFlag8BitBuffer | StringNormal | BufferOwned)
222 STRING_STATS_ADD_8BIT_STRING(m_length);
225 enum ConstructWithoutCopyingTag { ConstructWithoutCopying };
226 StringImpl(const UChar* characters, unsigned length, ConstructWithoutCopyingTag)
227 : m_refCount(s_refCountIncrement)
229 , m_data16(characters)
230 , m_hashAndFlags(StringNormal | BufferInternal)
235 STRING_STATS_ADD_16BIT_STRING(m_length);
238 StringImpl(const LChar* characters, unsigned length, ConstructWithoutCopyingTag)
239 : m_refCount(s_refCountIncrement)
241 , m_data8(characters)
242 , m_hashAndFlags(s_hashFlag8BitBuffer | StringNormal | BufferInternal)
247 STRING_STATS_ADD_8BIT_STRING(m_length);
250 // Create a StringImpl adopting ownership of the provided buffer (BufferOwned)
251 StringImpl(MallocPtr<UChar> characters, unsigned length)
252 : m_refCount(s_refCountIncrement)
254 , m_data16(characters.leakPtr())
255 , m_hashAndFlags(StringNormal | BufferOwned)
260 STRING_STATS_ADD_16BIT_STRING(m_length);
263 // Used to create new strings that are a substring of an existing 8-bit StringImpl (BufferSubstring)
264 StringImpl(const LChar* characters, unsigned length, PassRefPtr<StringImpl> base)
265 : m_refCount(s_refCountIncrement)
267 , m_data8(characters)
268 , m_hashAndFlags(s_hashFlag8BitBuffer | StringNormal | BufferSubstring)
273 ASSERT(base->bufferOwnership() != BufferSubstring);
275 substringBuffer() = base.leakRef();
277 STRING_STATS_ADD_8BIT_STRING2(m_length, true);
280 // Used to create new strings that are a substring of an existing 16-bit StringImpl (BufferSubstring)
281 StringImpl(const UChar* characters, unsigned length, PassRefPtr<StringImpl> base)
282 : m_refCount(s_refCountIncrement)
284 , m_data16(characters)
285 , m_hashAndFlags(StringNormal | BufferSubstring)
290 ASSERT(base->bufferOwnership() != BufferSubstring);
292 substringBuffer() = base.leakRef();
294 STRING_STATS_ADD_16BIT_STRING2(m_length, true);
297 enum CreateSymbolTag { CreateSymbol };
298 // Used to create new symbol strings that holds existing 8-bit [[Description]] string as a substring buffer (BufferSubstring).
299 StringImpl(CreateSymbolTag, const LChar* characters, unsigned length, PassRefPtr<StringImpl> base)
300 : m_refCount(s_refCountIncrement)
302 , m_data8(characters)
303 , m_hashAndFlags(s_hashFlag8BitBuffer | StringSymbol | BufferSubstring)
307 ASSERT(base->bufferOwnership() != BufferSubstring);
309 substringBuffer() = base.leakRef();
310 symbolRegistry() = nullptr;
311 hashForSymbol() = nextHashForSymbol();
313 STRING_STATS_ADD_8BIT_STRING2(m_length, true);
316 // Used to create new symbol strings that holds existing 16-bit [[Description]] string as a substring buffer (BufferSubstring).
317 StringImpl(CreateSymbolTag, const UChar* characters, unsigned length, PassRefPtr<StringImpl> base)
318 : m_refCount(s_refCountIncrement)
320 , m_data16(characters)
321 , m_hashAndFlags(StringSymbol | BufferSubstring)
325 ASSERT(base->bufferOwnership() != BufferSubstring);
327 substringBuffer() = base.leakRef();
328 symbolRegistry() = nullptr;
329 hashForSymbol() = nextHashForSymbol();
331 STRING_STATS_ADD_16BIT_STRING2(m_length, true);
335 WTF_EXPORT_STRING_API static void destroy(StringImpl*);
337 WTF_EXPORT_STRING_API static Ref<StringImpl> create(const UChar*, unsigned length);
338 WTF_EXPORT_STRING_API static Ref<StringImpl> create(const LChar*, unsigned length);
339 WTF_EXPORT_STRING_API static Ref<StringImpl> create8BitIfPossible(const UChar*, unsigned length);
340 template<size_t inlineCapacity>
341 static Ref<StringImpl> create8BitIfPossible(const Vector<UChar, inlineCapacity>& vector)
343 return create8BitIfPossible(vector.data(), vector.size());
345 WTF_EXPORT_STRING_API static Ref<StringImpl> create8BitIfPossible(const UChar*);
347 ALWAYS_INLINE static Ref<StringImpl> create(const char* s, unsigned length) { return create(reinterpret_cast<const LChar*>(s), length); }
348 WTF_EXPORT_STRING_API static Ref<StringImpl> create(const LChar*);
349 ALWAYS_INLINE static Ref<StringImpl> create(const char* s) { return create(reinterpret_cast<const LChar*>(s)); }
351 static ALWAYS_INLINE Ref<StringImpl> createSubstringSharingImpl8(PassRefPtr<StringImpl> rep, unsigned offset, unsigned length)
354 ASSERT(length <= rep->length());
359 ASSERT(rep->is8Bit());
360 StringImpl* ownerRep = (rep->bufferOwnership() == BufferSubstring) ? rep->substringBuffer() : rep.get();
362 // We allocate a buffer that contains both the StringImpl struct as well as the pointer to the owner string.
363 StringImpl* stringImpl = static_cast<StringImpl*>(fastMalloc(allocationSize<StringImpl*>(1)));
364 return adoptRef(*new (NotNull, stringImpl) StringImpl(rep->m_data8 + offset, length, ownerRep));
367 static ALWAYS_INLINE Ref<StringImpl> createSubstringSharingImpl(PassRefPtr<StringImpl> rep, unsigned offset, unsigned length)
370 ASSERT(length <= rep->length());
375 StringImpl* ownerRep = (rep->bufferOwnership() == BufferSubstring) ? rep->substringBuffer() : rep.get();
377 // We allocate a buffer that contains both the StringImpl struct as well as the pointer to the owner string.
378 StringImpl* stringImpl = static_cast<StringImpl*>(fastMalloc(allocationSize<StringImpl*>(1)));
380 return adoptRef(*new (NotNull, stringImpl) StringImpl(rep->m_data8 + offset, length, ownerRep));
381 return adoptRef(*new (NotNull, stringImpl) StringImpl(rep->m_data16 + offset, length, ownerRep));
384 template<unsigned charactersCount>
385 ALWAYS_INLINE static Ref<StringImpl> createFromLiteral(const char (&characters)[charactersCount])
387 COMPILE_ASSERT(charactersCount > 1, StringImplFromLiteralNotEmpty);
388 COMPILE_ASSERT((charactersCount - 1 <= ((unsigned(~0) - sizeof(StringImpl)) / sizeof(LChar))), StringImplFromLiteralCannotOverflow);
390 return createWithoutCopying(reinterpret_cast<const LChar*>(characters), charactersCount - 1);
393 // FIXME: Transition off of these functions to createWithoutCopying instead.
394 WTF_EXPORT_STRING_API static Ref<StringImpl> createFromLiteral(const char* characters, unsigned length);
395 WTF_EXPORT_STRING_API static Ref<StringImpl> createFromLiteral(const char* characters);
397 WTF_EXPORT_STRING_API static Ref<StringImpl> createWithoutCopying(const UChar* characters, unsigned length);
398 WTF_EXPORT_STRING_API static Ref<StringImpl> createWithoutCopying(const LChar* characters, unsigned length);
400 WTF_EXPORT_STRING_API static Ref<StringImpl> createUninitialized(unsigned length, LChar*& data);
401 WTF_EXPORT_STRING_API static Ref<StringImpl> createUninitialized(unsigned length, UChar*& data);
402 template <typename T> static ALWAYS_INLINE PassRefPtr<StringImpl> tryCreateUninitialized(unsigned length, T*& output)
409 if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(T))) {
413 StringImpl* resultImpl;
414 if (!tryFastMalloc(allocationSize<T>(length)).getValue(resultImpl)) {
418 output = resultImpl->tailPointer<T>();
420 return constructInternal<T>(resultImpl, length);
423 WTF_EXPORT_STRING_API static Ref<SymbolImpl> createSymbolEmpty();
424 WTF_EXPORT_STRING_API static Ref<SymbolImpl> createSymbol(PassRefPtr<StringImpl> rep);
426 // Reallocate the StringImpl. The originalString must be only owned by the PassRefPtr,
427 // and the buffer ownership must be BufferInternal. Just like the input pointer of realloc(),
428 // the originalString can't be used after this function.
429 static Ref<StringImpl> reallocate(PassRefPtr<StringImpl> originalString, unsigned length, LChar*& data);
430 static Ref<StringImpl> reallocate(PassRefPtr<StringImpl> originalString, unsigned length, UChar*& data);
432 static unsigned flagsOffset() { return OBJECT_OFFSETOF(StringImpl, m_hashAndFlags); }
433 static unsigned flagIs8Bit() { return s_hashFlag8BitBuffer; }
434 static unsigned flagIsAtomic() { return s_hashFlagStringKindIsAtomic; }
435 static unsigned flagIsSymbol() { return s_hashFlagStringKindIsSymbol; }
436 static unsigned maskStringKind() { return s_hashMaskStringKind; }
437 static unsigned dataOffset() { return OBJECT_OFFSETOF(StringImpl, m_data8); }
439 template<typename CharType, size_t inlineCapacity, typename OverflowHandler>
440 static Ref<StringImpl> adopt(Vector<CharType, inlineCapacity, OverflowHandler>& vector)
442 if (size_t size = vector.size()) {
443 ASSERT(vector.data());
444 if (size > std::numeric_limits<unsigned>::max())
446 return adoptRef(*new StringImpl(vector.releaseBuffer(), size));
451 WTF_EXPORT_STRING_API static Ref<StringImpl> adopt(StringBuffer<UChar>&);
452 WTF_EXPORT_STRING_API static Ref<StringImpl> adopt(StringBuffer<LChar>&);
454 unsigned length() const { return m_length; }
455 static ptrdiff_t lengthMemoryOffset() { return OBJECT_OFFSETOF(StringImpl, m_length); }
456 bool is8Bit() const { return m_hashAndFlags & s_hashFlag8BitBuffer; }
458 ALWAYS_INLINE const LChar* characters8() const { ASSERT(is8Bit()); return m_data8; }
459 ALWAYS_INLINE const UChar* characters16() const { ASSERT(!is8Bit()); return m_data16; }
461 template <typename CharType>
462 ALWAYS_INLINE const CharType *characters() const;
466 // For substrings, return the cost of the base string.
467 if (bufferOwnership() == BufferSubstring)
468 return substringBuffer()->cost();
470 if (m_hashAndFlags & s_hashFlagDidReportCost)
473 m_hashAndFlags |= s_hashFlagDidReportCost;
474 size_t result = m_length;
480 size_t costDuringGC()
485 if (bufferOwnership() == BufferSubstring)
486 return divideRoundedUp(substringBuffer()->costDuringGC(), refCount());
488 size_t result = m_length;
491 return divideRoundedUp(result, refCount());
494 WTF_EXPORT_STRING_API size_t sizeInBytes() const;
496 StringKind stringKind() const { return static_cast<StringKind>(m_hashAndFlags & s_hashMaskStringKind); }
497 bool isSymbol() const { return m_hashAndFlags & s_hashFlagStringKindIsSymbol; }
498 bool isAtomic() const { return m_hashAndFlags & s_hashFlagStringKindIsAtomic; }
500 void setIsAtomic(bool isAtomic)
505 m_hashAndFlags |= s_hashFlagStringKindIsAtomic;
506 ASSERT(stringKind() == StringAtomic);
508 m_hashAndFlags &= ~s_hashFlagStringKindIsAtomic;
509 ASSERT(stringKind() == StringNormal);
514 bool isSubString() const { return bufferOwnership() == BufferSubstring; }
517 static WTF_EXPORT_STRING_API CString utf8ForCharacters(const LChar* characters, unsigned length);
518 static WTF_EXPORT_STRING_API CString utf8ForCharacters(const UChar* characters, unsigned length, ConversionMode = LenientConversion);
519 WTF_EXPORT_STRING_API CString utf8ForRange(unsigned offset, unsigned length, ConversionMode = LenientConversion) const;
520 WTF_EXPORT_STRING_API CString utf8(ConversionMode = LenientConversion) const;
523 static WTF_EXPORT_STRING_API bool utf8Impl(const UChar* characters, unsigned length, char*& buffer, size_t bufferSize, ConversionMode);
525 // The high bits of 'hash' are always empty, but we prefer to store our flags
526 // in the low bits because it makes them slightly more efficient to access.
527 // So, we shift left and right when setting and getting our hash code.
528 void setHash(unsigned hash) const
531 // Multiple clients assume that StringHasher is the canonical string hash function.
532 ASSERT(hash == (is8Bit() ? StringHasher::computeHashAndMaskTop8Bits(m_data8, m_length) : StringHasher::computeHashAndMaskTop8Bits(m_data16, m_length)));
533 ASSERT(!(hash & (s_flagMask << (8 * sizeof(hash) - s_flagCount)))); // Verify that enough high bits are empty.
535 hash <<= s_flagCount;
536 ASSERT(!(hash & m_hashAndFlags)); // Verify that enough low bits are empty after shift.
537 ASSERT(hash); // Verify that 0 is a valid sentinel hash value.
539 m_hashAndFlags |= hash; // Store hash with flags in low bits.
542 unsigned rawHash() const
544 return m_hashAndFlags >> s_flagCount;
550 return rawHash() != 0;
553 unsigned existingHash() const
559 unsigned hash() const
562 return existingHash();
563 return hashSlowCase();
566 unsigned symbolAwareHash() const
569 return hashForSymbol();
573 unsigned existingSymbolAwareHash() const
576 return hashForSymbol();
577 return existingHash();
580 bool isStatic() const { return m_refCount & s_refCountFlagIsStaticString; }
582 inline size_t refCount() const
584 return m_refCount / s_refCountIncrement;
587 inline bool hasOneRef() const
589 return m_refCount == s_refCountIncrement;
592 // This method is useful for assertions.
593 inline bool hasAtLeastOneRef() const
600 ASSERT(!isCompilationThread());
602 STRING_STATS_REF_STRING(*this);
604 m_refCount += s_refCountIncrement;
609 ASSERT(!isCompilationThread());
611 STRING_STATS_DEREF_STRING(*this);
613 unsigned tempRefCount = m_refCount - s_refCountIncrement;
615 StringImpl::destroy(this);
618 m_refCount = tempRefCount;
621 WTF_EXPORT_PRIVATE static StringImpl* empty();
623 // FIXME: Does this really belong in StringImpl?
624 template <typename T> static void copyChars(T* destination, const T* source, unsigned numCharacters)
626 if (numCharacters == 1) {
627 *destination = *source;
631 if (numCharacters <= s_copyCharsInlineCutOff) {
633 #if (CPU(X86) || CPU(X86_64))
634 const unsigned charsPerInt = sizeof(uint32_t) / sizeof(T);
636 if (numCharacters > charsPerInt) {
637 unsigned stopCount = numCharacters & ~(charsPerInt - 1);
639 const uint32_t* srcCharacters = reinterpret_cast<const uint32_t*>(source);
640 uint32_t* destCharacters = reinterpret_cast<uint32_t*>(destination);
641 for (unsigned j = 0; i < stopCount; i += charsPerInt, ++j)
642 destCharacters[j] = srcCharacters[j];
645 for (; i < numCharacters; ++i)
646 destination[i] = source[i];
648 memcpy(destination, source, numCharacters * sizeof(T));
651 ALWAYS_INLINE static void copyChars(UChar* destination, const LChar* source, unsigned numCharacters)
653 for (unsigned i = 0; i < numCharacters; ++i)
654 destination[i] = source[i];
657 // Some string features, like refcounting and the atomicity flag, are not
658 // thread-safe. We achieve thread safety by isolation, giving each thread
659 // its own copy of the string.
660 Ref<StringImpl> isolatedCopy() const;
662 WTF_EXPORT_STRING_API Ref<StringImpl> substring(unsigned pos, unsigned len = UINT_MAX);
664 UChar at(unsigned i) const
666 ASSERT_WITH_SECURITY_IMPLICATION(i < m_length);
671 UChar operator[](unsigned i) const { return at(i); }
672 WTF_EXPORT_STRING_API UChar32 characterStartingAt(unsigned);
674 WTF_EXPORT_STRING_API bool containsOnlyWhitespace();
676 int toIntStrict(bool* ok = 0, int base = 10);
677 unsigned toUIntStrict(bool* ok = 0, int base = 10);
678 int64_t toInt64Strict(bool* ok = 0, int base = 10);
679 uint64_t toUInt64Strict(bool* ok = 0, int base = 10);
680 intptr_t toIntPtrStrict(bool* ok = 0, int base = 10);
682 WTF_EXPORT_STRING_API int toInt(bool* ok = 0); // ignores trailing garbage
683 unsigned toUInt(bool* ok = 0); // ignores trailing garbage
684 int64_t toInt64(bool* ok = 0); // ignores trailing garbage
685 uint64_t toUInt64(bool* ok = 0); // ignores trailing garbage
686 intptr_t toIntPtr(bool* ok = 0); // ignores trailing garbage
688 // FIXME: Like the strict functions above, these give false for "ok" when there is trailing garbage.
689 // Like the non-strict functions above, these return the value when there is trailing garbage.
690 // It would be better if these were more consistent with the above functions instead.
691 double toDouble(bool* ok = 0);
692 float toFloat(bool* ok = 0);
694 WTF_EXPORT_STRING_API Ref<StringImpl> convertToASCIILowercase();
695 WTF_EXPORT_STRING_API Ref<StringImpl> lower();
696 WTF_EXPORT_STRING_API Ref<StringImpl> upper();
697 WTF_EXPORT_STRING_API Ref<StringImpl> lower(const AtomicString& localeIdentifier);
698 WTF_EXPORT_STRING_API Ref<StringImpl> upper(const AtomicString& localeIdentifier);
700 Ref<StringImpl> foldCase();
702 Ref<StringImpl> stripWhiteSpace();
703 Ref<StringImpl> stripWhiteSpace(IsWhiteSpaceFunctionPtr);
704 WTF_EXPORT_STRING_API Ref<StringImpl> simplifyWhiteSpace();
705 Ref<StringImpl> simplifyWhiteSpace(IsWhiteSpaceFunctionPtr);
707 Ref<StringImpl> removeCharacters(CharacterMatchFunctionPtr);
708 template <typename CharType>
709 ALWAYS_INLINE Ref<StringImpl> removeCharacters(const CharType* characters, CharacterMatchFunctionPtr);
711 size_t find(LChar character, unsigned start = 0);
712 size_t find(char character, unsigned start = 0);
713 size_t find(UChar character, unsigned start = 0);
714 WTF_EXPORT_STRING_API size_t find(CharacterMatchFunctionPtr, unsigned index = 0);
715 size_t find(const LChar*, unsigned index = 0);
716 ALWAYS_INLINE size_t find(const char* s, unsigned index = 0) { return find(reinterpret_cast<const LChar*>(s), index); }
717 WTF_EXPORT_STRING_API size_t find(StringImpl*);
718 WTF_EXPORT_STRING_API size_t find(StringImpl*, unsigned index);
719 size_t findIgnoringCase(const LChar*, unsigned index = 0);
720 ALWAYS_INLINE size_t findIgnoringCase(const char* s, unsigned index = 0) { return findIgnoringCase(reinterpret_cast<const LChar*>(s), index); }
721 WTF_EXPORT_STRING_API size_t findIgnoringCase(StringImpl*, unsigned index = 0);
722 WTF_EXPORT_STRING_API size_t findIgnoringASCIICase(const StringImpl&) const;
723 WTF_EXPORT_STRING_API size_t findIgnoringASCIICase(const StringImpl&, unsigned startOffset) const;
724 WTF_EXPORT_STRING_API size_t findIgnoringASCIICase(const StringImpl*) const;
725 WTF_EXPORT_STRING_API size_t findIgnoringASCIICase(const StringImpl*, unsigned startOffset) const;
727 WTF_EXPORT_STRING_API size_t findNextLineStart(unsigned index = UINT_MAX);
729 WTF_EXPORT_STRING_API size_t reverseFind(UChar, unsigned index = UINT_MAX);
730 WTF_EXPORT_STRING_API size_t reverseFind(StringImpl*, unsigned index = UINT_MAX);
731 WTF_EXPORT_STRING_API size_t reverseFindIgnoringCase(StringImpl*, unsigned index = UINT_MAX);
733 WTF_EXPORT_STRING_API bool startsWith(const StringImpl*) const;
734 WTF_EXPORT_STRING_API bool startsWith(const StringImpl&) const;
735 WTF_EXPORT_STRING_API bool startsWithIgnoringASCIICase(const StringImpl*) const;
736 WTF_EXPORT_STRING_API bool startsWithIgnoringASCIICase(const StringImpl&) const;
737 bool startsWith(StringImpl* str, bool caseSensitive) { return caseSensitive ? startsWith(str) : (reverseFindIgnoringCase(str, 0) == 0); }
738 WTF_EXPORT_STRING_API bool startsWith(UChar) const;
739 WTF_EXPORT_STRING_API bool startsWith(const char*, unsigned matchLength, bool caseSensitive) const;
740 template<unsigned matchLength>
741 bool startsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return startsWith(prefix, matchLength - 1, caseSensitive); }
742 WTF_EXPORT_STRING_API bool hasInfixStartingAt(const StringImpl&, unsigned startOffset) const;
744 WTF_EXPORT_STRING_API bool endsWith(StringImpl*);
745 WTF_EXPORT_STRING_API bool endsWith(StringImpl&);
746 WTF_EXPORT_STRING_API bool endsWithIgnoringASCIICase(const StringImpl*) const;
747 WTF_EXPORT_STRING_API bool endsWithIgnoringASCIICase(const StringImpl&) const;
748 WTF_EXPORT_STRING_API bool endsWith(StringImpl*, bool caseSensitive);
749 WTF_EXPORT_STRING_API bool endsWith(UChar) const;
750 WTF_EXPORT_STRING_API bool endsWith(const char*, unsigned matchLength, bool caseSensitive) const;
751 template<unsigned matchLength>
752 bool endsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return endsWith(prefix, matchLength - 1, caseSensitive); }
753 WTF_EXPORT_STRING_API bool hasInfixEndingAt(const StringImpl&, unsigned endOffset) const;
755 WTF_EXPORT_STRING_API Ref<StringImpl> replace(UChar, UChar);
756 WTF_EXPORT_STRING_API Ref<StringImpl> replace(UChar, StringImpl*);
757 ALWAYS_INLINE Ref<StringImpl> replace(UChar pattern, const char* replacement, unsigned replacementLength) { return replace(pattern, reinterpret_cast<const LChar*>(replacement), replacementLength); }
758 WTF_EXPORT_STRING_API Ref<StringImpl> replace(UChar, const LChar*, unsigned replacementLength);
759 Ref<StringImpl> replace(UChar, const UChar*, unsigned replacementLength);
760 WTF_EXPORT_STRING_API Ref<StringImpl> replace(StringImpl*, StringImpl*);
761 WTF_EXPORT_STRING_API Ref<StringImpl> replace(unsigned index, unsigned len, StringImpl*);
763 WTF_EXPORT_STRING_API UCharDirection defaultWritingDirection(bool* hasStrongDirectionality = nullptr);
766 RetainPtr<CFStringRef> createCFString();
769 WTF_EXPORT_STRING_API operator NSString*();
773 ALWAYS_INLINE static StringStats& stringStats() { return m_stringStats; }
776 WTF_EXPORT_STRING_API static const UChar latin1CaseFoldTable[256];
778 Ref<StringImpl> extractFoldedStringInSymbol()
781 ASSERT(bufferOwnership() == BufferSubstring);
782 ASSERT(substringBuffer());
783 ASSERT(!substringBuffer()->isSymbol());
784 return createSubstringSharingImpl(this, 0, length());
787 SymbolRegistry* const& symbolRegistry() const
790 return *(tailPointer<SymbolRegistry*>() + 1);
793 SymbolRegistry*& symbolRegistry()
796 return *(tailPointer<SymbolRegistry*>() + 1);
799 const unsigned& hashForSymbol() const
801 return const_cast<StringImpl*>(this)->hashForSymbol();
804 unsigned& hashForSymbol()
807 return *reinterpret_cast<unsigned*>((tailPointer<SymbolRegistry*>() + 2));
814 bool requiresCopy() const
816 if (bufferOwnership() != BufferInternal)
820 return m_data8 == tailPointer<LChar>();
821 return m_data16 == tailPointer<UChar>();
825 static size_t allocationSize(unsigned tailElementCount)
827 return tailOffset<T>() + tailElementCount * sizeof(T);
831 static ptrdiff_t tailOffset()
834 // MSVC doesn't support alignof yet.
835 return roundUpToMultipleOf<sizeof(T)>(sizeof(StringImpl));
837 return roundUpToMultipleOf<alignof(T)>(offsetof(StringImpl, m_hashAndFlags) + sizeof(StringImpl::m_hashAndFlags));
842 const T* tailPointer() const
844 return reinterpret_cast_ptr<const T*>(reinterpret_cast<const uint8_t*>(this) + tailOffset<T>());
850 return reinterpret_cast_ptr<T*>(reinterpret_cast<uint8_t*>(this) + tailOffset<T>());
853 StringImpl* const& substringBuffer() const
855 ASSERT(bufferOwnership() == BufferSubstring);
857 return *tailPointer<StringImpl*>();
860 StringImpl*& substringBuffer()
862 ASSERT(bufferOwnership() == BufferSubstring);
864 return *tailPointer<StringImpl*>();
867 // This number must be at least 2 to avoid sharing empty, null as well as 1 character strings from SmallStrings.
868 static const unsigned s_copyCharsInlineCutOff = 20;
870 BufferOwnership bufferOwnership() const { return static_cast<BufferOwnership>(m_hashAndFlags & s_hashMaskBufferOwnership); }
871 template <class UCharPredicate> Ref<StringImpl> stripMatchedCharacters(UCharPredicate);
872 template <typename CharType, class UCharPredicate> Ref<StringImpl> simplifyMatchedCharactersToSpace(UCharPredicate);
873 template <typename CharType> static Ref<StringImpl> constructInternal(StringImpl*, unsigned);
874 template <typename CharType> static Ref<StringImpl> createUninitializedInternal(unsigned, CharType*&);
875 template <typename CharType> static Ref<StringImpl> createUninitializedInternalNonEmpty(unsigned, CharType*&);
876 template <typename CharType> static Ref<StringImpl> reallocateInternal(PassRefPtr<StringImpl>, unsigned, CharType*&);
877 template <typename CharType> static Ref<StringImpl> createInternal(const CharType*, unsigned);
878 WTF_EXPORT_PRIVATE NEVER_INLINE unsigned hashSlowCase() const;
879 WTF_EXPORT_PRIVATE static unsigned nextHashForSymbol();
881 // The bottom bit in the ref count indicates a static (immortal) string.
882 static const unsigned s_refCountFlagIsStaticString = 0x1;
883 static const unsigned s_refCountIncrement = 0x2; // This allows us to ref / deref without disturbing the static string flag.
886 WTF_EXPORTDATA static StringStats m_stringStats;
890 struct StaticASCIILiteral {
891 // These member variables must match the layout of StringImpl.
894 const LChar* m_data8;
895 unsigned m_hashAndFlags;
897 // These values mimic ConstructFromLiteral.
898 static const unsigned s_initialRefCount = s_refCountIncrement;
899 static const unsigned s_initialFlags = s_hashFlag8BitBuffer | StringNormal | BufferInternal;
900 static const unsigned s_hashShift = s_flagCount;
904 void assertHashIsCorrect()
907 ASSERT(existingHash() == StringHasher::computeHashAndMaskTop8Bits(characters8(), length()));
912 // These member variables must match the layout of StaticASCIILiteral.
916 const LChar* m_data8;
917 const UChar* m_data16;
919 mutable unsigned m_hashAndFlags;
922 static_assert(sizeof(StringImpl) == sizeof(StringImpl::StaticASCIILiteral), "");
925 // StringImpls created from StaticASCIILiteral will ASSERT
926 // in the generic ValueCheck<T>::checkConsistency
927 // as they are not allocated by fastMalloc.
928 // We don't currently have any way to detect that case
929 // so we ignore the consistency check for all StringImpl*.
931 ValueCheck<StringImpl*> {
932 static void checkConsistency(const StringImpl*) { }
937 ALWAYS_INLINE Ref<StringImpl> StringImpl::constructInternal<LChar>(StringImpl* impl, unsigned length) { return adoptRef(*new (NotNull, impl) StringImpl(length, Force8BitConstructor)); }
939 ALWAYS_INLINE Ref<StringImpl> StringImpl::constructInternal<UChar>(StringImpl* impl, unsigned length) { return adoptRef(*new (NotNull, impl) StringImpl(length)); }
942 ALWAYS_INLINE const LChar* StringImpl::characters<LChar>() const { return characters8(); }
945 ALWAYS_INLINE const UChar* StringImpl::characters<UChar>() const { return characters16(); }
947 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const StringImpl*);
948 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const LChar*);
949 inline bool equal(const StringImpl* a, const char* b) { return equal(a, reinterpret_cast<const LChar*>(b)); }
950 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const LChar*, unsigned);
951 WTF_EXPORT_STRING_API bool equal(const StringImpl*, const UChar*, unsigned);
952 inline bool equal(const StringImpl* a, const char* b, unsigned length) { return equal(a, reinterpret_cast<const LChar*>(b), length); }
953 inline bool equal(const LChar* a, StringImpl* b) { return equal(b, a); }
954 inline bool equal(const char* a, StringImpl* b) { return equal(b, reinterpret_cast<const LChar*>(a)); }
955 WTF_EXPORT_STRING_API bool equal(const StringImpl& a, const StringImpl& b);
957 WTF_EXPORT_STRING_API bool equalIgnoringCase(const StringImpl*, const StringImpl*);
958 WTF_EXPORT_STRING_API bool equalIgnoringCase(const StringImpl*, const LChar*);
959 inline bool equalIgnoringCase(const LChar* a, const StringImpl* b) { return equalIgnoringCase(b, a); }
960 WTF_EXPORT_STRING_API bool equalIgnoringCase(const LChar*, const LChar*, unsigned);
961 WTF_EXPORT_STRING_API bool equalIgnoringCase(const UChar*, const LChar*, unsigned);
962 inline bool equalIgnoringCase(const UChar* a, const char* b, unsigned length) { return equalIgnoringCase(a, reinterpret_cast<const LChar*>(b), length); }
963 inline bool equalIgnoringCase(const LChar* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, a, length); }
964 inline bool equalIgnoringCase(const char* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
965 inline bool equalIgnoringCase(const char* a, const LChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
966 inline bool equalIgnoringCase(const UChar* a, const UChar* b, int length)
969 return !u_memcasecmp(a, b, length, U_FOLD_CASE_DEFAULT);
971 WTF_EXPORT_STRING_API bool equalIgnoringCaseNonNull(const StringImpl*, const StringImpl*);
973 WTF_EXPORT_STRING_API bool equalIgnoringNullity(StringImpl*, StringImpl*);
974 WTF_EXPORT_STRING_API bool equalIgnoringNullity(const UChar*, size_t length, StringImpl*);
976 WTF_EXPORT_STRING_API bool equalIgnoringASCIICase(const StringImpl&, const StringImpl&);
977 WTF_EXPORT_STRING_API bool equalIgnoringASCIICase(const StringImpl*, const StringImpl*);
978 WTF_EXPORT_STRING_API bool equalIgnoringASCIICase(const StringImpl& a, const char* b, unsigned bLength);
979 WTF_EXPORT_STRING_API bool equalIgnoringASCIICaseNonNull(const StringImpl*, const StringImpl*);
981 template<unsigned charactersCount>
982 bool equalIgnoringASCIICase(const StringImpl* a, const char (&b)[charactersCount])
984 return a ? equalIgnoringASCIICase(*a, b, charactersCount - 1) : false;
987 inline size_t find(const LChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
989 while (index < length) {
990 if (matchFunction(characters[index]))
997 inline size_t find(const UChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
999 while (index < length) {
1000 if (matchFunction(characters[index]))
1007 template<typename CharacterType>
1008 inline size_t findNextLineStart(const CharacterType* characters, unsigned length, unsigned index = 0)
1010 while (index < length) {
1011 CharacterType c = characters[index++];
1012 if ((c != '\n') && (c != '\r'))
1015 // There can only be a start of a new line if there are more characters
1016 // beyond the current character.
1017 if (index < length) {
1018 // The 3 common types of line terminators are 1. \r\n (Windows),
1019 // 2. \r (old MacOS) and 3. \n (Unix'es).
1022 return index; // Case 3: just \n.
1024 CharacterType c2 = characters[index];
1026 return index; // Case 2: just \r.
1029 // But, there's only a start of a new line if there are more
1030 // characters beyond the \r\n.
1031 if (++index < length)
1038 template<typename CharacterType>
1039 inline size_t reverseFindLineTerminator(const CharacterType* characters, unsigned length, unsigned index = UINT_MAX)
1043 if (index >= length)
1045 CharacterType c = characters[index];
1046 while ((c != '\n') && (c != '\r')) {
1049 c = characters[index];
1054 template<typename CharacterType>
1055 inline size_t reverseFind(const CharacterType* characters, unsigned length, CharacterType matchCharacter, unsigned index = UINT_MAX)
1059 if (index >= length)
1061 while (characters[index] != matchCharacter) {
1068 ALWAYS_INLINE size_t reverseFind(const UChar* characters, unsigned length, LChar matchCharacter, unsigned index = UINT_MAX)
1070 return reverseFind(characters, length, static_cast<UChar>(matchCharacter), index);
1073 inline size_t reverseFind(const LChar* characters, unsigned length, UChar matchCharacter, unsigned index = UINT_MAX)
1075 if (matchCharacter & ~0xFF)
1077 return reverseFind(characters, length, static_cast<LChar>(matchCharacter), index);
1080 inline size_t StringImpl::find(LChar character, unsigned start)
1083 return WTF::find(characters8(), m_length, character, start);
1084 return WTF::find(characters16(), m_length, character, start);
1087 ALWAYS_INLINE size_t StringImpl::find(char character, unsigned start)
1089 return find(static_cast<LChar>(character), start);
1092 inline size_t StringImpl::find(UChar character, unsigned start)
1095 return WTF::find(characters8(), m_length, character, start);
1096 return WTF::find(characters16(), m_length, character, start);
1099 template<size_t inlineCapacity> inline bool equalIgnoringNullity(const Vector<UChar, inlineCapacity>& a, StringImpl* b)
1101 return equalIgnoringNullity(a.data(), a.size(), b);
1104 template<typename CharacterType1, typename CharacterType2>
1105 inline int codePointCompare(unsigned l1, unsigned l2, const CharacterType1* c1, const CharacterType2* c2)
1107 const unsigned lmin = l1 < l2 ? l1 : l2;
1109 while (pos < lmin && *c1 == *c2) {
1116 return (c1[0] > c2[0]) ? 1 : -1;
1121 return (l1 > l2) ? 1 : -1;
1124 inline int codePointCompare8(const StringImpl* string1, const StringImpl* string2)
1126 return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters8());
1129 inline int codePointCompare16(const StringImpl* string1, const StringImpl* string2)
1131 return codePointCompare(string1->length(), string2->length(), string1->characters16(), string2->characters16());
1134 inline int codePointCompare8To16(const StringImpl* string1, const StringImpl* string2)
1136 return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters16());
1139 inline int codePointCompare(const StringImpl* string1, const StringImpl* string2)
1142 return (string2 && string2->length()) ? -1 : 0;
1145 return string1->length() ? 1 : 0;
1147 bool string1Is8Bit = string1->is8Bit();
1148 bool string2Is8Bit = string2->is8Bit();
1149 if (string1Is8Bit) {
1151 return codePointCompare8(string1, string2);
1152 return codePointCompare8To16(string1, string2);
1155 return -codePointCompare8To16(string2, string1);
1156 return codePointCompare16(string1, string2);
1159 inline bool isSpaceOrNewline(UChar c)
1161 // Use isASCIISpace() for basic Latin-1.
1162 // This will include newlines, which aren't included in Unicode DirWS.
1163 return c <= 0x7F ? isASCIISpace(c) : u_charDirection(c) == U_WHITE_SPACE_NEUTRAL;
1166 template<typename CharacterType>
1167 inline unsigned lengthOfNullTerminatedString(const CharacterType* string)
1171 while (string[length])
1174 RELEASE_ASSERT(length < std::numeric_limits<unsigned>::max());
1175 return static_cast<unsigned>(length);
1178 inline Ref<StringImpl> StringImpl::isolatedCopy() const
1180 if (!requiresCopy()) {
1182 return StringImpl::createWithoutCopying(m_data8, m_length);
1183 return StringImpl::createWithoutCopying(m_data16, m_length);
1187 return create(m_data8, m_length);
1188 return create(m_data16, m_length);
1193 // StringHash is the default hash for StringImpl* and RefPtr<StringImpl>
1194 template<typename T> struct DefaultHash;
1195 template<> struct DefaultHash<StringImpl*> {
1196 typedef StringHash Hash;
1198 template<> struct DefaultHash<RefPtr<StringImpl>> {
1199 typedef StringHash Hash;
1204 using WTF::StringImpl;
1206 using WTF::equalIgnoringASCIICase;
1207 using WTF::TextCaseSensitivity;
1208 using WTF::TextCaseSensitive;
1209 using WTF::TextCaseInsensitive;