/*
 * 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.
 *
 */

#ifndef AtomicString_h
#define AtomicString_h

#include <cstring>
#include <iosfwd>

#include "build/build_config.h"
#include "platform/wtf/Allocator.h"
#include "platform/wtf/HashTableDeletedValueType.h"
#include "platform/wtf/WTFExport.h"
#include "platform/wtf/text/CString.h"
#include "platform/wtf/text/StringView.h"
#include "platform/wtf/text/WTFString.h"

namespace WTF {

struct AtomicStringHash;

// An AtomicString instance represents a string, and multiple AtomicString
// instances can share their string storage if the strings are
// identical. Comparing two AtomicString instances is much faster than comparing
// two String instances because we just check string storage identity.
//
// AtomicString instances are not thread-safe. An AtomicString instance created
// in a thread must be used only in the creator thread.  If multiple threads
// access a single AtomicString instance, we have race condition of a reference
// count in StringImpl, and would hit a runtime CHECK in
// AtomicStringTable::remove().
//
// Exception: nullAtom and emptyAtom, are shared in multiple threads, and are
// never stored in AtomicStringTable.
class WTF_EXPORT AtomicString {
  USING_FAST_MALLOC(AtomicString);

 public:
  // The function is defined in StringStatics.cpp.
  static void Init();

  AtomicString() {}
  AtomicString(const LChar* chars)
      : AtomicString(chars,
                     chars ? strlen(reinterpret_cast<const char*>(chars)) : 0) {
  }
  AtomicString(const char* chars)
      : AtomicString(reinterpret_cast<const LChar*>(chars)) {}
  AtomicString(const LChar* chars, unsigned length);
  AtomicString(const UChar* chars, unsigned length);
  AtomicString(const UChar* chars);
  AtomicString(const char16_t* chars)
      : AtomicString(reinterpret_cast<const UChar*>(chars)) {}

  template <size_t inlineCapacity>
  explicit AtomicString(const Vector<UChar, inlineCapacity>& vector)
      : AtomicString(vector.data(), vector.size()) {}

  // Constructing an AtomicString from a String / StringImpl can be expensive if
  // the StringImpl is not already atomic.
  explicit AtomicString(StringImpl* impl) : string_(Add(impl)) {}
  explicit AtomicString(const String& s) : string_(Add(s.Impl())) {}

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

  explicit operator bool() const { return !IsNull(); }
  operator const String&() const { return string_; }
  const String& GetString() const { return string_; }

  StringImpl* Impl() const { return string_.Impl(); }

  bool Is8Bit() const { return string_.Is8Bit(); }
  const LChar* Characters8() const { return string_.Characters8(); }
  const UChar* Characters16() const { return string_.Characters16(); }
  unsigned length() const { return string_.length(); }

  UChar operator[](unsigned i) const { return string_[i]; }

  // Find characters.
  size_t find(UChar c, unsigned start = 0) const {
    return string_.find(c, start);
  }
  size_t find(LChar c, unsigned start = 0) const {
    return string_.find(c, start);
  }
  size_t find(char c, unsigned start = 0) const {
    return find(static_cast<LChar>(c), start);
  }
  size_t Find(CharacterMatchFunctionPtr match_function,
              unsigned start = 0) const {
    return string_.Find(match_function, start);
  }

  // Find substrings.
  size_t Find(const StringView& value,
              unsigned start = 0,
              TextCaseSensitivity case_sensitivity = kTextCaseSensitive) const {
    return string_.Find(value, start, case_sensitivity);
  }

  // Unicode aware case insensitive string matching. Non-ASCII characters might
  // match to ASCII characters. This function is rarely used to implement web
  // platform features.
  size_t FindIgnoringCase(const StringView& value, unsigned start = 0) const {
    return string_.FindIgnoringCase(value, start);
  }

  // ASCII case insensitive string matching.
  size_t FindIgnoringASCIICase(const StringView& value,
                               unsigned start = 0) const {
    return string_.FindIgnoringASCIICase(value, start);
  }

  bool Contains(char c) const { return find(c) != kNotFound; }
  bool Contains(
      const StringView& value,
      TextCaseSensitivity case_sensitivity = kTextCaseSensitive) const {
    return Find(value, 0, case_sensitivity) != kNotFound;
  }

  // Find the last instance of a single character or string.
  size_t ReverseFind(UChar c, unsigned start = UINT_MAX) const {
    return string_.ReverseFind(c, start);
  }
  size_t ReverseFind(const StringView& value, unsigned start = UINT_MAX) const {
    return string_.ReverseFind(value, start);
  }

  bool StartsWith(
      const StringView& prefix,
      TextCaseSensitivity case_sensitivity = kTextCaseSensitive) const {
    return string_.StartsWith(prefix, case_sensitivity);
  }
  bool StartsWithIgnoringCase(const StringView& prefix) const {
    return string_.StartsWithIgnoringCase(prefix);
  }
  bool StartsWithIgnoringASCIICase(const StringView& prefix) const {
    return string_.StartsWithIgnoringASCIICase(prefix);
  }
  bool StartsWith(UChar character) const {
    return string_.StartsWith(character);
  }

  bool EndsWith(
      const StringView& suffix,
      TextCaseSensitivity case_sensitivity = kTextCaseSensitive) const {
    return string_.EndsWith(suffix, case_sensitivity);
  }
  bool EndsWith(UChar character) const { return string_.EndsWith(character); }

