/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H_
#define IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H_

#include <cstdint>
#include <limits>
#include <type_traits>
#include <utility>
#include "chrome/common/ipc_message.h"
#include "chrome/common/ipc_message_utils.h"
#include "ipc/EnumSerializer.h"
#include "ipc/IPCMessageUtils.h"
#include "mozilla/Assertions.h"
#include "mozilla/BitSet.h"
#include "mozilla/EnumSet.h"
#include "mozilla/EnumTypeTraits.h"
#include "mozilla/Maybe.h"
#include "mozilla/TimeStamp.h"

#include "mozilla/Vector.h"
#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/dom/UserActivation.h"
#include "gfxPlatform.h"
#include "NonCustomCSSPropertyId.h"
#include "nsContentPolicyType.h"
#include "nsContentPermissionHelper.h"
#include "nsDebug.h"
#include "nsIContentPolicy.h"
#include "nsID.h"
#include "nsILoadInfo.h"
#include "nsIThread.h"
#include "nsLiteralString.h"
#include "nsNetUtil.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsTHashSet.h"

// XXX Includes that are only required by implementations which could be moved
// to the cpp file.
#include "base/string_util.h"  // for StringPrintf

#ifdef _MSC_VER
#  pragma warning(disable : 4800)
#endif

namespace mozilla {
template <typename... Ts>
class Variant;

namespace detail {
template <typename... Ts>
struct VariantTag;
}
}  // namespace mozilla

namespace mozilla::dom {
template <typename T>
class Optional;
}

class nsAtom;

namespace IPC {

template <class T>
struct ParamTraits<nsTSubstring<T>> {
  typedef nsTSubstring<T> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    bool isVoid = aParam.IsVoid();
    aWriter->WriteBool(isVoid);

    if (isVoid) {
      // represents a nullptr pointer
      return;
    }

    WriteSequenceParam<const T&>(aWriter, aParam.BeginReading(),
                                 aParam.Length());
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    bool isVoid;
    if (!aReader->ReadBool(&isVoid)) {
      return false;
    }

    if (isVoid) {
      aResult->SetIsVoid(true);
      return true;
    }

    return ReadSequenceParam<T>(aReader, [&](uint32_t aLength) -> T* {
      T* data = nullptr;
      aResult->GetMutableData(&data, aLength);
      return data;
    });
  }
};

template <class T>
struct ParamTraits<nsTString<T>> : ParamTraits<nsTSubstring<T>> {};

template <class T>
struct ParamTraits<nsTLiteralString<T>> : ParamTraits<nsTSubstring<T>> {};

template <class T, size_t N>
struct ParamTraits<nsTAutoStringN<T, N>> : ParamTraits<nsTSubstring<T>> {};

template <class T>
struct ParamTraits<nsTDependentString<T>> : ParamTraits<nsTSubstring<T>> {};

// Key type must be a type with ParamTraits, a default constructor and a move
// constructor.
template <typename KeyClass,
          typename ConstructableKeyType = std::remove_const_t<
              std::remove_reference_t<typename KeyClass::KeyType>>>
struct ParamTraitsforHashSet {
  typedef nsTBaseHashSet<KeyClass> paramType;
  using KeyType = typename KeyClass::KeyType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    uint32_t count = aParam.Count();
    WriteParam(aWriter, count);
    for (const auto& key : aParam) {
      WriteParam(aWriter, key);
    }
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    uint32_t count;
    if (!ReadParam(aReader, &count)) {
      return false;
    }
    paramType table(count);
    for (uint32_t i = 0; i < count; ++i) {
      ConstructableKeyType key;
      if (!ReadParam(aReader, &key)) {
        return false;
      }
      table.Insert(std::move(key));
    }
    *aResult = std::move(table);
    return true;
  }
};

template <typename KeyClass>
struct ParamTraits<nsTBaseHashSet<KeyClass>> : ParamTraitsforHashSet<KeyClass> {
};
template <>
struct ParamTraits<nsTBaseHashSet<nsStringHashKey>>
    : ParamTraitsforHashSet<nsStringHashKey, nsString> {};

template <typename E>
struct ParamTraits<nsTArray<E>> {
  typedef nsTArray<E> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static void Write(MessageWriter* aWriter, paramType&& aParam) {
    WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) {
      if constexpr (std::is_trivially_default_constructible_v<E>) {
        return aResult->AppendElements(aLength);
      } else {
        aResult->SetCapacity(aLength);
        return mozilla::Some(MakeBackInserter(*aResult));
      }
    });
  }
};

template <typename E>
struct ParamTraits<CopyableTArray<E>> : ParamTraits<nsTArray<E>> {};

