Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / wtf / text / StringImpl.h
1 /*
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.
5  *
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.
10  *
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.
15  *
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.
20  *
21  */
22
23 #ifndef StringImpl_h
24 #define StringImpl_h
25
26 #include <limits.h>
27 #include "wtf/ASCIICType.h"
28 #include "wtf/Forward.h"
29 #include "wtf/HashMap.h"
30 #include "wtf/StringHasher.h"
31 #include "wtf/Vector.h"
32 #include "wtf/WTFExport.h"
33 #include "wtf/unicode/Unicode.h"
34
35 #if USE(CF)
36 typedef const struct __CFString * CFStringRef;
37 #endif
38
39 #ifdef __OBJC__
40 @class NSString;
41 #endif
42
43 namespace WTF {
44
45 struct AlreadyHashed;
46 struct CStringTranslator;
47 template<typename CharacterType> struct HashAndCharactersTranslator;
48 struct HashAndUTF8CharactersTranslator;
49 struct LCharBufferTranslator;
50 struct CharBufferFromLiteralDataTranslator;
51 struct SubstringTranslator;
52 struct UCharBufferTranslator;
53 template<typename> class RetainPtr;
54
55 enum TextCaseSensitivity { TextCaseSensitive, TextCaseInsensitive };
56
57 enum StripBehavior { StripExtraWhiteSpace, DoNotStripWhiteSpace };
58
59 typedef bool (*CharacterMatchFunctionPtr)(UChar);
60 typedef bool (*IsWhiteSpaceFunctionPtr)(UChar);
61 typedef HashMap<unsigned, StringImpl*, AlreadyHashed> StaticStringsTable;
62
63 // Define STRING_STATS to turn on run time statistics of string sizes and memory usage
64 #undef STRING_STATS
65
66 #ifdef STRING_STATS
67 struct StringStats {
68     inline void add8BitString(unsigned length)
69     {
70         ++m_totalNumberStrings;
71         ++m_number8BitStrings;
72         m_total8BitData += length;
73     }
74
75     inline void add16BitString(unsigned length)
76     {
77         ++m_totalNumberStrings;
78         ++m_number16BitStrings;
79         m_total16BitData += length;
80     }
81
82     void removeString(StringImpl*);
83     void printStats();
84
85     static const unsigned s_printStringStatsFrequency = 5000;
86     static unsigned s_stringRemovesTillPrintStats;
87
88     unsigned m_totalNumberStrings;
89     unsigned m_number8BitStrings;
90     unsigned m_number16BitStrings;
91     unsigned long long m_total8BitData;
92     unsigned long long m_total16BitData;
93 };
94
95 void addStringForStats(StringImpl*);
96 void removeStringForStats(StringImpl*);
97
98 #define STRING_STATS_ADD_8BIT_STRING(length) StringImpl::stringStats().add8BitString(length); addStringForStats(this)
99 #define STRING_STATS_ADD_16BIT_STRING(length) StringImpl::stringStats().add16BitString(length); addStringForStats(this)
100 #define STRING_STATS_REMOVE_STRING(string) StringImpl::stringStats().removeString(string); removeStringForStats(this)
101 #else
102 #define STRING_STATS_ADD_8BIT_STRING(length) ((void)0)
103 #define STRING_STATS_ADD_16BIT_STRING(length) ((void)0)
104 #define STRING_STATS_REMOVE_STRING(string) ((void)0)
105 #endif
106
107 // You can find documentation about this class in this doc:
108 // https://docs.google.com/document/d/1kOCUlJdh2WJMJGDf-WoEQhmnjKLaOYRbiHz5TiGJl14/edit?usp=sharing
109 class WTF_EXPORT StringImpl {
110     WTF_MAKE_NONCOPYABLE(StringImpl);
111     friend struct WTF::CStringTranslator;
112     template<typename CharacterType> friend struct WTF::HashAndCharactersTranslator;
113     friend struct WTF::HashAndUTF8CharactersTranslator;
114     friend struct WTF::CharBufferFromLiteralDataTranslator;
115     friend struct WTF::LCharBufferTranslator;
116     friend struct WTF::SubstringTranslator;
117     friend struct WTF::UCharBufferTranslator;
118
119 private:
120     // StringImpls are allocated out of the WTF buffer partition.
121     void* operator new(size_t);
122     void* operator new(size_t, void* ptr) { return ptr; };
123     void operator delete(void*);
124
125     // Used to construct static strings, which have an special refCount that can never hit zero.
126     // This means that the static string will never be destroyed, which is important because
127     // static strings will be shared across threads & ref-counted in a non-threadsafe manner.
128     enum ConstructEmptyStringTag { ConstructEmptyString };
129     explicit StringImpl(ConstructEmptyStringTag)
130         : m_refCount(1)
131         , m_length(0)
132         , m_hash(0)
133         , m_isAtomic(false)
134         , m_is8Bit(true)
135         , m_isStatic(true)
136     {
137         // Ensure that the hash is computed so that AtomicStringHash can call existingHash()
138         // with impunity. The empty string is special because it is never entered into
139         // AtomicString's HashKey, but still needs to compare correctly.
140         STRING_STATS_ADD_8BIT_STRING(m_length);
141         hash();
142     }
143
144     // FIXME: there has to be a less hacky way to do this.
145     enum Force8Bit { Force8BitConstructor };
146     StringImpl(unsigned length, Force8Bit)
147         : m_refCount(1)
148         , m_length(length)
149         , m_hash(0)
150         , m_isAtomic(false)
151         , m_is8Bit(true)
152         , m_isStatic(false)
153     {
154         ASSERT(m_length);
155         STRING_STATS_ADD_8BIT_STRING(m_length);
156     }
157
158     StringImpl(unsigned length)
159         : m_refCount(1)
160         , m_length(length)
161         , m_hash(0)
162         , m_isAtomic(false)
163         , m_is8Bit(false)
164         , m_isStatic(false)
165     {
166         ASSERT(m_length);
167         STRING_STATS_ADD_16BIT_STRING(m_length);
168     }
169
170     enum StaticStringTag { StaticString };
171     StringImpl(unsigned length, unsigned hash, StaticStringTag)
172         : m_refCount(1)
173         , m_length(length)
174         , m_hash(hash)
175         , m_isAtomic(false)
176         , m_is8Bit(true)
177         , m_isStatic(true)
178     {
179     }
180
181 public:
182     ~StringImpl();
183
184     static StringImpl* createStatic(const char* string, unsigned length, unsigned hash);
185     static void freezeStaticStrings();
186     static const StaticStringsTable& allStaticStrings();
187     static unsigned highestStaticStringLength() { return m_highestStaticStringLength; }
188
189     static PassRefPtr<StringImpl> create(const UChar*, unsigned length);
190     static PassRefPtr<StringImpl> create(const LChar*, unsigned length);
191     static PassRefPtr<StringImpl> create8BitIfPossible(const UChar*, unsigned length);
192     template<size_t inlineCapacity>
193     static PassRefPtr<StringImpl> create8BitIfPossible(const Vector<UChar, inlineCapacity>& vector)
194     {
195         return create8BitIfPossible(vector.data(), vector.size());
196     }
197
198     ALWAYS_INLINE static PassRefPtr<StringImpl> create(const char* s, unsigned length) { return create(reinterpret_cast<const LChar*>(s), length); }
199     static PassRefPtr<StringImpl> create(const LChar*);
200     ALWAYS_INLINE static PassRefPtr<StringImpl> create(const char* s) { return create(reinterpret_cast<const LChar*>(s)); }
201
202     static PassRefPtr<StringImpl> createUninitialized(unsigned length, LChar*& data);
203     static PassRefPtr<StringImpl> createUninitialized(unsigned length, UChar*& data);
204
205     // Reallocate the StringImpl. The originalString must be only owned by the PassRefPtr.
206     // Just like the input pointer of realloc(), the originalString can't be used after this function.
207     static PassRefPtr<StringImpl> reallocate(PassRefPtr<StringImpl> originalString, unsigned length);
208
209     // If this StringImpl has only one reference, we can truncate the string by updating
210     // its m_length property without actually re-allocating its buffer.
211     void truncateAssumingIsolated(unsigned length)
212     {
213         ASSERT(hasOneRef());
214         ASSERT(length <= m_length);
215         m_length = length;
216     }
217
218     unsigned length() const { return m_length; }
219     bool is8Bit() const { return m_is8Bit; }
220
221     ALWAYS_INLINE const LChar* characters8() const { ASSERT(is8Bit()); return reinterpret_cast<const LChar*>(this + 1); }
222     ALWAYS_INLINE const UChar* characters16() const { ASSERT(!is8Bit()); return reinterpret_cast<const UChar*>(this + 1); }
223
224     template <typename CharType>
225     ALWAYS_INLINE const CharType * getCharacters() const;
226
227     size_t sizeInBytes() const;
228
229     bool isAtomic() const { return m_isAtomic; }
230     void setIsAtomic(bool isAtomic) { m_isAtomic = isAtomic; }
231
232     bool isStatic() const { return m_isStatic; }
233
234 private:
235     // The high bits of 'hash' are always empty, but we prefer to store our flags
236     // in the low bits because it makes them slightly more efficient to access.
237     // So, we shift left and right when setting and getting our hash code.
238     void setHash(unsigned hash) const
239     {
240         ASSERT(!hasHash());
241         // Multiple clients assume that StringHasher is the canonical string hash function.
242         ASSERT(hash == (is8Bit() ? StringHasher::computeHashAndMaskTop8Bits(characters8(), m_length) : StringHasher::computeHashAndMaskTop8Bits(characters16(), m_length)));
243         m_hash = hash;
244         ASSERT(hash); // Verify that 0 is a valid sentinel hash value.
245     }
246
247     unsigned rawHash() const
248     {
249         return m_hash;
250     }
251
252     void destroyIfNotStatic();
253
254 public:
255     bool hasHash() const
256     {
257         return rawHash() != 0;
258     }
259
260     unsigned existingHash() const
261     {
262         ASSERT(hasHash());
263         return rawHash();
264     }
265
266     unsigned hash() const
267     {
268         if (hasHash())
269             return existingHash();
270         return hashSlowCase();
271     }
272
273     inline bool hasOneRef() const
274     {
275         return m_refCount == 1;
276     }
277
278     inline void ref()
279     {
280         ++m_refCount;
281     }
282
283     inline void deref()
284     {
285         if (hasOneRef()) {
286             destroyIfNotStatic();
287             return;
288         }
289
290         --m_refCount;
291     }
292
293     static StringImpl* empty();
294
295     // FIXME: Does this really belong in StringImpl?
296     template <typename T> static void copyChars(T* destination, const T* source, unsigned numCharacters)
297     {
298         if (numCharacters == 1) {
299             *destination = *source;
300             return;
301         }
302
303         // FIXME: Is this implementation really faster than memcpy?
304         if (numCharacters <= s_copyCharsInlineCutOff) {
305             unsigned i = 0;
306 #if (CPU(X86) || CPU(X86_64))
307             const unsigned charsPerInt = sizeof(uint32_t) / sizeof(T);
308
309             if (numCharacters > charsPerInt) {
310                 unsigned stopCount = numCharacters & ~(charsPerInt - 1);
311
312                 const uint32_t* srcCharacters = reinterpret_cast<const uint32_t*>(source);
313                 uint32_t* destCharacters = reinterpret_cast<uint32_t*>(destination);
314                 for (unsigned j = 0; i < stopCount; i += charsPerInt, ++j)
315                     destCharacters[j] = srcCharacters[j];
316             }
317 #endif
318             for (; i < numCharacters; ++i)
319                 destination[i] = source[i];
320         } else
321             memcpy(destination, source, numCharacters * sizeof(T));
322     }
323
324     ALWAYS_INLINE static void copyChars(UChar* destination, const LChar* source, unsigned numCharacters)
325     {
326         for (unsigned i = 0; i < numCharacters; ++i)
327             destination[i] = source[i];
328     }
329
330     // Some string features, like refcounting and the atomicity flag, are not
331     // thread-safe. We achieve thread safety by isolation, giving each thread
332     // its own copy of the string.
333     PassRefPtr<StringImpl> isolatedCopy() const;
334
335     PassRefPtr<StringImpl> substring(unsigned pos, unsigned len = UINT_MAX);
336
337     UChar operator[](unsigned i) const
338     {
339         ASSERT_WITH_SECURITY_IMPLICATION(i < m_length);
340         if (is8Bit())
341             return characters8()[i];
342         return characters16()[i];
343     }
344     UChar32 characterStartingAt(unsigned);
345
346     bool containsOnlyWhitespace();
347
348     int toIntStrict(bool* ok = 0, int base = 10);
349     unsigned toUIntStrict(bool* ok = 0, int base = 10);
350     int64_t toInt64Strict(bool* ok = 0, int base = 10);
351     uint64_t toUInt64Strict(bool* ok = 0, int base = 10);
352     intptr_t toIntPtrStrict(bool* ok = 0, int base = 10);
353
354     int toInt(bool* ok = 0); // ignores trailing garbage
355     unsigned toUInt(bool* ok = 0); // ignores trailing garbage
356     int64_t toInt64(bool* ok = 0); // ignores trailing garbage
357     uint64_t toUInt64(bool* ok = 0); // ignores trailing garbage
358     intptr_t toIntPtr(bool* ok = 0); // ignores trailing garbage
359
360     // FIXME: Like the strict functions above, these give false for "ok" when there is trailing garbage.
361     // Like the non-strict functions above, these return the value when there is trailing garbage.
362     // It would be better if these were more consistent with the above functions instead.
363     double toDouble(bool* ok = 0);
364     float toFloat(bool* ok = 0);
365
366     PassRefPtr<StringImpl> lower();
367     PassRefPtr<StringImpl> upper();
368     PassRefPtr<StringImpl> lower(const AtomicString& localeIdentifier);
369     PassRefPtr<StringImpl> upper(const AtomicString& localeIdentifier);
370
371     PassRefPtr<StringImpl> fill(UChar);
372     // FIXME: Do we need fill(char) or can we just do the right thing if UChar is ASCII?
373     PassRefPtr<StringImpl> foldCase();
374
375     PassRefPtr<StringImpl> stripWhiteSpace();
376     PassRefPtr<StringImpl> stripWhiteSpace(IsWhiteSpaceFunctionPtr);
377     PassRefPtr<StringImpl> simplifyWhiteSpace(StripBehavior stripBehavior = StripExtraWhiteSpace);
378     PassRefPtr<StringImpl> simplifyWhiteSpace(IsWhiteSpaceFunctionPtr, StripBehavior stripBehavior = StripExtraWhiteSpace);
379
380     PassRefPtr<StringImpl> removeCharacters(CharacterMatchFunctionPtr);
381     template <typename CharType>
382     ALWAYS_INLINE PassRefPtr<StringImpl> removeCharacters(const CharType* characters, CharacterMatchFunctionPtr);
383
384     size_t find(LChar character, unsigned start = 0);
385     size_t find(char character, unsigned start = 0);
386     size_t find(UChar character, unsigned start = 0);
387     size_t find(CharacterMatchFunctionPtr, unsigned index = 0);
388     size_t find(const LChar*, unsigned index = 0);
389     ALWAYS_INLINE size_t find(const char* s, unsigned index = 0) { return find(reinterpret_cast<const LChar*>(s), index); }
390     size_t find(StringImpl*);
391     size_t find(StringImpl*, unsigned index);
392     size_t findIgnoringCase(const LChar*, unsigned index = 0);
393     ALWAYS_INLINE size_t findIgnoringCase(const char* s, unsigned index = 0) { return findIgnoringCase(reinterpret_cast<const LChar*>(s), index); }
394     size_t findIgnoringCase(StringImpl*, unsigned index = 0);
395
396     size_t findNextLineStart(unsigned index = UINT_MAX);
397
398     size_t reverseFind(UChar, unsigned index = UINT_MAX);
399     size_t reverseFind(StringImpl*, unsigned index = UINT_MAX);
400     size_t reverseFindIgnoringCase(StringImpl*, unsigned index = UINT_MAX);
401
402     size_t count(LChar) const;
403
404     bool startsWith(StringImpl* str, bool caseSensitive = true) { return (caseSensitive ? reverseFind(str, 0) : reverseFindIgnoringCase(str, 0)) == 0; }
405     bool startsWith(UChar) const;
406     bool startsWith(const char*, unsigned matchLength, bool caseSensitive) const;
407     template<unsigned matchLength>
408     bool startsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return startsWith(prefix, matchLength - 1, caseSensitive); }
409
410     bool endsWith(StringImpl*, bool caseSensitive = true);
411     bool endsWith(UChar) const;
412     bool endsWith(const char*, unsigned matchLength, bool caseSensitive) const;
413     template<unsigned matchLength>
414     bool endsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const { return endsWith(prefix, matchLength - 1, caseSensitive); }
415
416     PassRefPtr<StringImpl> replace(UChar, UChar);
417     PassRefPtr<StringImpl> replace(UChar, StringImpl*);
418     ALWAYS_INLINE PassRefPtr<StringImpl> replace(UChar pattern, const char* replacement, unsigned replacementLength) { return replace(pattern, reinterpret_cast<const LChar*>(replacement), replacementLength); }
419     PassRefPtr<StringImpl> replace(UChar, const LChar*, unsigned replacementLength);
420     PassRefPtr<StringImpl> replace(UChar, const UChar*, unsigned replacementLength);
421     PassRefPtr<StringImpl> replace(StringImpl*, StringImpl*);
422     PassRefPtr<StringImpl> replace(unsigned index, unsigned len, StringImpl*);
423     PassRefPtr<StringImpl> upconvertedString();
424
425 #if USE(CF)
426     RetainPtr<CFStringRef> createCFString();
427 #endif
428 #ifdef __OBJC__
429     operator NSString*();
430 #endif
431
432 #ifdef STRING_STATS
433     ALWAYS_INLINE static StringStats& stringStats() { return m_stringStats; }
434 #endif
435
436 private:
437     template<typename CharType> static size_t allocationSize(unsigned length)
438     {
439         RELEASE_ASSERT(length <= ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(CharType)));
440         return sizeof(StringImpl) + length * sizeof(CharType);
441     }
442
443     // This number must be at least 2 to avoid sharing empty, null as well as 1 character strings from SmallStrings.
444     static const unsigned s_copyCharsInlineCutOff = 20;
445
446     template <class UCharPredicate> PassRefPtr<StringImpl> stripMatchedCharacters(UCharPredicate);
447     template <typename CharType, class UCharPredicate> PassRefPtr<StringImpl> simplifyMatchedCharactersToSpace(UCharPredicate, StripBehavior);
448     NEVER_INLINE unsigned hashSlowCase() const;
449
450 #ifdef STRING_STATS
451     static StringStats m_stringStats;
452 #endif
453
454     static unsigned m_highestStaticStringLength;
455
456 #ifndef NDEBUG
457     void assertHashIsCorrect()
458     {
459         ASSERT(hasHash());
460         ASSERT(existingHash() == StringHasher::computeHashAndMaskTop8Bits(characters8(), length()));
461     }
462 #endif
463
464 private:
465     unsigned m_refCount;
466     unsigned m_length;
467     mutable unsigned m_hash : 24;
468     unsigned m_isAtomic : 1;
469     unsigned m_is8Bit : 1;
470     unsigned m_isStatic : 1;
471 };
472
473 template <>
474 ALWAYS_INLINE const LChar* StringImpl::getCharacters<LChar>() const { return characters8(); }
475
476 template <>
477 ALWAYS_INLINE const UChar* StringImpl::getCharacters<UChar>() const { return characters16(); }
478
479 WTF_EXPORT bool equal(const StringImpl*, const StringImpl*);
480 WTF_EXPORT bool equal(const StringImpl*, const LChar*);
481 inline bool equal(const StringImpl* a, const char* b) { return equal(a, reinterpret_cast<const LChar*>(b)); }
482 WTF_EXPORT bool equal(const StringImpl*, const LChar*, unsigned);
483 WTF_EXPORT bool equal(const StringImpl*, const UChar*, unsigned);
484 inline bool equal(const StringImpl* a, const char* b, unsigned length) { return equal(a, reinterpret_cast<const LChar*>(b), length); }
485 inline bool equal(const LChar* a, StringImpl* b) { return equal(b, a); }
486 inline bool equal(const char* a, StringImpl* b) { return equal(b, reinterpret_cast<const LChar*>(a)); }
487 WTF_EXPORT bool equalNonNull(const StringImpl* a, const StringImpl* b);
488
489 template<typename CharType>
490 ALWAYS_INLINE bool equal(const CharType* a, const CharType* b, unsigned length) { return !memcmp(a, b, length * sizeof(CharType)); }
491
492 ALWAYS_INLINE bool equal(const LChar* a, const UChar* b, unsigned length)
493 {
494     for (unsigned i = 0; i < length; ++i) {
495         if (a[i] != b[i])
496             return false;
497     }
498     return true;
499 }
500
501 ALWAYS_INLINE bool equal(const UChar* a, const LChar* b, unsigned length) { return equal(b, a, length); }
502
503 WTF_EXPORT bool equalIgnoringCase(const StringImpl*, const StringImpl*);
504 WTF_EXPORT bool equalIgnoringCase(const StringImpl*, const LChar*);
505 inline bool equalIgnoringCase(const LChar* a, const StringImpl* b) { return equalIgnoringCase(b, a); }
506 WTF_EXPORT bool equalIgnoringCase(const LChar*, const LChar*, unsigned);
507 WTF_EXPORT bool equalIgnoringCase(const UChar*, const LChar*, unsigned);
508 inline bool equalIgnoringCase(const UChar* a, const char* b, unsigned length) { return equalIgnoringCase(a, reinterpret_cast<const LChar*>(b), length); }
509 inline bool equalIgnoringCase(const LChar* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, a, length); }
510 inline bool equalIgnoringCase(const char* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
511 inline bool equalIgnoringCase(const char* a, const LChar* b, unsigned length) { return equalIgnoringCase(b, reinterpret_cast<const LChar*>(a), length); }
512 inline bool equalIgnoringCase(const UChar* a, const UChar* b, int length)
513 {
514     ASSERT(length >= 0);
515     return !Unicode::umemcasecmp(a, b, length);
516 }
517 WTF_EXPORT bool equalIgnoringCaseNonNull(const StringImpl*, const StringImpl*);
518
519 WTF_EXPORT bool equalIgnoringNullity(StringImpl*, StringImpl*);
520
521 template<typename CharacterType>
522 inline size_t find(const CharacterType* characters, unsigned length, CharacterType matchCharacter, unsigned index = 0)
523 {
524     while (index < length) {
525         if (characters[index] == matchCharacter)
526             return index;
527         ++index;
528     }
529     return kNotFound;
530 }
531
532 ALWAYS_INLINE size_t find(const UChar* characters, unsigned length, LChar matchCharacter, unsigned index = 0)
533 {
534     return find(characters, length, static_cast<UChar>(matchCharacter), index);
535 }
536
537 inline size_t find(const LChar* characters, unsigned length, UChar matchCharacter, unsigned index = 0)
538 {
539     if (matchCharacter & ~0xFF)
540         return kNotFound;
541     return find(characters, length, static_cast<LChar>(matchCharacter), index);
542 }
543
544 inline size_t find(const LChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
545 {
546     while (index < length) {
547         if (matchFunction(characters[index]))
548             return index;
549         ++index;
550     }
551     return kNotFound;
552 }
553
554 inline size_t find(const UChar* characters, unsigned length, CharacterMatchFunctionPtr matchFunction, unsigned index = 0)
555 {
556     while (index < length) {
557         if (matchFunction(characters[index]))
558             return index;
559         ++index;
560     }
561     return kNotFound;
562 }
563
564 template<typename CharacterType>
565 inline size_t findNextLineStart(const CharacterType* characters, unsigned length, unsigned index = 0)
566 {
567     while (index < length) {
568         CharacterType c = characters[index++];
569         if ((c != '\n') && (c != '\r'))
570             continue;
571
572         // There can only be a start of a new line if there are more characters
573         // beyond the current character.
574         if (index < length) {
575             // The 3 common types of line terminators are 1. \r\n (Windows),
576             // 2. \r (old MacOS) and 3. \n (Unix'es).
577
578             if (c == '\n')
579                 return index; // Case 3: just \n.
580
581             CharacterType c2 = characters[index];
582             if (c2 != '\n')
583                 return index; // Case 2: just \r.
584
585             // Case 1: \r\n.
586             // But, there's only a start of a new line if there are more
587             // characters beyond the \r\n.
588             if (++index < length)
589                 return index;
590         }
591     }
592     return kNotFound;
593 }
594
595 template<typename CharacterType>
596 inline size_t reverseFindLineTerminator(const CharacterType* characters, unsigned length, unsigned index = UINT_MAX)
597 {
598     if (!length)
599         return kNotFound;
600     if (index >= length)
601         index = length - 1;
602     CharacterType c = characters[index];
603     while ((c != '\n') && (c != '\r')) {
604         if (!index--)
605             return kNotFound;
606         c = characters[index];
607     }
608     return index;
609 }
610
611 template<typename CharacterType>
612 inline size_t reverseFind(const CharacterType* characters, unsigned length, CharacterType matchCharacter, unsigned index = UINT_MAX)
613 {
614     if (!length)
615         return kNotFound;
616     if (index >= length)
617         index = length - 1;
618     while (characters[index] != matchCharacter) {
619         if (!index--)
620             return kNotFound;
621     }
622     return index;
623 }
624
625 ALWAYS_INLINE size_t reverseFind(const UChar* characters, unsigned length, LChar matchCharacter, unsigned index = UINT_MAX)
626 {
627     return reverseFind(characters, length, static_cast<UChar>(matchCharacter), index);
628 }
629
630 inline size_t reverseFind(const LChar* characters, unsigned length, UChar matchCharacter, unsigned index = UINT_MAX)
631 {
632     if (matchCharacter & ~0xFF)
633         return kNotFound;
634     return reverseFind(characters, length, static_cast<LChar>(matchCharacter), index);
635 }
636
637 inline size_t StringImpl::find(LChar character, unsigned start)
638 {
639     if (is8Bit())
640         return WTF::find(characters8(), m_length, character, start);
641     return WTF::find(characters16(), m_length, character, start);
642 }
643
644 ALWAYS_INLINE size_t StringImpl::find(char character, unsigned start)
645 {
646     return find(static_cast<LChar>(character), start);
647 }
648
649 inline size_t StringImpl::find(UChar character, unsigned start)
650 {
651     if (is8Bit())
652         return WTF::find(characters8(), m_length, character, start);
653     return WTF::find(characters16(), m_length, character, start);
654 }
655
656 inline unsigned lengthOfNullTerminatedString(const UChar* string)
657 {
658     size_t length = 0;
659     while (string[length] != UChar(0))
660         ++length;
661     RELEASE_ASSERT(length <= std::numeric_limits<unsigned>::max());
662     return static_cast<unsigned>(length);
663 }
664
665 template<size_t inlineCapacity>
666 bool equalIgnoringNullity(const Vector<UChar, inlineCapacity>& a, StringImpl* b)
667 {
668     if (!b)
669         return !a.size();
670     if (a.size() != b->length())
671         return false;
672     if (b->is8Bit())
673         return equal(a.data(), b->characters8(), b->length());
674     return equal(a.data(), b->characters16(), b->length());
675 }
676
677 template<typename CharacterType1, typename CharacterType2>
678 static inline int codePointCompare(unsigned l1, unsigned l2, const CharacterType1* c1, const CharacterType2* c2)
679 {
680     const unsigned lmin = l1 < l2 ? l1 : l2;
681     unsigned pos = 0;
682     while (pos < lmin && *c1 == *c2) {
683         ++c1;
684         ++c2;
685         ++pos;
686     }
687
688     if (pos < lmin)
689         return (c1[0] > c2[0]) ? 1 : -1;
690
691     if (l1 == l2)
692         return 0;
693
694     return (l1 > l2) ? 1 : -1;
695 }
696
697 static inline int codePointCompare8(const StringImpl* string1, const StringImpl* string2)
698 {
699     return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters8());
700 }
701
702 static inline int codePointCompare16(const StringImpl* string1, const StringImpl* string2)
703 {
704     return codePointCompare(string1->length(), string2->length(), string1->characters16(), string2->characters16());
705 }
706
707 static inline int codePointCompare8To16(const StringImpl* string1, const StringImpl* string2)
708 {
709     return codePointCompare(string1->length(), string2->length(), string1->characters8(), string2->characters16());
710 }
711
712 static inline int codePointCompare(const StringImpl* string1, const StringImpl* string2)
713 {
714     if (!string1)
715         return (string2 && string2->length()) ? -1 : 0;
716
717     if (!string2)
718         return string1->length() ? 1 : 0;
719
720     bool string1Is8Bit = string1->is8Bit();
721     bool string2Is8Bit = string2->is8Bit();
722     if (string1Is8Bit) {
723         if (string2Is8Bit)
724             return codePointCompare8(string1, string2);
725         return codePointCompare8To16(string1, string2);
726     }
727     if (string2Is8Bit)
728         return -codePointCompare8To16(string2, string1);
729     return codePointCompare16(string1, string2);
730 }
731
732 static inline bool isSpaceOrNewline(UChar c)
733 {
734     // Use isASCIISpace() for basic Latin-1.
735     // This will include newlines, which aren't included in Unicode DirWS.
736     return c <= 0x7F ? WTF::isASCIISpace(c) : WTF::Unicode::direction(c) == WTF::Unicode::WhiteSpaceNeutral;
737 }
738
739 inline PassRefPtr<StringImpl> StringImpl::isolatedCopy() const
740 {
741     if (is8Bit())
742         return create(characters8(), m_length);
743     return create(characters16(), m_length);
744 }
745
746 struct StringHash;
747
748 // StringHash is the default hash for StringImpl* and RefPtr<StringImpl>
749 template<typename T> struct DefaultHash;
750 template<> struct DefaultHash<StringImpl*> {
751     typedef StringHash Hash;
752 };
753 template<> struct DefaultHash<RefPtr<StringImpl> > {
754     typedef StringHash Hash;
755 };
756
757 }
758
759 using WTF::StringImpl;
760 using WTF::equal;
761 using WTF::equalNonNull;
762 using WTF::TextCaseSensitivity;
763 using WTF::TextCaseSensitive;
764 using WTF::TextCaseInsensitive;
765
766 #endif