initial import
[vuplus_webkit] / Source / JavaScriptCore / wtf / text / StringImpl.h
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 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/CrossThreadRefCounted.h>
29 #include <wtf/Forward.h>
30 #include <wtf/OwnFastMallocPtr.h>
31 #include <wtf/StdLibExtras.h>
32 #include <wtf/StringHasher.h>
33 #include <wtf/Vector.h>
34 #include <wtf/text/StringImplBase.h>
35 #include <wtf/unicode/Unicode.h>
36
37 #if USE(CF)
38 typedef const struct __CFString * CFStringRef;
39 #endif
40
41 #ifdef __OBJC__
42 @class NSString;
43 #endif
44
45 // FIXME: This is a temporary layering violation while we move string code to WTF.
46 // Landing the file moves in one patch, will follow on with patches to change the namespaces.
47 namespace JSC {
48 struct IdentifierCStringTranslator;
49 struct IdentifierUCharBufferTranslator;
50 }
51
52 namespace WTF {
53
54 struct CStringTranslator;
55 struct HashAndCharactersTranslator;
56 struct HashAndUTF8CharactersTranslator;
57 struct UCharBufferTranslator;
58
59 enum TextCaseSensitivity { TextCaseSensitive, TextCaseInsensitive };
60
61 typedef OwnFastMallocPtr<const UChar> SharableUChar;
62 typedef CrossThreadRefCounted<SharableUChar> SharedUChar;
63 typedef bool (*CharacterMatchFunctionPtr)(UChar);
64 typedef bool (*IsWhiteSpaceFunctionPtr)(UChar);
65
66 class StringImpl : public StringImplBase {
67     friend struct JSC::IdentifierCStringTranslator;
68     friend struct JSC::IdentifierUCharBufferTranslator;
69     friend struct WTF::CStringTranslator;
70     friend struct WTF::HashAndCharactersTranslator;
71     friend struct WTF::HashAndUTF8CharactersTranslator;
72     friend struct WTF::UCharBufferTranslator;
73     friend class AtomicStringImpl;
74 private:
75     // Used to construct static strings, which have an special refCount that can never hit zero.
76     // This means that the static string will never be destroyed, which is important because
77     // static strings will be shared across threads & ref-counted in a non-threadsafe manner.
78     StringImpl(const UChar* characters, unsigned length, StaticStringConstructType)
79         : StringImplBase(length, ConstructStaticString)
80         , m_data(characters)
81         , m_buffer(0)
82         , m_hash(0)
83     {
84         // Ensure that the hash is computed so that AtomicStringHash can call existingHash()
85         // with impunity. The empty string is special because it is never entered into
86         // AtomicString's HashKey, but still needs to compare correctly.
87         hash();
88     }
89
90     // Create a normal string with internal storage (BufferInternal)
91     StringImpl(unsigned length)
92         : StringImplBase(length, BufferInternal)
93         , m_data(reinterpret_cast<const UChar*>(this + 1))
94         , m_buffer(0)
95         , m_hash(0)
96     {
97         ASSERT(m_data);
98         ASSERT(m_length);
99     }
100
101     // Create a StringImpl adopting ownership of the provided buffer (BufferOwned)
102     StringImpl(const UChar* characters, unsigned length)
103         : StringImplBase(length, BufferOwned)
104         , m_data(characters)
105         , m_buffer(0)
106         , m_hash(0)
107     {
108         ASSERT(m_data);
109         ASSERT(m_length);
110     }
111
112     // Used to create new strings that are a substring of an existing StringImpl (BufferSubstring)
113     StringImpl(const UChar* characters, unsigned length, PassRefPtr<StringImpl> base)
114         : StringImplBase(length, BufferSubstring)
115         , m_data(characters)
116         , m_substringBuffer(base.leakRef())
117         , m_hash(0)
118     {
119         ASSERT(m_data);
120         ASSERT(m_length);
121         ASSERT(m_substringBuffer->bufferOwnership() != BufferSubstring);
122     }
123
124     // Used to construct new strings sharing an existing SharedUChar (BufferShared)
125     StringImpl(const UChar* characters, unsigned length, PassRefPtr<SharedUChar> sharedBuffer)
126         : StringImplBase(length, BufferShared)
127         , m_data(characters)
128         , m_sharedBuffer(sharedBuffer.leakRef())
129         , m_hash(0)
130     {
131         ASSERT(m_data);
132         ASSERT(m_length);
133     }
134
135     // For use only by AtomicString's XXXTranslator helpers.
136     void setHash(unsigned hash)
137     {
138         ASSERT(!isStatic());
139         ASSERT(!m_hash);
140         ASSERT(hash == StringHasher::computeHash(m_data, m_length));
141         m_hash = hash;
142     }
143
144 public:
145     ~StringImpl();
146
147     static PassRefPtr<StringImpl> create(const UChar*, unsigned length);
148     static PassRefPtr<StringImpl> create(const char*, unsigned length);
149     static PassRefPtr<StringImpl> create(const char*);
150     static PassRefPtr<StringImpl> create(const UChar*, unsigned length, PassRefPtr<SharedUChar> sharedBuffer);
151     static ALWAYS_INLINE PassRefPtr<StringImpl> create(PassRefPtr<StringImpl> rep, unsigned offset, unsigned length)
152     {
153         ASSERT(rep);
154         ASSERT(length <= rep->length());
155
156         if (!length)
157             return empty();
158
159         StringImpl* ownerRep = (rep->bufferOwnership() == BufferSubstring) ? rep->m_substringBuffer : rep.get();
160         return adoptRef(new StringImpl(rep->m_data + offset, length, ownerRep));
161     }
162
163     static PassRefPtr<StringImpl> createUninitialized(unsigned length, UChar*& data);
164     static ALWAYS_INLINE PassRefPtr<StringImpl> tryCreateUninitialized(unsigned length, UChar*& output)
165     {
166         if (!length) {
167             output = 0;
168             return empty();
169         }
170
171         if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(UChar))) {
172             output = 0;
173             return 0;
174         }
175         StringImpl* resultImpl;
176         if (!tryFastMalloc(sizeof(UChar) * length + sizeof(StringImpl)).getValue(resultImpl)) {
177             output = 0;
178             return 0;
179         }
180         output = reinterpret_cast<UChar*>(resultImpl + 1);
181         return adoptRef(new(resultImpl) StringImpl(length));
182     }
183
184     static unsigned dataOffset() { return OBJECT_OFFSETOF(StringImpl, m_data); }
185     static PassRefPtr<StringImpl> createWithTerminatingNullCharacter(const StringImpl&);
186     static PassRefPtr<StringImpl> createStrippingNullCharacters(const UChar*, unsigned length);
187
188     template<size_t inlineCapacity>
189     static PassRefPtr<StringImpl> adopt(Vector<UChar, inlineCapacity>& vector)
190     {
191         if (size_t size = vector.size()) {
192             ASSERT(vector.data());
193             if (size > std::numeric_limits<unsigned>::max())
194                 CRASH();
195             return adoptRef(new StringImpl(vector.releaseBuffer(), size));
196         }
197         return empty();
198     }
199     static PassRefPtr<StringImpl> adopt(StringBuffer&);
200
201     SharedUChar* sharedBuffer();
202     const UChar* characters() const { return m_data; }
203
204     size_t cost()
205     {
206         // For substrings, return the cost of the base string.
207         if (bufferOwnership() == BufferSubstring)
208             return m_substringBuffer->cost();
209
210         if (m_refCountAndFlags & s_refCountFlagShouldReportedCost) {
211             m_refCountAndFlags &= ~s_refCountFlagShouldReportedCost;
212             return m_length;
213         }
214         return 0;
215     }
216
217     bool isIdentifier() const { return m_refCountAndFlags & s_refCountFlagIsIdentifier; }
218     void setIsIdentifier(bool isIdentifier)
219     {
220         ASSERT(!isStatic());
221         if (isIdentifier)
222             m_refCountAndFlags |= s_refCountFlagIsIdentifier;
223         else
224             m_refCountAndFlags &= ~s_refCountFlagIsIdentifier;
225     }
226
227     bool hasTerminatingNullCharacter() const { return m_refCountAndFlags & s_refCountFlagHasTerminatingNullCharacter; }
228
229     bool isAtomic() const { return m_refCountAndFlags & s_refCountFlagIsAtomic; }
230     void setIsAtomic(bool isIdentifier)
231     {
232         ASSERT(!isStatic());
233         if (isIdentifier)
234             m_refCountAndFlags |= s_refCountFlagIsAtomic;
235         else
236             m_refCountAndFlags &= ~s_refCountFlagIsAtomic;
237     }
238
239     unsigned hash() const { if (!m_hash) m_hash = StringHasher::computeHash(m_data, m_length); return m_hash; }
240     unsigned existingHash() const { ASSERT(m_hash); return m_hash; }
241     bool hasHash() const { return m_hash; }
242
243     ALWAYS_INLINE void deref() { m_refCountAndFlags -= s_refCountIncrement; if (!(m_refCountAndFlags & (s_refCountMask | s_refCountFlagStatic))) delete this; }
244     ALWAYS_INLINE bool hasOneRef() const { return (m_refCountAndFlags & (s_refCountMask | s_refCountFlagStatic)) == s_refCountIncrement; }
245
246     static StringImpl* empty();
247
248     static void copyChars(UChar* destination, const UChar* source, unsigned numCharacters)
249     {
250         if (numCharacters <= s_copyCharsInlineCutOff) {
251             for (unsigned i = 0; i < numCharacters; ++i)
252                 destination[i] = source[i];
253         } else
254             memcpy(destination, source, numCharacters * sizeof(UChar));
255     }
256
257     // Returns a StringImpl suitable for use on another thread.
258     PassRefPtr<StringImpl> crossThreadString();
259     // Makes a deep copy. Helpful only if you need to use a String on another thread
260     // (use crossThreadString if the method call doesn't need to be threadsafe).
261     // Since StringImpl objects are immutable, there's no other reason to make a copy.
262     PassRefPtr<StringImpl> threadsafeCopy() const;
263
264     PassRefPtr<StringImpl> substring(unsigned pos, unsigned len = UINT_MAX);
265
266     UChar operator[](unsigned i) { ASSERT(i < m_length); return m_data[i]; }
267     UChar32 characterStartingAt(unsigned);
268
269     bool containsOnlyWhitespace();
270
271     int toIntStrict(bool* ok = 0, int base = 10);
272     unsigned toUIntStrict(bool* ok = 0, int base = 10);
273     int64_t toInt64Strict(bool* ok = 0, int base = 10);
274     uint64_t toUInt64Strict(bool* ok = 0, int base = 10);
275     intptr_t toIntPtrStrict(bool* ok = 0, int base = 10);
276
277     int toInt(bool* ok = 0); // ignores trailing garbage
278     unsigned toUInt(bool* ok = 0); // ignores trailing garbage
279     int64_t toInt64(bool* ok = 0); // ignores trailing garbage
280     uint64_t toUInt64(bool* ok = 0); // ignores trailing garbage
281     intptr_t toIntPtr(bool* ok = 0); // ignores trailing garbage
282
283     double toDouble(bool* ok = 0, bool* didReadNumber = 0);
284     float toFloat(bool* ok = 0, bool* didReadNumber = 0);
285
286     PassRefPtr<StringImpl> lower();
287     PassRefPtr<StringImpl> upper();
288
289     PassRefPtr<StringImpl> fill(UChar);
290     PassRefPtr<StringImpl> foldCase();
291
292     PassRefPtr<StringImpl> stripWhiteSpace();
293     PassRefPtr<StringImpl> stripWhiteSpace(IsWhiteSpaceFunctionPtr);
294     PassRefPtr<StringImpl> simplifyWhiteSpace();
295     PassRefPtr<StringImpl> simplifyWhiteSpace(IsWhiteSpaceFunctionPtr);
296
297     PassRefPtr<StringImpl> removeCharacters(CharacterMatchFunctionPtr);
298
299     size_t find(UChar, unsigned index = 0);
300     size_t find(CharacterMatchFunctionPtr, unsigned index = 0);
301     size_t find(const char*, unsigned index = 0);
302     size_t find(StringImpl*, unsigned index = 0);
303     size_t findIgnoringCase(const char*, unsigned index = 0);
304     size_t findIgnoringCase(StringImpl*, unsigned index = 0);
305
306     size_t reverseFind(UChar, unsigned index = UINT_MAX);
307     size_t reverseFind(StringImpl*, unsigned index = UINT_MAX);
308     size_t reverseFindIgnoringCase(StringImpl*, unsigned index = UINT_MAX);
309
310     bool startsWith(StringImpl* str, bool caseSensitive = true) { return (caseSensitive ? reverseFind(str, 0) : reverseFindIgnoringCase(str, 0)) == 0; }
311     bool endsWith(StringImpl*, bool caseSensitive = true);
312
313     PassRefPtr<StringImpl> replace(UChar, UChar);
314     PassRefPtr<StringImpl> replace(UChar, StringImpl*);
315     PassRefPtr<StringImpl> replace(StringImpl*, StringImpl*);
316     PassRefPtr<StringImpl> replace(unsigned index, unsigned len, StringImpl*);
317
318     WTF::Unicode::Direction defaultWritingDirection(bool* hasStrongDirectionality = 0);
319
320 #if USE(CF)
321     CFStringRef createCFString();
322 #endif
323 #ifdef __OBJC__
324     operator NSString*();
325 #endif
326
327 private:
328     // This number must be at least 2 to avoid sharing empty, null as well as 1 character strings from SmallStrings.
329     static const unsigned s_copyCharsInlineCutOff = 20;
330
331     static PassRefPtr<StringImpl> createStrippingNullCharactersSlowCase(const UChar*, unsigned length);
332     
333     BufferOwnership bufferOwnership() const { return static_cast<BufferOwnership>(m_refCountAndFlags & s_refCountMaskBufferOwnership); }
334     bool isStatic() const { return m_refCountAndFlags & s_refCountFlagStatic; }
335     template <class UCharPredicate> PassRefPtr<StringImpl> stripMatchedCharacters(UCharPredicate);
336     template <class UCharPredicate> PassRefPtr<StringImpl> simplifyMatchedCharactersToSpace(UCharPredicate);
337
338     const UChar* m_data;
339     union {
340         void* m_buffer;
341         StringImpl* m_substringBuffer;
342         SharedUChar* m_sharedBuffer;
343     };
344     mutable unsigned m_hash;
345 };
346
347 bool equal(const StringImpl*, const StringImpl*);
348 bool equal(const StringImpl*, const char*);
349 inline bool equal(const char* a, StringImpl* b) { return equal(b, a); }
350 bool equal(const StringImpl*, const UChar*, unsigned);
351
352 bool equalIgnoringCase(StringImpl*, StringImpl*);
353 bool equalIgnoringCase(StringImpl*, const char*);
354 inline bool equalIgnoringCase(const char* a, StringImpl* b) { return equalIgnoringCase(b, a); }
355 bool equalIgnoringCase(const UChar* a, const char* b, unsigned length);
356 inline bool equalIgnoringCase(const char* a, const UChar* b, unsigned length) { return equalIgnoringCase(b, a, length); }
357
358 bool equalIgnoringNullity(StringImpl*, StringImpl*);
359
360 template<size_t inlineCapacity>
361 bool equalIgnoringNullity(const Vector<UChar, inlineCapacity>& a, StringImpl* b)
362 {
363     if (!b)
364         return !a.size();
365     if (a.size() != b->length())
366         return false;
367     return !memcmp(a.data(), b->characters(), b->length());
368 }
369
370 int codePointCompare(const StringImpl*, const StringImpl*);
371
372 static inline bool isSpaceOrNewline(UChar c)
373 {
374     // Use isASCIISpace() for basic Latin-1.
375     // This will include newlines, which aren't included in Unicode DirWS.
376     return c <= 0x7F ? WTF::isASCIISpace(c) : WTF::Unicode::direction(c) == WTF::Unicode::WhiteSpaceNeutral;
377 }
378
379 // This is a hot function because it's used when parsing HTML.
380 inline PassRefPtr<StringImpl> StringImpl::createStrippingNullCharacters(const UChar* characters, unsigned length)
381 {
382     ASSERT(characters);
383     ASSERT(length);
384
385     // Optimize for the case where there are no Null characters by quickly
386     // searching for nulls, and then using StringImpl::create, which will
387     // memcpy the whole buffer.  This is faster than assigning character by
388     // character during the loop. 
389
390     // Fast case.
391     int foundNull = 0;
392     for (unsigned i = 0; !foundNull && i < length; i++) {
393         int c = characters[i]; // more efficient than using UChar here (at least on Intel Mac OS)
394         foundNull |= !c;
395     }
396     if (!foundNull)
397         return StringImpl::create(characters, length);
398
399     return StringImpl::createStrippingNullCharactersSlowCase(characters, length);
400 }
401
402 struct StringHash;
403
404 // StringHash is the default hash for StringImpl* and RefPtr<StringImpl>
405 template<typename T> struct DefaultHash;
406 template<> struct DefaultHash<StringImpl*> {
407     typedef StringHash Hash;
408 };
409 template<> struct DefaultHash<RefPtr<StringImpl> > {
410     typedef StringHash Hash;
411 };
412
413 }
414
415 using WTF::StringImpl;
416 using WTF::equal;
417 using WTF::TextCaseSensitivity;
418 using WTF::TextCaseSensitive;
419 using WTF::TextCaseInsensitive;
420
421 #endif