template <typename E>
struct ParamTraits<FallibleTArray<E>> {
  typedef FallibleTArray<E> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static void Write(MessageWriter* aWriter, paramType&& aParam) {
    WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) {
      if constexpr (std::is_trivially_default_constructible_v<E>) {
        return aResult->AppendElements(aLength, mozilla::fallible);
      } else {
        if (!aResult->SetCapacity(aLength, mozilla::fallible)) {
          return mozilla::Maybe<BackInserter>{};
        }
        return mozilla::Some(BackInserter{.mArray = aResult});
      }
    });
  }

 private:
  struct BackInserter {
    using iterator_category = std::output_iterator_tag;
    using value_type = void;
    using difference_type = void;
    using pointer = void;
    using reference = void;

    struct Proxy {
      paramType& mArray;

      template <typename U>
      void operator=(U&& aValue) {
        // This won't fail because we've reserved capacity earlier.
        MOZ_ALWAYS_TRUE(mArray.AppendElement(aValue, mozilla::fallible));
      }
    };
    Proxy operator*() { return Proxy{.mArray = *mArray}; }

    BackInserter& operator++() { return *this; }
    BackInserter& operator++(int) { return *this; }

    paramType* mArray = nullptr;
  };
};

template <typename E, size_t N>
struct ParamTraits<AutoTArray<E, N>> : ParamTraits<nsTArray<E>> {
  typedef AutoTArray<E, N> paramType;
};

template <typename E, size_t N>
struct ParamTraits<CopyableAutoTArray<E, N>> : ParamTraits<AutoTArray<E, N>> {};

template <typename T>
struct ParamTraits<mozilla::dom::Sequence<T>> : ParamTraits<FallibleTArray<T>> {
};

template <typename E, size_t N, typename AP>
struct ParamTraits<mozilla::Vector<E, N, AP>> {
  typedef mozilla::Vector<E, N, AP> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static void Write(MessageWriter* aWriter, paramType&& aParam) {
    WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) -> E* {
      if (!aResult->resize(aLength)) {
        // So that OOM failure shows up as OOM crash instead of IPC FatalError.
        NS_ABORT_OOM(aLength * sizeof(E));
      }
      return aResult->begin();
    });
  }
};

template <>
struct ParamTraits<float> {
  typedef float paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    aWriter->WriteBytes(&aParam, sizeof(paramType));
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    return aReader->ReadBytesInto(aResult, sizeof(*aResult));
  }
};

template <>
struct ParamTraits<NonCustomCSSPropertyId>
    : public ContiguousEnumSerializer<
          NonCustomCSSPropertyId, eCSSProperty_FIRST, eCSSProperty_INVALID> {};

template <>
struct ParamTraits<nsID> {
  typedef nsID paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteParam(aWriter, aParam.m0);
    WriteParam(aWriter, aParam.m1);
    WriteParam(aWriter, aParam.m2);
    for (unsigned int i = 0; i < std::size(aParam.m3); i++) {
      WriteParam(aWriter, aParam.m3[i]);
    }
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    if (!ReadParam(aReader, &(aResult->m0)) ||
        !ReadParam(aReader, &(aResult->m1)) ||
        !ReadParam(aReader, &(aResult->m2)))
      return false;

    for (unsigned int i = 0; i < std::size(aResult->m3); i++)
      if (!ReadParam(aReader, &(aResult->m3[i]))) return false;

    return true;
  }
};

struct nsContentPolicyTypeValidator {
  using IntegralType = std::underlying_type_t<nsContentPolicyType>;

  static bool IsLegalValue(const IntegralType e) {
    switch (e) {
#define CONTENT_POLICY_TYPE(name) case nsContentPolicyType::name:
      FOR_EACH_CONTENT_POLICY_TYPE(CONTENT_POLICY_TYPE)
#undef CONTENT_POLICY_TYPE
      return true;

      case nsContentPolicyType::TYPE_INVALID:
        // NOTE: It is intentionally valid to send TYPE_INVALID over IPC.
        return true;
    }

    return false;
  }
};

template <>
struct ParamTraits<nsContentPolicyType>
    : EnumSerializer<nsContentPolicyType, nsContentPolicyTypeValidator> {};

template <>
struct ParamTraits<mozilla::TimeDuration> {
  typedef mozilla::TimeDuration paramType;
  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteParam(aWriter, aParam.mValue);
  }
  static bool Read(MessageReader* aReader, paramType* aResult) {
    return ReadParam(aReader, &aResult->mValue);
  };
};

template <>
struct ParamTraits<mozilla::TimeStamp> {
  typedef mozilla::TimeStamp paramType;
  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    WriteParam(aWriter, aParam.mValue);
  }
  static bool Read(MessageReader* aReader, paramType* aResult) {
    return ReadParam(aReader, &aResult->mValue);
  };
};