  // Returns a lowercase version of the string. This function might
  // convert non-ASCII characters to ASCII characters. For example,
  // DeprecatedLower() for U+212A is 'k'.
  // This function is rarely used to implement web platform features.
  // See crbug.com/627682.
  // This function is deprecated. We should use LowerASCII(), or introduce
  // LowerUnicode().
  AtomicString DeprecatedLower() const;

  // Returns a lowercase/uppercase version of the string.
  // These functions convert ASCII characters only.
  AtomicString LowerASCII() const;
  AtomicString UpperASCII() const;

  int ToInt(bool* ok = 0) const { return string_.ToInt(ok); }
  double ToDouble(bool* ok = 0) const { return string_.ToDouble(ok); }
  float ToFloat(bool* ok = 0) const { return string_.ToFloat(ok); }

  static AtomicString Number(int);
  static AtomicString Number(unsigned);
  static AtomicString Number(long);
  static AtomicString Number(unsigned long);
  static AtomicString Number(long long);
  static AtomicString Number(unsigned long long);

  static AtomicString Number(double, unsigned precision = 6);

  bool IsNull() const { return string_.IsNull(); }
  bool IsEmpty() const { return string_.IsEmpty(); }

#ifdef __OBJC__
  AtomicString(NSString* s) : string_(Add((CFStringRef)s)) {}
  operator NSString*() const { return string_; }
#endif
  // AtomicString::fromUTF8 will return a null string if
  // the input data contains invalid UTF-8 sequences.
  // NOTE: Passing a zero size means use the whole string.
  static AtomicString FromUTF8(const char*, size_t length);
  static AtomicString FromUTF8(const char*);

  CString Ascii() const { return string_.Ascii(); }
  CString Latin1() const { return string_.Latin1(); }
  CString Utf8(UTF8ConversionMode mode = kLenientUTF8Conversion) const {
    return string_.Utf8(mode);
  }

  size_t CharactersSizeInBytes() const {
    return string_.CharactersSizeInBytes();
  }

  bool IsSafeToSendToAnotherThread() const {
    return string_.IsSafeToSendToAnotherThread();
  }

#ifndef NDEBUG
  void Show() const;
#endif

 private:
  String string_;

  ALWAYS_INLINE static RefPtr<StringImpl> Add(StringImpl* r) {
    if (!r || r->IsAtomic())
      return r;
    return AddSlowCase(r);
  }
  static RefPtr<StringImpl> AddSlowCase(StringImpl*);
#if defined(OS_MACOSX)
  static RefPtr<StringImpl> Add(CFStringRef);
#endif
};

inline bool operator==(const AtomicString& a, const AtomicString& b) {
  return a.Impl() == b.Impl();
}
inline bool operator==(const AtomicString& a, const String& b) {
  // We don't use equalStringView so we get the isAtomic() optimization inside
  // WTF::equal.
  return Equal(a.Impl(), b.Impl());
}
inline bool operator==(const String& a, const AtomicString& b) {
  return b == a;
}
inline bool operator==(const AtomicString& a, const char* b) {
  return EqualStringView(a, b);
}
inline bool operator==(const char* a, const AtomicString& b) {
  return b == a;
}

inline bool operator!=(const AtomicString& a, const AtomicString& b) {
  return a.Impl() != b.Impl();
}
inline bool operator!=(const AtomicString& a, const String& b) {
  return !(a == b);
}
inline bool operator!=(const String& a, const AtomicString& b) {
  return !(a == b);
}
inline bool operator!=(const AtomicString& a, const char* b) {
  return !(a == b);
}
inline bool operator!=(const char* a, const AtomicString& b) {
  return !(a == b);
}

// Define external global variables for the commonly used atomic strings.
// These are only usable from the main thread.
WTF_EXPORT extern const AtomicString& g_null_atom;
WTF_EXPORT extern const AtomicString& g_empty_atom;
WTF_EXPORT extern const AtomicString& g_star_atom;
WTF_EXPORT extern const AtomicString& g_xml_atom;
WTF_EXPORT extern const AtomicString& g_xmlns_atom;
WTF_EXPORT extern const AtomicString& g_xlink_atom;
WTF_EXPORT extern const AtomicString& g_http_atom;
WTF_EXPORT extern const AtomicString& g_https_atom;

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

// Pretty printer for gtest and base/logging.*.  It prepends and appends
// double-quotes, and escapes chracters other than ASCII printables.
WTF_EXPORT std::ostream& operator<<(std::ostream&, const AtomicString&);

inline StringView::StringView(const AtomicString& string,
                              unsigned offset,
                              unsigned length)
    : StringView(string.Impl(), offset, length) {}
inline StringView::StringView(const AtomicString& string, unsigned offset)
    : StringView(string.Impl(), offset) {}
inline StringView::StringView(const AtomicString& string)
    : StringView(string.Impl()) {}

}  // namespace WTF

WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(AtomicString);

using WTF::AtomicString;
using WTF::g_null_atom;
using WTF::g_empty_atom;
using WTF::g_star_atom;
using WTF::g_xml_atom;
using WTF::g_xmlns_atom;
using WTF::g_xlink_atom;

#include "platform/wtf/text/StringConcatenate.h"
#endif  // AtomicString_h
