/*
 * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#pragma once

#include <wtf/text/AtomicStringImpl.h>
#include <wtf/text/IntegerToStringConversion.h>
#include <wtf/text/WTFString.h>

// Define 'NO_IMPLICIT_ATOMICSTRING' before including this header,
// to disallow (expensive) implicit String-->AtomicString conversions.
#ifdef NO_IMPLICIT_ATOMICSTRING
#define ATOMICSTRING_CONVERSION explicit
#else
#define ATOMICSTRING_CONVERSION
#endif

namespace WTF {

class AtomicStringTable;
struct AtomicStringHash;

class AtomicString {
	WTF_MAKE_FAST_ALLOCATED;
public:
    WTF_EXPORT_PRIVATE static void init();

    ALWAYS_INLINE AtomicString() { }
    AtomicString(const LChar* s) : m_string(add(s)) { }
    AtomicString(const char* s) : m_string(add(s)) { }
    AtomicString(const LChar* s, unsigned length) : m_string(add(s, length)) { }
    AtomicString(const UChar* s, unsigned length) : m_string(add(s, length)) { }
    AtomicString(const UChar* s, unsigned length, unsigned existingHash) : m_string(add(s, length, existingHash)) { }
    AtomicString(const UChar* s) : m_string(add(s)) { }

    template<size_t inlineCapacity>
    explicit AtomicString(Vector<UChar, inlineCapacity> characters)
        : m_string(add(characters.data(), characters.size()))
    {
    }

    ATOMICSTRING_CONVERSION ALWAYS_INLINE AtomicString(StringImpl* imp) : m_string(add(imp)) { }
    ALWAYS_INLINE AtomicString(AtomicStringImpl* imp) : m_string(imp) { }
    ATOMICSTRING_CONVERSION ALWAYS_INLINE AtomicString(const String& s) : m_string(add(s.impl())) { }
    AtomicString(StringImpl* baseString, unsigned start, unsigned length) : m_string(add(baseString, start, length)) { }

    // FIXME: AtomicString doesn’t always have AtomicStringImpl, so one of those two names needs to change..
    AtomicString(UniquedStringImpl* uid);

    enum ConstructFromLiteralTag { ConstructFromLiteral };
    AtomicString(const char* characters, unsigned length, ConstructFromLiteralTag)
    : m_string(addFromLiteralData(characters, length))
    {
    }

    template<unsigned characterCount>
    AtomicString(const char (&characters)[characterCount], ConstructFromLiteralTag)
    : m_string(addFromLiteralData(characters, characterCount - 1))
    {
        COMPILE_ASSERT(characterCount > 1, AtomicStringFromLiteralNotEmpty);
        COMPILE_ASSERT((characterCount - 1 <= ((unsigned(~0) - sizeof(StringImpl)) / sizeof(LChar))), AtomicStringFromLiteralCannotOverflow);
    }

    // The explicit constructors with AtomicString::ConstructFromLiteral must be used for literals.
    AtomicString(ASCIILiteral characters)
    : m_string(addFromLiteralData(characters.characters(), characters.length()))
    {
    }

    ALWAYS_INLINE AtomicString(const AtomicString& other) : m_string(other.m_string) { }
    ALWAYS_INLINE AtomicString& operator=(const AtomicString& other) { m_string = other.m_string; return *this; }

    ALWAYS_INLINE ~AtomicString() = default;

    // We have to declare the copy constructor and copy assignment operator as well, otherwise
    // they'll be implicitly deleted by adding the move constructor and move assignment operator.
    // FIXME: Instead of explicitly casting to String&& here, we should use WTFMove, but that requires us to
    // have a standard library that supports move semantics.
    AtomicString(AtomicString&& other) : m_string(static_cast<String&&>(other.m_string)) { }
    AtomicString& operator=(AtomicString&& other) { m_string = static_cast<String&&>(other.m_string); return *this; }

    // Hash table deleted values, which are only constructed and never copied or destroyed.
    ALWAYS_INLINE AtomicString(WTF::HashTableDeletedValueType) : m_string(WTF::HashTableDeletedValue) { }
    ALWAYS_INLINE bool isHashTableDeletedValue() const { return m_string.isHashTableDeletedValue(); }

    unsigned existingHash() const { return isNull() ? 0 : impl()->existingHash(); }

    static PassRefPtr<AtomicStringImpl> lookup(const LChar* characters, unsigned length)
    {
        return findInternal(characters, length);
    }
    static PassRefPtr<AtomicStringImpl> lookup(const UChar* characters, unsigned length)
    {
        return findInternal(characters, length);
    }

    static PassRefPtr<AtomicStringImpl> find(StringImpl* string)
    {
        if (!string || string->isAtomic())
            return static_cast<AtomicStringImpl*>(string);
        return findSlowCase(*string);
    }

    static PassRefPtr<AtomicStringImpl> find(StringImpl& string)
    {
        if (string.isAtomic())
            return static_cast<AtomicStringImpl&>(string);
        return findSlowCase(string);
    }

    operator const String&() const { return m_string; }
    const String& string() const { return m_string; }
    String releaseString() { return WTFMove(m_string); }

    // FIXME: What guarantees this isn't a SymbolImpl rather than an AtomStringImpl?
    ALWAYS_INLINE AtomicStringImpl* impl() const { return static_cast<AtomicStringImpl *>(m_string.impl()); }
    PassRefPtr<AtomicStringImpl> releaseImpl() { return static_pointer_cast<AtomicStringImpl>(m_string.releaseImpl()); }

    PassRefPtr<StringImpl> release() { return m_string.release(); }
    
    ALWAYS_INLINE bool is8Bit() const { return m_string.is8Bit(); }
    ALWAYS_INLINE const LChar* characters8() const { return m_string.characters8(); }
    ALWAYS_INLINE const UChar* characters16() const { return m_string.characters16(); }
    ALWAYS_INLINE unsigned length() const { return m_string.length(); }
    
    ALWAYS_INLINE UChar operator[](unsigned int i) const { return m_string[i]; }

    WTF_EXPORT_PRIVATE static AtomicString number(int);
    WTF_EXPORT_PRIVATE static AtomicString number(unsigned);
    WTF_EXPORT_PRIVATE static AtomicString number(unsigned long);
    WTF_EXPORT_PRIVATE static AtomicString number(unsigned long long);
    WTF_EXPORT_PRIVATE static AtomicString number(float);
    WTF_EXPORT_PRIVATE static AtomicString number(double);
    // If we need more overloads of the number function, we can add all the others that String has, but these seem to do for now.

    ALWAYS_INLINE bool contains(UChar c) const { return m_string.contains(c); }
    ALWAYS_INLINE bool contains(const LChar* s, bool caseSensitive = true) const
        { return m_string.contains(s, caseSensitive); }
    bool contains(const String& s) const
        { return m_string.contains(s); }
    bool contains(const String& s, bool caseSensitive) const
        { return m_string.contains(s, caseSensitive); }
    bool containsIgnoringASCIICase(const String& s) const
        { return m_string.containsIgnoringASCIICase(s); }

    ALWAYS_INLINE size_t find(UChar c, size_t start = 0) const { return m_string.find(c, start); }
    ALWAYS_INLINE size_t find(const LChar* s, size_t start = 0, bool caseSentitive = true) const
        { return m_string.find(s, start, caseSentitive); }
    ALWAYS_INLINE size_t find(const String& s, size_t start = 0, bool caseSentitive = true) const
        { return m_string.find(s, start, caseSentitive); }
    size_t findIgnoringASCIICase(const String& s) const
        { return m_string.findIgnoringASCIICase(s); }
    size_t findIgnoringASCIICase(const String& s, unsigned startOffset) const
        { return m_string.findIgnoringASCIICase(s, startOffset); }
    size_t find(CharacterMatchFunctionPtr matchFunction, unsigned start = 0) const
        { return m_string.find(matchFunction, start); }

    bool startsWith(const String& s) const
        { return m_string.startsWith(s); }
    bool startsWithIgnoringASCIICase(const String& s) const
        { return m_string.startsWithIgnoringASCIICase(s); }
    bool startsWith(const String& s, bool caseSensitive) const
        { return m_string.startsWith(s, caseSensitive); }
    ALWAYS_INLINE bool startsWith(UChar character) const
        { return m_string.startsWith(character); }
    template<unsigned matchLength>
    ALWAYS_INLINE bool startsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const
        { return m_string.startsWith<matchLength>(prefix, caseSensitive); }

    bool endsWith(const String& s) const
        { return m_string.endsWith(s); }
    bool endsWithIgnoringASCIICase(const String& s) const
        { return m_string.endsWithIgnoringASCIICase(s); }
    bool endsWith(const String& s, bool caseSensitive) const
        { return m_string.endsWith(s, caseSensitive); }
    ALWAYS_INLINE bool endsWith(UChar character) const
        { return m_string.endsWith(character); }
    template<unsigned matchLength>
    ALWAYS_INLINE bool endsWith(const char (&prefix)[matchLength], bool caseSensitive = true) const
        { return m_string.endsWith<matchLength>(prefix, caseSensitive); }

    WTF_EXPORT_PRIVATE AtomicString convertToASCIILowercase() const;
    WTF_EXPORT_STRING_API AtomicString convertToASCIIUppercase() const;
    WTF_EXPORT_PRIVATE AtomicString lower() const;
    AtomicString upper() const { return AtomicString(impl()->upper()); }
    
    ALWAYS_INLINE int toInt(bool* ok = 0) const { return m_string.toInt(ok); }
    ALWAYS_INLINE double toDouble(bool* ok = 0) const { return m_string.toDouble(ok); }
    ALWAYS_INLINE float toFloat(bool* ok = 0) const { return m_string.toFloat(ok); }
    ALWAYS_INLINE bool percentage(int& p) const { return m_string.percentage(p); }

    ALWAYS_INLINE bool isNull() const { return m_string.isNull(); }
    ALWAYS_INLINE bool isEmpty() const { return m_string.isEmpty(); }

    static void remove(StringImpl*);
    
#if USE(CF)
    AtomicString(CFStringRef s) :  m_string(add(String(s).impl())) { }
    CFStringRef createCFString() const { return m_string.createCFString(); }
#endif    
#ifdef __OBJC__
    AtomicString(NSString* s) : m_string(add(String(s).impl())) { }
    operator NSString*() const { return m_string; }
#endif
#if PLATFORM(QT)
    AtomicString(const QString& s) : m_string(add(String(s).impl())) { }
    operator QString() const { return m_string; }
#endif

    // AtomicString::fromUTF8 will return a null string if
    // the input data contains invalid UTF-8 sequences.
    static AtomicString fromUTF8(const char*, size_t);
    static AtomicString fromUTF8(const char*);

#ifndef NDEBUG
    void show() const;
#endif
    
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(const LChar*);
    ALWAYS_INLINE static PassRefPtr<StringImpl> add(const char* s) { return add(reinterpret_cast<const LChar*>(s)); };
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(const LChar*, unsigned length);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(const UChar*, unsigned length);
    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProvider(StringTableProvider& stringTableProvider, const LChar* characters, unsigned length)
	{
    	return addSlowCase(stringTableProvider.atomicStringTable(), characters, length);
	}
    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProvider(StringTableProvider& stringTableProvider, const UChar* characters, unsigned length)
	{
    	return addSlowCase(stringTableProvider.atomicStringTable(), characters, length);
	}
    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProviderNotEmpty(StringTableProvider& stringTableProvider, const LChar* characters, unsigned length)
	{
    	return addSlowCaseNotEmpty(stringTableProvider.atomicStringTable(), characters, length);
	}
    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProviderNotEmpty(StringTableProvider& stringTableProvider, const UChar* characters, unsigned length)
	{
    	return addSlowCaseNotEmpty(stringTableProvider.atomicStringTable(), characters, length);
	}
    ALWAYS_INLINE static PassRefPtr<StringImpl> add(const char* s, unsigned length) { return add(reinterpret_cast<const LChar*>(s), length); };
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(const UChar*, unsigned length, unsigned existingHash);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(const UChar*);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(StringImpl*, unsigned offset, unsigned length);
    ALWAYS_INLINE static PassRefPtr<StringImpl> add(StringImpl* string)
	{
        if (!string)
            return string;
        if (string->isAtomic()) {
            ASSERT_WITH_MESSAGE(!string->length() || isInAtomicStringTable(string), "The atomic string comes from an other thread!");
            return string;
        }
        return addSlowCase(string);
    }
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addFromLiteralData(const char *characters, unsigned length);
    template<typename StringTableProvider>
    static PassRefPtr<StringImpl> addFromLiteralDataWithStringTableProvider(StringTableProvider& stringTableProvider, const char *characters, unsigned length)
	{
    	return addFromLiteralDataSlowCase(stringTableProvider.atomicStringTable(), characters, length);
	}

    WTF_EXPORT_PRIVATE static AtomicString fromUTF8Internal(const char*, const char*);

    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProvider(StringTableProvider& stringTableProvider, StringImpl* string)
    {
        if (!string)
            return string;
        if (string->isAtomic()) {
            ASSERT_WITH_MESSAGE(!string->length() || isInAtomicStringTable(string), "The atomic string comes from an other thread!");
            return string;
        }
        return addSlowCase(stringTableProvider.atomicStringTable(), string);
    }

    template<typename StringTableProvider>
    ALWAYS_INLINE static PassRefPtr<StringImpl> addWithStringTableProvider(StringTableProvider& stringTableProvider, StringImpl& string)
    {
        if (string.isAtomic()) {
            ASSERT_WITH_MESSAGE(!string.length() || isInAtomicStringTable(&string), "The atomic string comes from an other thread!");
            return &string;
        }
        return addSlowCase(stringTableProvider.atomicStringTable(), &string);
    }

    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> add(AtomicStringTable& stringTable, StringImpl* string)
	{
        if (!string)
            return string;
        if (string->isAtomic()) {
            ASSERT_WITH_MESSAGE(!string->length() || isInAtomicStringTable(string), "The atomic string comes from an other thread!");
            return string;
        }
        return addSlowCase(stringTable, string);
	}

private:
    enum class CaseConvertType { Upper, Lower };
    template<CaseConvertType> AtomicString convertASCIICase() const;

    String m_string;

    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCase(StringImpl*);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCase(AtomicStringTable&, StringImpl*);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCase(AtomicStringTable&, const LChar*, unsigned length);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCase(AtomicStringTable&, const UChar*, unsigned length);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCaseNotEmpty(AtomicStringTable&, const LChar*, unsigned length);
    WTF_EXPORT_PRIVATE static PassRefPtr<StringImpl> addSlowCaseNotEmpty(AtomicStringTable&, const UChar*, unsigned length);
    static PassRefPtr<StringImpl> addFromLiteralDataSlowCase(AtomicStringTable&, const char *characters, unsigned length);

    WTF_EXPORT_STRING_API static PassRefPtr<AtomicStringImpl> findSlowCase(StringImpl&);

    WTF_EXPORT_STRING_API static PassRefPtr<AtomicStringImpl> findInternal(const LChar*, unsigned length);
    WTF_EXPORT_STRING_API static PassRefPtr<AtomicStringImpl> findInternal(const UChar*, unsigned length);
};

typedef AtomicString AtomString;

ALWAYS_INLINE bool operator==(const AtomicString& a, const AtomicString& b) { return a.impl() == b.impl(); }
bool operator==(const AtomicString&, const LChar*);
ALWAYS_INLINE bool operator==(const AtomicString& a, const char* b) { return WTF::equal(a.impl(), reinterpret_cast<const LChar*>(b)); }
inline bool operator==(const AtomString& a, const ASCIILiteral& b) { return WTF::equal(a.impl(), b); }
inline bool operator==(const AtomicString& a, const Vector<UChar>& b) { return a.impl() && equal(a.impl(), b.data(), b.size()); }    
ALWAYS_INLINE bool operator==(const AtomicString& a, const String& b) { return equal(a.impl(), b.impl()); }
ALWAYS_INLINE bool operator==(const LChar* a, const AtomicString& b) { return b == a; }
ALWAYS_INLINE bool operator==(const String& a, const AtomicString& b) { return equal(a.impl(), b.impl()); }
ALWAYS_INLINE bool operator==(const Vector<UChar>& a, const AtomicString& b) { return b == a; }

ALWAYS_INLINE bool operator!=(const AtomicString& a, const AtomicString& b) { return a.impl() != b.impl(); }
ALWAYS_INLINE bool operator!=(const AtomicString& a, const LChar* b) { return !(a == b); }
ALWAYS_INLINE bool operator!=(const AtomicString& a, const char* b) { return !(a == b); }
ALWAYS_INLINE bool operator!=(const AtomicString& a, const String& b) { return !equal(a.impl(), b.impl()); }
ALWAYS_INLINE bool operator!=(const AtomicString& a, const Vector<UChar>& b) { return !(a == b); }
ALWAYS_INLINE bool operator!=(const LChar* a, const AtomicString& b) { return !(b == a); }
inline bool operator!=(const ASCIILiteral& a, const AtomString& b) { return !(b == a); }
ALWAYS_INLINE bool operator!=(const String& a, const AtomicString& b) { return !equal(a.impl(), b.impl()); }
ALWAYS_INLINE bool operator!=(const Vector<UChar>& a, const AtomicString& b) { return !(a == b); }

inline bool equalIgnoringASCIICase(const AtomicString& a, const AtomicString& b)
{
    return equalIgnoringASCIICase(a.string(), b.string());
}

inline bool equalIgnoringASCIICase(const AtomicString& a, const String& b)
{
    return equalIgnoringASCIICase(a.string(), b);
}

inline bool equalIgnoringASCIICase(const String& a, const AtomicString& b)
{
    return equalIgnoringASCIICase(a, b.string());
}

inline bool equalIgnoringASCIICase(const AtomicString& a, const char* b)
{
    return equalIgnoringASCIICase(a.string(), b);
}

template <unsigned characterCount> inline bool equalIgnoringASCIICase(const AtomicString& a, const char (&b)[characterCount]) { return equalIgnoringASCIICase<characterCount>(a.impl(), b); }

template<unsigned length> ALWAYS_INLINE bool equalLettersIgnoringASCIICase(const AtomicString& string, const char (&lowercaseLetters)[length])
{
    return equalLettersIgnoringASCIICase(string.impl(), lowercaseLetters);
}

template<> struct IntegerToStringConversionTrait<AtomicString> {
    using ReturnType = AtomicString;
    using AdditionalArgumentType = void;
    static AtomicString flush(LChar* characters, unsigned length, void*) { return AtomicString(characters, length); }
};

inline AtomicString::AtomicString(UniquedStringImpl* uid)
    : m_string(uid)
{
}

// Define external global variables for the commonly used atomic strings.
// These are only usable from the main thread.
#ifndef ATOMICSTRING_HIDE_GLOBALS
extern const WTF_EXPORTDATA AtomicString nullAtom;
extern const WTF_EXPORTDATA AtomicString emptyAtom;
extern const WTF_EXPORTDATA AtomicString textAtom;
extern const WTF_EXPORTDATA AtomicString commentAtom;
extern const WTF_EXPORTDATA AtomicString starAtom;
extern const WTF_EXPORTDATA AtomicString xmlAtom;
extern const WTF_EXPORTDATA AtomicString xmlnsAtom;
extern const WTF_EXPORTDATA AtomicString xlinkAtom;

inline AtomicString AtomicString::fromUTF8(const char* characters, size_t length)
{
    if (!characters)
        return nullAtom;
    if (!length)
        return emptyAtom;
    return fromUTF8Internal(characters, characters + length);
}

inline AtomicString AtomicString::fromUTF8(const char* characters)
{
    if (!characters)
        return nullAtom;
    if (!*characters)
        return emptyAtom;
    return fromUTF8Internal(characters, 0);
}
#endif

// AtomicStringHash is the default hash for AtomicString
template<typename T> struct DefaultHash;
template<> struct DefaultHash<AtomicString> {
    typedef AtomicStringHash Hash;
};

} // namespace WTF

#ifndef ATOMICSTRING_HIDE_GLOBALS
using WTF::AtomString;
using WTF::AtomicString;
using WTF::nullAtom;
using WTF::emptyAtom;
using WTF::textAtom;
using WTF::commentAtom;
using WTF::starAtom;
using WTF::xmlAtom;
using WTF::xmlnsAtom;
using WTF::xlinkAtom;
#endif

#include <wtf/text/StringConcatenate.h>

#define DEFINE_STATIC_LOCAL_ATOMICSTRING(name, arguments) \
    static NeverDestroyed<const AtomicString> name arguments