template <class T>
struct ParamTraits<mozilla::Maybe<T>> {
  typedef mozilla::Maybe<T> paramType;

  static void Write(MessageWriter* writer, const paramType& param) {
    if (param.isSome()) {
      WriteParam(writer, true);
      WriteParam(writer, param.ref());
    } else {
      WriteParam(writer, false);
    }
  }

  static void Write(MessageWriter* writer, paramType&& param) {
    if (param.isSome()) {
      WriteParam(writer, true);
      WriteParam(writer, std::move(param.ref()));
    } else {
      WriteParam(writer, false);
    }
  }

  static bool Read(MessageReader* reader, paramType* result) {
    bool isSome;
    if (!ReadParam(reader, &isSome)) {
      return false;
    }
    if (isSome) {
      mozilla::Maybe<T> tmp = ReadParam<T>(reader).TakeMaybe();
      if (!tmp) {
        return false;
      }
      *result = std::move(tmp);
    } else {
      *result = mozilla::Nothing();
    }
    return true;
  }
};

template <typename T, typename U>
struct ParamTraits<mozilla::EnumSet<T, U>> {
  typedef mozilla::EnumSet<T, U> paramType;
  typedef U serializedType;

  static void Write(MessageWriter* writer, const paramType& param) {
    MOZ_RELEASE_ASSERT(IsLegalValue(param.serialize()));
    WriteParam(writer, param.serialize());
  }

  static bool Read(MessageReader* reader, paramType* result) {
    serializedType tmp;

    if (ReadParam(reader, &tmp)) {
      if (IsLegalValue(tmp)) {
        result->deserialize(tmp);
        return true;
      }
    }

    return false;
  }

  static constexpr size_t kUnderlyingWidth = [] {
    if constexpr (std::numeric_limits<serializedType>::is_specialized) {
      return std::numeric_limits<serializedType>::digits;
    } else {
      return serializedType().size();  // for std::bitset<N>
    }
  }();

  static constexpr serializedType AllEnumBits() {
    return ~serializedType(0) >>
           (kUnderlyingWidth - (mozilla::MaxEnumValue<T>::value + 1));
  }

  static constexpr bool IsLegalValue(const serializedType value) {
    static_assert(mozilla::MaxEnumValue<T>::value < kUnderlyingWidth,
                  "Enum max value is not in the range!");
    static_assert(
        std::is_unsigned_v<decltype(mozilla::MaxEnumValue<T>::value)>,
        "Type of MaxEnumValue<T>::value specialization should be unsigned!");

    return (value & AllEnumBits()) == value;
  }
};

template <class... Ts>
struct ParamTraits<mozilla::Variant<Ts...>> {
  typedef mozilla::Variant<Ts...> paramType;
  using Tag = typename mozilla::detail::VariantTag<Ts...>::Type;

  static void Write(MessageWriter* writer, const paramType& param) {
    WriteParam(writer, param.tag);
    param.match([writer](const auto& t) { WriteParam(writer, t); });
  }

  // Because VariantReader is a nested struct, we need the dummy template
  // parameter to avoid making VariantReader<0> an explicit specialization,
  // which is not allowed for a nested class template
  template <size_t N, typename dummy = void>
  struct VariantReader {
    using Next = VariantReader<N - 1>;

    // Since the VariantReader specializations start at N , we need to
    // subtract one to look at N - 1, the first valid tag.  This means our
    // comparisons are off by 1.  If we get to N = 0 then we have failed to
    // find a match to the tag.
    static constexpr size_t Idx = N - 1;
    using T = mozilla::detail::Nth<Idx, Ts...>;

    static ReadResult<paramType> Read(MessageReader* reader, Tag tag) {
      if (tag == Idx) {
        auto p = ReadParam<T>(reader);
        if (p) {
          return ReadResult<paramType>(
              std::in_place, mozilla::VariantIndex<Idx>{}, std::move(*p));
        }
        return {};
      } else {
        return Next::Read(reader, tag);
      }
    }

  };  // VariantReader<N>

  // Since we are conditioning on tag = N - 1 in the preceding specialization,
  // if we get to `VariantReader<0, dummy>` we have failed to find
  // a matching tag.
  template <typename dummy>
  struct VariantReader<0, dummy> {
    static ReadResult<paramType> Read(MessageReader* reader, Tag tag) {
      return {};
    }
  };

  static ReadResult<paramType> Read(MessageReader* reader) {
    Tag tag;
    if (ReadParam(reader, &tag)) {
      return VariantReader<sizeof...(Ts)>::Read(reader, tag);
    }
    return {};
  }
};

template <typename T>
struct ParamTraits<mozilla::dom::Optional<T>> {
  typedef mozilla::dom::Optional<T> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    if (aParam.WasPassed()) {
      WriteParam(aWriter, true);
      WriteParam(aWriter, aParam.Value());
      return;
    }

    WriteParam(aWriter, false);
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    bool wasPassed = false;

    if (!ReadParam(aReader, &wasPassed)) {
      return false;
    }

    aResult->Reset();

    if (wasPassed) {
      if (!ReadParam(aReader, &aResult->Construct())) {
        return false;
      }
    }

    return true;
  }
};

template <>
struct ParamTraits<nsAtom*> {
  typedef nsAtom paramType;

  static void Write(MessageWriter* aWriter, const paramType* aParam);
  static bool Read(MessageReader* aReader, RefPtr<paramType>* aResult);
};

struct CrossOriginOpenerPolicyValidator {
  using IntegralType =
      std::underlying_type_t<nsILoadInfo::CrossOriginOpenerPolicy>;

  static bool IsLegalValue(const IntegralType e) {
    return AreIntegralValuesEqual(e, nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) ||
           AreIntegralValuesEqual(e, nsILoadInfo::OPENER_POLICY_SAME_ORIGIN) ||
           AreIntegralValuesEqual(
               e, nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_POPUPS) ||
           AreIntegralValuesEqual(
               e, nsILoadInfo::
                      OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP);
  }

 private:
  static bool AreIntegralValuesEqual(
      const IntegralType aLhs,
      const nsILoadInfo::CrossOriginOpenerPolicy aRhs) {
    return aLhs == static_cast<IntegralType>(aRhs);
  }
};

template <>
struct ParamTraits<nsILoadInfo::CrossOriginOpenerPolicy>
    : EnumSerializer<nsILoadInfo::CrossOriginOpenerPolicy,
                     CrossOriginOpenerPolicyValidator> {};

struct CrossOriginEmbedderPolicyValidator {
  using IntegralType =
      std::underlying_type_t<nsILoadInfo::CrossOriginEmbedderPolicy>;

  static bool IsLegalValue(const IntegralType e) {
    return AreIntegralValuesEqual(e, nsILoadInfo::EMBEDDER_POLICY_NULL) ||
           AreIntegralValuesEqual(e,
                                  nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP) ||
           AreIntegralValuesEqual(e,
                                  nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS);
  }

 private:
  static bool AreIntegralValuesEqual(
      const IntegralType aLhs,
      const nsILoadInfo::CrossOriginEmbedderPolicy aRhs) {
    return aLhs == static_cast<IntegralType>(aRhs);
  }
};

template <>
struct ParamTraits<nsILoadInfo::CrossOriginEmbedderPolicy>
    : EnumSerializer<nsILoadInfo::CrossOriginEmbedderPolicy,
                     CrossOriginEmbedderPolicyValidator> {};

template <>
struct ParamTraits<nsIThread::QoSPriority>
    : public ContiguousEnumSerializerInclusive<nsIThread::QoSPriority,
                                               nsIThread::QOS_PRIORITY_NORMAL,
                                               nsIThread::QOS_PRIORITY_LOW> {};

template <size_t N, typename Word>
struct ParamTraits<mozilla::BitSet<N, Word>> {
  typedef mozilla::BitSet<N, Word> paramType;

  static void Write(MessageWriter* aWriter, const paramType& aParam) {
    for (Word word : aParam.Storage()) {
      WriteParam(aWriter, word);
    }
  }

  static bool Read(MessageReader* aReader, paramType* aResult) {
    for (Word& word : aResult->Storage()) {
      if (!ReadParam(aReader, &word)) {
        return false;
      }
    }
    return true;
  }
};

// Use TiedFields for LinkHeader serialization to ensure that all fields are
// serialized.
template <>
struct ParamTraits<mozilla::net::LinkHeader>
    : ParamTraits_TiedFields<mozilla::net::LinkHeader> {};

DEFINE_IPC_SERIALIZER_WITH_FIELDS(mozilla::dom::UserActivation::Modifiers,
                                  mModifiers);

template <>
struct ParamTraits<gfxPlatform::GlobalReflowFlags>
    : public BitFlagsEnumSerializer<gfxPlatform::GlobalReflowFlags,
                                    gfxPlatform::GlobalReflowFlags::ALL_BITS> {
};

template <>
struct ParamTraits<nsILoadInfo::IPAddressSpace>
    : public ContiguousEnumSerializer<nsILoadInfo::IPAddressSpace,
                                      nsILoadInfo::IPAddressSpace::Unknown,
                                      nsILoadInfo::IPAddressSpace::Invalid> {};

using PromptResult = mozilla::dom::ContentPermissionRequestBase::PromptResult;
template <>
struct ParamTraits<PromptResult>
    : public ContiguousEnumSerializerInclusive<
          PromptResult, PromptResult::Granted, PromptResult::Pending> {};

} /* namespace IPC */

#endif /* IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H_ */
