/* THIS FILE IS AUTOGENERATED FROM Headers.webidl BY Codegen.py - DO NOT EDIT */

#include "HeadersBinding.h"
#include "WrapperFactory.h"
#include "jsapi.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/Headers.h"
#include "mozilla/dom/IterableIterator.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/UnionConversions.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.h"

namespace mozilla {
namespace dom {

namespace HeadersGuardEnumValues {
extern const EnumEntry strings[6] = {
  {"none", 4},
  {"request", 7},
  {"request-no-cors", 15},
  {"response", 8},
  {"immutable", 9},
  { nullptr, 0 }
};
} // namespace HeadersGuardEnumValues

bool
ToJSValue(JSContext* aCx, HeadersGuardEnum aArgument, JS::MutableHandle<JS::Value> aValue)
{
  MOZ_ASSERT(uint32_t(aArgument) < ArrayLength(HeadersGuardEnumValues::strings));
  JSString* resultStr =
    JS_NewStringCopyN(aCx, HeadersGuardEnumValues::strings[uint32_t(aArgument)].value,
                      HeadersGuardEnumValues::strings[uint32_t(aArgument)].length);
  if (!resultStr) {
    return false;
  }
  aValue.setString(resultStr);
  return true;
}


void
ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap& aUnion, const char* aName, uint32_t aFlags)
{
  if (aUnion.IsHeaders()) {
    ImplCycleCollectionTraverse(aCallback, aUnion.GetAsHeaders(), "mHeaders", aFlags);
  }
}


void
ImplCycleCollectionUnlink(OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap& aUnion)
{
  aUnion.Uninit();
}


bool
HeadersOrByteStringSequenceSequenceOrByteStringMozMap::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
      break;
    }
    case eHeaders: {
      if (!GetOrCreateDOMReflector(cx, mValue.mHeaders.Value(), rval)) {
        MOZ_ASSERT(true || JS_IsExceptionPending(cx));
        return false;
      }
      return true;
      break;
    }
    case eByteStringSequenceSequence: {

      uint32_t length = mValue.mByteStringSequenceSequence.Value().Length();
      JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));
      if (!returnArray) {
        return false;
      }
      // Scope for 'tmp'
      {
        JS::Rooted<JS::Value> tmp(cx);
        for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
          // Control block to let us common up the JS_DefineElement calls when there
          // are different ways to succeed at wrapping the object.
          do {

            uint32_t length = mValue.mByteStringSequenceSequence.Value()[sequenceIdx0].Length();
            JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));
            if (!returnArray) {
              return false;
            }
            // Scope for 'tmp'
            {
              JS::Rooted<JS::Value> tmp(cx);
              for (uint32_t sequenceIdx1 = 0; sequenceIdx1 < length; ++sequenceIdx1) {
                // Control block to let us common up the JS_DefineElement calls when there
                // are different ways to succeed at wrapping the object.
                do {
                  if (!NonVoidByteStringToJsval(cx, mValue.mByteStringSequenceSequence.Value()[sequenceIdx0][sequenceIdx1], &tmp)) {
                    return false;
                  }
                  break;
                } while (0);
                if (!JS_DefineElement(cx, returnArray, sequenceIdx1, tmp,
                                      JSPROP_ENUMERATE)) {
                  return false;
                }
              }
            }
            tmp.setObject(*returnArray);
            break;
          } while (0);
          if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
                                JSPROP_ENUMERATE)) {
            return false;
          }
        }
      }
      rval.setObject(*returnArray);
      return true;
      break;
    }
    case eByteStringMozMap: {

      nsTArray<nsString> keys;
      mValue.mByteStringMozMap.Value().GetKeys(keys);
      JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx));
      if (!returnObj) {
        return false;
      }
      // Scope for 'tmp'
      {
        JS::Rooted<JS::Value> tmp(cx);
        for (size_t idx = 0; idx < keys.Length(); ++idx) {
          auto& mozMapValue0 = mValue.mByteStringMozMap.Value().Get(keys[idx]);
          // Control block to let us common up the JS_DefineUCProperty calls when there
          // are different ways to succeed at wrapping the value.
          do {
            if (!NonVoidByteStringToJsval(cx, mozMapValue0, &tmp)) {
              return false;
            }
            break;
          } while (0);
          if (!JS_DefineUCProperty(cx, returnObj, keys[idx].get(),
                                   keys[idx].Length(), tmp,
                                   JSPROP_ENUMERATE)) {
            return false;
          }
        }
      }
      rval.setObject(*returnObj);
      return true;
      break;
    }
    default: {
      return false;
      break;
    }
  }

  return false;
}


OwningNonNull<mozilla::dom::Headers>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::RawSetAsHeaders()
{
  if (mType == eHeaders) {
    return mValue.mHeaders.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eHeaders;
  return mValue.mHeaders.SetValue();
}

OwningNonNull<mozilla::dom::Headers>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::SetAsHeaders()
{
  if (mType == eHeaders) {
    return mValue.mHeaders.Value();
  }
  Uninit();
  mType = eHeaders;
  return mValue.mHeaders.SetValue();
}

bool
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::TrySetToHeaders(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    OwningNonNull<mozilla::dom::Headers>& memberSlot = RawSetAsHeaders();
    static_assert(IsRefcounted<mozilla::dom::Headers>::value, "We can only store refcounted classes.");{
      nsresult rv = UnwrapObject<prototypes::id::Headers, mozilla::dom::Headers>(value, memberSlot);
      if (NS_FAILED(rv)) {
        DestroyHeaders();
        tryNext = true;
        return true;
      }
    }
  }
  return true;
}

void
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::DestroyHeaders()
{
  MOZ_ASSERT(IsHeaders(), "Wrong type!");
  mValue.mHeaders.Destroy();
  mType = eUninitialized;
}




Sequence<Sequence<nsCString>>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::RawSetAsByteStringSequenceSequence()
{
  if (mType == eByteStringSequenceSequence) {
    return mValue.mByteStringSequenceSequence.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eByteStringSequenceSequence;
  return mValue.mByteStringSequenceSequence.SetValue();
}

Sequence<Sequence<nsCString>>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::SetAsByteStringSequenceSequence()
{
  if (mType == eByteStringSequenceSequence) {
    return mValue.mByteStringSequenceSequence.Value();
  }
  Uninit();
  mType = eByteStringSequenceSequence;
  return mValue.mByteStringSequenceSequence.SetValue();
}

bool
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::TrySetToByteStringSequenceSequence(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    Sequence<Sequence<nsCString>>& memberSlot = RawSetAsByteStringSequenceSequence();
    JS::ForOfIterator iter(cx);
    if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
      return false;
    }
    if (!iter.valueIsIterable()) {
      DestroyByteStringSequenceSequence();
      tryNext = true;
      return true;
    }
    Sequence<Sequence<nsCString>> &arr = memberSlot;
    JS::Rooted<JS::Value> temp(cx);
    while (true) {
      bool done;
      if (!iter.next(&temp, &done)) {
        return false;
      }
      if (done) {
        break;
      }
      Sequence<nsCString>* slotPtr = arr.AppendElement(mozilla::fallible);
      if (!slotPtr) {
        JS_ReportOutOfMemory(cx);
        return false;
      }
      Sequence<nsCString>& slot = *slotPtr;
      if (temp.isObject()) {
        JS::ForOfIterator iter1(cx);
        if (!iter1.init(temp, JS::ForOfIterator::AllowNonIterable)) {
          return false;
        }
        if (!iter1.valueIsIterable()) {
          ThrowErrorMessage(cx, MSG_NOT_SEQUENCE, "Element of member of HeadersOrByteStringSequenceSequenceOrByteStringMozMap");
          return false;
        }
        Sequence<nsCString> &arr1 = slot;
        JS::Rooted<JS::Value> temp1(cx);
        while (true) {
          bool done1;
          if (!iter1.next(&temp1, &done1)) {
            return false;
          }
          if (done1) {
            break;
          }
          nsCString* slotPtr1 = arr1.AppendElement(mozilla::fallible);
          if (!slotPtr1) {
            JS_ReportOutOfMemory(cx);
            return false;
          }
          nsCString& slot1 = *slotPtr1;
          if (!ConvertJSValueToByteString(cx, temp1, false, slot1)) {
            return false;
          }
        }
      } else {
        ThrowErrorMessage(cx, MSG_NOT_SEQUENCE, "Element of member of HeadersOrByteStringSequenceSequenceOrByteStringMozMap");
        return false;
      }
    }
  }
  return true;
}

void
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::DestroyByteStringSequenceSequence()
{
  MOZ_ASSERT(IsByteStringSequenceSequence(), "Wrong type!");
  mValue.mByteStringSequenceSequence.Destroy();
  mType = eUninitialized;
}




MozMap<nsCString>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::RawSetAsByteStringMozMap()
{
  if (mType == eByteStringMozMap) {
    return mValue.mByteStringMozMap.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eByteStringMozMap;
  return mValue.mByteStringMozMap.SetValue();
}

MozMap<nsCString>&
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::SetAsByteStringMozMap()
{
  if (mType == eByteStringMozMap) {
    return mValue.mByteStringMozMap.Value();
  }
  Uninit();
  mType = eByteStringMozMap;
  return mValue.mByteStringMozMap.SetValue();
}

bool
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::TrySetToByteStringMozMap(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    MozMap<nsCString>& memberSlot = RawSetAsByteStringMozMap();
    MozMap<nsCString> &mozMap = memberSlot;

    JS::Rooted<JSObject*> mozMapObj(cx, &value.toObject());
    JS::Rooted<JS::IdVector> ids(cx, JS::IdVector(cx));
    if (!JS_Enumerate(cx, mozMapObj, &ids)) {
      return false;
    }
    JS::Rooted<JS::Value> propNameValue(cx);
    JS::Rooted<JS::Value> temp(cx);
    JS::Rooted<jsid> curId(cx);
    for (size_t i = 0; i < ids.length(); ++i) {
      // Make sure we get the value before converting the name, since
      // getting the value can trigger GC but our name is a dependent
      // string.
      curId = ids[i];
      binding_detail::FakeString propName;
      bool isSymbol;
      if (!ConvertIdToString(cx, curId, propName, isSymbol) ||
          (!isSymbol && !JS_GetPropertyById(cx, mozMapObj, curId, &temp))) {
        return false;
      }
      if (isSymbol) {
        continue;
      }

      nsCString* slotPtr = mozMap.AddEntry(propName);
      if (!slotPtr) {
        JS_ReportOutOfMemory(cx);
        return false;
      }
      nsCString& slot = *slotPtr;
      if (!ConvertJSValueToByteString(cx, temp, false, slot)) {
        return false;
      }
    }
  }
  return true;
}

void
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::DestroyByteStringMozMap()
{
  MOZ_ASSERT(IsByteStringMozMap(), "Wrong type!");
  mValue.mByteStringMozMap.Destroy();
  mType = eUninitialized;
}




void
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::Uninit()
{
  switch (mType) {
    case eUninitialized: {
      break;
    }
    case eHeaders: {
      DestroyHeaders();
      break;
    }
    case eByteStringSequenceSequence: {
      DestroyByteStringSequenceSequence();
      break;
    }
    case eByteStringMozMap: {
      DestroyByteStringMozMap();
      break;
    }
  }
}

bool
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
      break;
    }
    case eHeaders: {
      if (!GetOrCreateDOMReflector(cx, mValue.mHeaders.Value(), rval)) {
        MOZ_ASSERT(true || JS_IsExceptionPending(cx));
        return false;
      }
      return true;
      break;
    }
    case eByteStringSequenceSequence: {

      uint32_t length = mValue.mByteStringSequenceSequence.Value().Length();
      JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));
      if (!returnArray) {
        return false;
      }
      // Scope for 'tmp'
      {
        JS::Rooted<JS::Value> tmp(cx);
        for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
          // Control block to let us common up the JS_DefineElement calls when there
          // are different ways to succeed at wrapping the object.
          do {

            uint32_t length = mValue.mByteStringSequenceSequence.Value()[sequenceIdx0].Length();
            JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));
            if (!returnArray) {
              return false;
            }
            // Scope for 'tmp'
            {
              JS::Rooted<JS::Value> tmp(cx);
              for (uint32_t sequenceIdx1 = 0; sequenceIdx1 < length; ++sequenceIdx1) {
                // Control block to let us common up the JS_DefineElement calls when there
                // are different ways to succeed at wrapping the object.
                do {
                  if (!NonVoidByteStringToJsval(cx, mValue.mByteStringSequenceSequence.Value()[sequenceIdx0][sequenceIdx1], &tmp)) {
                    return false;
                  }
                  break;
                } while (0);
                if (!JS_DefineElement(cx, returnArray, sequenceIdx1, tmp,
                                      JSPROP_ENUMERATE)) {
                  return false;
                }
              }
            }
            tmp.setObject(*returnArray);
            break;
          } while (0);
          if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
                                JSPROP_ENUMERATE)) {
            return false;
          }
        }
      }
      rval.setObject(*returnArray);
      return true;
      break;
    }
    case eByteStringMozMap: {

      nsTArray<nsString> keys;
      mValue.mByteStringMozMap.Value().GetKeys(keys);
      JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx));
      if (!returnObj) {
        return false;
      }
      // Scope for 'tmp'
      {
        JS::Rooted<JS::Value> tmp(cx);
        for (size_t idx = 0; idx < keys.Length(); ++idx) {
          auto& mozMapValue0 = mValue.mByteStringMozMap.Value().Get(keys[idx]);
          // Control block to let us common up the JS_DefineUCProperty calls when there
          // are different ways to succeed at wrapping the value.
          do {
            if (!NonVoidByteStringToJsval(cx, mozMapValue0, &tmp)) {
              return false;
            }
            break;
          } while (0);
          if (!JS_DefineUCProperty(cx, returnObj, keys[idx].get(),
                                   keys[idx].Length(), tmp,
                                   JSPROP_ENUMERATE)) {
            return false;
          }
        }
      }
      rval.setObject(*returnObj);
      return true;
      break;
    }
    default: {
      return false;
      break;
    }
  }

  return false;
}

void
OwningHeadersOrByteStringSequenceSequenceOrByteStringMozMap::TraceUnion(JSTracer* trc)
{
}


namespace HeadersBinding {

static bool
append(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 2)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "Headers.append");
  }
  nsCString arg0;
  if (!ConvertJSValueToByteString(cx, args[0], false, arg0)) {
    return false;
  }
  nsCString arg1;
  if (!ConvertJSValueToByteString(cx, args[1], false, arg1)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  self->Append(Constify(arg0), Constify(arg1), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo append_methodinfo = {
  { (JSJitGetterOp)append },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
_delete_(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 1)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "Headers.delete");
  }
  nsCString arg0;
  if (!ConvertJSValueToByteString(cx, args[0], false, arg0)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  self->Delete(Constify(arg0), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo delete_methodinfo = {
  { (JSJitGetterOp)_delete_ },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
get(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 1)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "Headers.get");
  }
  nsCString arg0;
  if (!ConvertJSValueToByteString(cx, args[0], false, arg0)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  nsCString result;
  self->Get(Constify(arg0), result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ByteStringToJsval(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo get_methodinfo = {
  { (JSJitGetterOp)get },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNKNOWN,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
has(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 1)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "Headers.has");
  }
  nsCString arg0;
  if (!ConvertJSValueToByteString(cx, args[0], false, arg0)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  bool result(self->Has(Constify(arg0), rv));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setBoolean(result);
  return true;
}

static const JSJitInfo has_methodinfo = {
  { (JSJitGetterOp)has },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_BOOLEAN,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
set(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 2)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "Headers.set");
  }
  nsCString arg0;
  if (!ConvertJSValueToByteString(cx, args[0], false, arg0)) {
    return false;
  }
  nsCString arg1;
  if (!ConvertJSValueToByteString(cx, args[1], false, arg1)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  self->Set(Constify(arg0), Constify(arg1), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo set_methodinfo = {
  { (JSJitGetterOp)set },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
get_guard(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, JSJitGetterCallArgs args)
{
  HeadersGuardEnum result(self->Guard());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static bool
set_guard(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, JSJitSetterCallArgs args)
{
  HeadersGuardEnum arg0;
  {
    int index;
    if (!FindEnumStringIndex<false>(cx, args[0], HeadersGuardEnumValues::strings, "HeadersGuardEnum", "Value being assigned to Headers.guard", &index)) {
      return false;
    }
    if (index < 0) {
      return true;
    }
    arg0 = static_cast<HeadersGuardEnum>(index);
  }
  binding_detail::FastErrorResult rv;
  self->SetGuard(arg0, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));

  return true;
}

static const JSJitInfo guard_getterinfo = {
  { (JSJitGetterOp)get_guard },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_STRING,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");
static const JSJitInfo guard_setterinfo = {
  { (JSJitGetterOp)set_guard },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Setter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
entries(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  typedef mozilla::dom::IterableIterator<mozilla::dom::Headers> itrType;
  RefPtr<itrType> result(new itrType(self,
                                       itrType::IterableIteratorType::Entries,
                                       &HeadersIteratorBinding::Wrap));
  static_assert(!IsPointer<decltype(result)>::value,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!WrapNewBindingNonWrapperCachedObject(cx, obj, result, args.rval())) {
    MOZ_ASSERT(true || JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo::ArgType entries_methodinfo_argTypes[] = { JSJitInfo::ArgTypeListEnd };
static const JSTypedMethodJitInfo entries_methodinfo = {
  {
    { (JSJitGetterOp)entries },
    { prototypes::id::Headers },
    { PrototypeTraits<prototypes::id::Headers>::Depth },
    JSJitInfo::Method,
    JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
    JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
    false,  /* isInfallible. False in setters. */
    false,  /* isMovable.  Not relevant for setters. */
    false, /* isEliminatable.  Not relevant for setters. */
    false, /* isAlwaysInSlot.  Only relevant for getters. */
    false, /* isLazilyCachedInSlot.  Only relevant for getters. */
    true,  /* isTypedMethod.  Only relevant for methods. */
    0   /* Reserved slot index, if we're stored in a slot, else 0. */
  },
  entries_methodinfo_argTypes
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
keys(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  typedef mozilla::dom::IterableIterator<mozilla::dom::Headers> itrType;
  RefPtr<itrType> result(new itrType(self,
                                       itrType::IterableIteratorType::Keys,
                                       &HeadersIteratorBinding::Wrap));
  static_assert(!IsPointer<decltype(result)>::value,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!WrapNewBindingNonWrapperCachedObject(cx, obj, result, args.rval())) {
    MOZ_ASSERT(true || JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo::ArgType keys_methodinfo_argTypes[] = { JSJitInfo::ArgTypeListEnd };
static const JSTypedMethodJitInfo keys_methodinfo = {
  {
    { (JSJitGetterOp)keys },
    { prototypes::id::Headers },
    { PrototypeTraits<prototypes::id::Headers>::Depth },
    JSJitInfo::Method,
    JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
    JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
    false,  /* isInfallible. False in setters. */
    false,  /* isMovable.  Not relevant for setters. */
    false, /* isEliminatable.  Not relevant for setters. */
    false, /* isAlwaysInSlot.  Only relevant for getters. */
    false, /* isLazilyCachedInSlot.  Only relevant for getters. */
    true,  /* isTypedMethod.  Only relevant for methods. */
    0   /* Reserved slot index, if we're stored in a slot, else 0. */
  },
  keys_methodinfo_argTypes
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
values(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  typedef mozilla::dom::IterableIterator<mozilla::dom::Headers> itrType;
  RefPtr<itrType> result(new itrType(self,
                                       itrType::IterableIteratorType::Values,
                                       &HeadersIteratorBinding::Wrap));
  static_assert(!IsPointer<decltype(result)>::value,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!WrapNewBindingNonWrapperCachedObject(cx, obj, result, args.rval())) {
    MOZ_ASSERT(true || JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo::ArgType values_methodinfo_argTypes[] = { JSJitInfo::ArgTypeListEnd };
static const JSTypedMethodJitInfo values_methodinfo = {
  {
    { (JSJitGetterOp)values },
    { prototypes::id::Headers },
    { PrototypeTraits<prototypes::id::Headers>::Depth },
    JSJitInfo::Method,
    JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
    JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
    false,  /* isInfallible. False in setters. */
    false,  /* isMovable.  Not relevant for setters. */
    false, /* isEliminatable.  Not relevant for setters. */
    false, /* isAlwaysInSlot.  Only relevant for getters. */
    false, /* isLazilyCachedInSlot.  Only relevant for getters. */
    true,  /* isTypedMethod.  Only relevant for methods. */
    0   /* Reserved slot index, if we're stored in a slot, else 0. */
  },
  values_methodinfo_argTypes
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
forEach(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::Headers* self, const JSJitMethodCallArgs& args)
{
  JS::Rooted<JSObject*> arg0(cx);
  if (args.get(0).isObject()) {
    arg0 = &args.get(0).toObject();
  } else {
    ThrowErrorMessage(cx, MSG_NOT_OBJECT, "Argument 1 of Headers.forEach");
    return false;
  }
  JS::Rooted<JS::Value> arg1(cx);
  if (args.hasDefined(1)) {
    arg1 = args.get(1);
  } else {
    arg1 = JS::UndefinedValue();
  }
  if (!JS::IsCallable(arg0)) {
    ThrowErrorMessage(cx, MSG_NOT_CALLABLE, "Argument 1 of Headers.forEach");
    return false;
  }
  JS::AutoValueArray<3> callArgs(cx);
  callArgs[2].setObject(*obj);
  JS::Rooted<JS::Value> ignoredReturnVal(cx);
  for (size_t i = 0; i < self->GetIterableLength(); ++i) {
    if (!ToJSValue(cx, self->GetValueAtIndex(i), callArgs[0])) {
      return false;
    }
    if (!ToJSValue(cx, self->GetKeyAtIndex(i), callArgs[1])) {
      return false;
    }
    if (!JS::Call(cx, arg1, arg0, JS::HandleValueArray(callArgs),
                  &ignoredReturnVal)) {
      return false;
    }
  }
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo forEach_methodinfo = {
  { (JSJitGetterOp)forEach },
  { prototypes::id::Headers },
  { PrototypeTraits<prototypes::id::Headers>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
_addProperty(JSContext* cx, JS::Handle<JSObject*> obj, JS::Handle<jsid> id, JS::Handle<JS::Value> val)
{
  mozilla::dom::Headers* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::Headers>(obj);
  // We don't want to preserve if we don't have a wrapper, and we
  // obviously can't preserve if we're not initialized.
  if (self && self->GetWrapperPreserveColor()) {
    PreserveWrapper(self);
  }
  return true;
}

static void
_finalize(js::FreeOp* fop, JSObject* obj)
{
  mozilla::dom::Headers* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::Headers>(obj);
  if (self) {
    ClearWrapper(self, self);
    AddForDeferredFinalization<mozilla::dom::Headers>(self);
  }
}

static void
_objectMoved(JSObject* obj, const JSObject* old)
{
  mozilla::dom::Headers* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::Headers>(obj);
  if (self) {
    UpdateWrapper(self, self, obj, old);
  }
}

static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("append", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&append_methodinfo), 2, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("delete", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&delete_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("get", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&get_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("has", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&has_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("set", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&set_methodinfo), 2, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("entries", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&entries_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("keys", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&keys_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("values", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&values_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("forEach", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&forEach_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


// Can't be const because the pref-enabled boolean needs to be writable
static Prefable<const JSFunctionSpec> sMethods[] = {
  { nullptr, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static jsid sMethods_ids[10];

static const JSPropertySpec sChromeAttributes_specs[] = {
  { "guard", JSPROP_SHARED | JSPROP_ENUMERATE, { { { { GenericBindingGetter, &guard_getterinfo } }, { { GenericBindingSetter, &guard_setterinfo } } } } },
  JS_PS_END
};


// Can't be const because the pref-enabled boolean needs to be writable
static Prefable<const JSPropertySpec> sChromeAttributes[] = {
  { nullptr, &sChromeAttributes_specs[0] },
  { nullptr, nullptr }
};

static jsid sChromeAttributes_ids[2];


static const NativePropertiesN<1> sNativeProperties = {
  5,
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  {
    { sMethods, sMethods_ids, sMethods_specs }
  }
};

static const NativePropertiesN<1> sChromeOnlyNativeProperties = {
  5,
  false, 0,
  false, 0,
  false, 0,
  true,  0 /* sChromeAttributes */,
  false, 0,
  false, 0,
  false, 0,
  {
    { sChromeAttributes, sChromeAttributes_ids, sChromeAttributes_specs }
  }
};

static bool
_constructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::Rooted<JSObject*> obj(cx, &args.callee());
  if (!args.isConstructing()) {
    // XXXbz wish I could get the name from the callee instead of
    // Adding more relocations
    return ThrowConstructorWithoutNew(cx, "Headers");
  }
  JS::Rooted<JSObject*> desiredProto(cx);
  if (!GetDesiredProto(cx, args, &desiredProto)) {
    return false;
  }

  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  Optional<HeadersOrByteStringSequenceSequenceOrByteStringMozMap> arg0;
  Maybe<HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument> arg0_holder;
  if (args.hasDefined(0)) {
    arg0.Construct();
    arg0_holder.emplace(arg0.Value());
    {
      bool done = false, failed = false, tryNext;
      if (args[0].isObject()) {
        done = (failed = !arg0_holder.ref().TrySetToHeaders(cx, args[0], tryNext, false)) || !tryNext;

        if (!done) {
          done = (failed = !arg0_holder.ref().TrySetToByteStringSequenceSequence(cx, args[0], tryNext, false)) || !tryNext;
        }
        if (!done) {
          done = (failed = !arg0_holder.ref().TrySetToByteStringMozMap(cx, args[0], tryNext, false)) || !tryNext;
        }
      }
      if (failed) {
        return false;
      }
      if (!done) {
        ThrowErrorMessage(cx, MSG_NOT_IN_UNION, "Argument 1 of Headers.constructor", "Headers, ByteStringSequenceSequence, ByteStringMozMap");
        return false;
      }
    }
  }
  Maybe<JSAutoCompartment> ac;
  if (objIsXray) {
    obj = js::CheckedUnwrap(obj);
    if (!obj) {
      return false;
    }
    ac.emplace(cx, obj);
    if (!JS_WrapObject(cx, &desiredProto)) {
      return false;
    }
  }
  binding_detail::FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::Headers>(mozilla::dom::Headers::Constructor(global, Constify(arg0), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!IsPointer<decltype(result)>::value,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
    MOZ_ASSERT(true || JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const js::ClassOps sInterfaceObjectClassOps = {
    nullptr,               /* addProperty */
    nullptr,               /* delProperty */
    nullptr,               /* getProperty */
    nullptr,               /* setProperty */
    nullptr,               /* enumerate */
    nullptr,               /* resolve */
    nullptr,               /* mayResolve */
    nullptr,               /* finalize */
    _constructor, /* call */
    nullptr,               /* hasInstance */
    _constructor, /* construct */
    nullptr,               /* trace */
};

static const DOMIfaceAndProtoJSClass sInterfaceObjectClass = {
  {
    "Function",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_SLOTS_BASE),
    &sInterfaceObjectClassOps,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    &sInterfaceObjectClassObjectOps
  },
  eInterface,
  true,
  prototypes::id::Headers,
  PrototypeTraits<prototypes::id::Headers>::Depth,
  sNativePropertyHooks,
  "function Headers() {\n    [native code]\n}",
  JS::GetRealmFunctionPrototype
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "HeadersPrototype",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eInterfacePrototype,
  false,
  prototypes::id::Headers,
  PrototypeTraits<prototypes::id::Headers>::Depth,
  sNativePropertyHooks,
  "[object HeadersPrototype]",
  JS::GetRealmObjectPrototype
};

JSObject*
DefineDOMInterface(JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::Handle<jsid> id, bool aDefineOnGlobal)
{
  return GetConstructorObjectHandle(aCx, aDefineOnGlobal);
}

static const js::ClassOps sClassOps = {
  _addProperty, /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* getProperty */
  nullptr,               /* setProperty */
  nullptr, /* enumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* hasInstance */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const js::ClassExtension sClassExtension = {
  nullptr, /* weakmapKeyDelegateOp */
  _objectMoved /* objectMovedOp */
};

static const DOMJSClass sClass = {
  { "Headers",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1),
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::Headers, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  IsBaseOf<nsISupports, mozilla::dom::Headers >::value,
  sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::Headers>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::Headers>::Get()
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

const JSClass*
GetJSClass()
{
  return sClass.ToJSClass();
}

bool
Wrap(JSContext* aCx, mozilla::dom::Headers* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  MOZ_ASSERT(static_cast<mozilla::dom::Headers*>(aObject) ==
             reinterpret_cast<mozilla::dom::Headers*>(aObject),
             "Multiple inheritance for mozilla::dom::Headers is broken.");
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));
  MOZ_ASSERT(!aCache->GetWrapper(),
             "You should probably not be using Wrap() directly; use "
             "GetOrCreateDOMReflector instead");

  MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache),
             "nsISupports must be on our primary inheritance chain");

  JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
  if (!global) {
    return false;
  }
  MOZ_ASSERT(JS_IsGlobalObject(global));
  MOZ_ASSERT(!JS::ObjectIsMarkedGray(global));

  // That might have ended up wrapping us already, due to the wonders
  // of XBL.  Check for that, and bail out as needed.
  aReflector.set(aCache->GetWrapper());
  if (aReflector) {
#ifdef DEBUG
    binding_detail::AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
    return true;
  }

  JSAutoCompartment ac(aCx, global);
  JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
  if (!canonicalProto) {
    return false;
  }
  JS::Rooted<JSObject*> proto(aCx);
  if (aGivenProto) {
    proto = aGivenProto;
    // Unfortunately, while aGivenProto was in the compartment of aCx
    // coming in, we changed compartments to that of "parent" so may need
    // to wrap the proto here.
    if (js::GetContextCompartment(aCx) != js::GetObjectCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

  BindingJSObjectCreator<mozilla::dom::Headers> creator(aCx);
  creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
  if (!aReflector) {
    return false;
  }

  aCache->SetWrapper(aReflector);
  creator.InitializationSucceeded();

  MOZ_ASSERT(aCache->GetWrapperPreserveColor() &&
             aCache->GetWrapperPreserveColor() == aReflector);
  // If proto != canonicalProto, we have to preserve our wrapper;
  // otherwise we won't be able to properly recreate it later, since
  // we won't know what proto to use.  Note that we don't check
  // aGivenProto here, since it's entirely possible (and even
  // somewhat common) to have a non-null aGivenProto which is the
  // same as canonicalProto.
  if (proto != canonicalProto) {
    PreserveWrapper(aObject);
  }

  return true;
}

const NativePropertyHooks sNativePropertyHooks[] = { {
  nullptr,
  nullptr,
  nullptr,
  { sNativeProperties.Upcast(), sChromeOnlyNativeProperties.Upcast() },
  prototypes::id::Headers,
  constructors::id::Headers,
  nullptr,
  &DefaultXrayExpandoObjectClass
} };

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, bool aDefineOnGlobal)
{
  JS::Rooted<JSObject*> parentProto(aCx, JS::GetRealmObjectPrototype(aCx));
  if (!parentProto) {
    return;
  }

  JS::Rooted<JSObject*> constructorProto(aCx, JS::GetRealmFunctionPrototype(aCx));
  if (!constructorProto) {
    return;
  }

  static bool sIdsInited = false;
  if (!sIdsInited && NS_IsMainThread()) {
    if (!InitIds(aCx, sMethods, sMethods_ids)) {
      return;
    }
    if (!InitIds(aCx, sChromeAttributes, sChromeAttributes_ids)) {
      return;
    }
    sIdsInited = true;
  }

  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::Headers);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::Headers);
  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass.mBase, protoCache,
                              constructorProto, &sInterfaceObjectClass.mBase, 0, nullptr,
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nsContentUtils::ThreadsafeIsCallerChrome() ? sChromeOnlyNativeProperties.Upcast() : nullptr,
                              "Headers", aDefineOnGlobal,
                              nullptr,
                              false);

  // Set up aliases on the interface prototype object we just created.
  JS::Handle<JSObject*> proto = GetProtoObjectHandle(aCx);
  if (!proto) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }

  JS::Rooted<JS::Value> aliasedVal(aCx);

  if (!JS_GetProperty(aCx, proto, "entries", &aliasedVal)) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }
  JS::Rooted<jsid> iteratorId(aCx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(aCx, JS::SymbolCode::iterator)));
  if (!JS_DefinePropertyById(aCx, proto, iteratorId, aliasedVal, JSPROP_ENUMERATE)) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }
}

JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  bool aDefineOnGlobal = true;

  /* Make sure our global is sane.  Hopefully we can remove this sometime */
  JSObject* global = JS::CurrentGlobalOrNull(aCx);
  if (!(js::GetObjectClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
    return nullptr;
  }

  /* Check to see whether the interface objects are already installed */
  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
  if (!protoAndIfaceCache.EntrySlotIfExists(prototypes::id::Headers)) {
    JS::Rooted<JSObject*> rootedGlobal(aCx, global);
    CreateInterfaceObjects(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
  }

  /*
   * The object might _still_ be null, but that's OK.
   *
   * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
   * traced by TraceProtoAndIfaceCache() and its contents are never
   * changed after they have been set.
   *
   * Calling address() avoids the read read barrier that does gray
   * unmarking, but it's not possible for the object to be gray here.
   */

  const JS::Heap<JSObject*>& entrySlot = protoAndIfaceCache.EntrySlotMustExist(prototypes::id::Headers);
  MOZ_ASSERT_IF(entrySlot, !JS::ObjectIsMarkedGray(entrySlot));
  return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}

JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx, bool aDefineOnGlobal)
{
  /* Get the interface object for this class.  This will create the object as
     needed. */

  /* Make sure our global is sane.  Hopefully we can remove this sometime */
  JSObject* global = JS::CurrentGlobalOrNull(aCx);
  if (!(js::GetObjectClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
    return nullptr;
  }

  /* Check to see whether the interface objects are already installed */
  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
  if (!protoAndIfaceCache.EntrySlotIfExists(constructors::id::Headers)) {
    JS::Rooted<JSObject*> rootedGlobal(aCx, global);
    CreateInterfaceObjects(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
  }

  /*
   * The object might _still_ be null, but that's OK.
   *
   * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
   * traced by TraceProtoAndIfaceCache() and its contents are never
   * changed after they have been set.
   *
   * Calling address() avoids the read read barrier that does gray
   * unmarking, but it's not possible for the object to be gray here.
   */

  const JS::Heap<JSObject*>& entrySlot = protoAndIfaceCache.EntrySlotMustExist(constructors::id::Headers);
  MOZ_ASSERT_IF(entrySlot, !JS::ObjectIsMarkedGray(entrySlot));
  return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}

JSObject*
GetConstructorObject(JSContext* aCx)
{
  return GetConstructorObjectHandle(aCx);
}

} // namespace HeadersBinding



namespace HeadersIteratorBinding {

static bool
next(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::IterableIterator<mozilla::dom::Headers>* self, const JSJitMethodCallArgs& args)
{
  binding_detail::FastErrorResult rv;
  JS::Rooted<JSObject*> result(cx);
  self->Next(cx, &result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  JS::ExposeObjectToActiveJS(result);
  args.rval().setObject(*result);
  if (!MaybeWrapObjectValue(cx, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo next_methodinfo = {
  { (JSJitGetterOp)next },
  { prototypes::id::HeadersIterator },
  { PrototypeTraits<prototypes::id::HeadersIterator>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static void
_finalize(js::FreeOp* fop, JSObject* obj)
{
  mozilla::dom::IterableIterator<mozilla::dom::Headers>* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::IterableIterator<mozilla::dom::Headers>>(obj);
  if (self) {
    AddForDeferredFinalization<mozilla::dom::IterableIterator<mozilla::dom::Headers>>(self);
  }
}

static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("next", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&next_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


// Can't be const because the pref-enabled boolean needs to be writable
static Prefable<const JSFunctionSpec> sMethods[] = {
  { nullptr, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static jsid sMethods_ids[2];


static const NativePropertiesN<1> sNativeProperties = {
  -1,
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  {
    { sMethods, sMethods_ids, sMethods_specs }
  }
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "HeadersIteratorPrototype",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eInterfacePrototype,
  false,
  prototypes::id::HeadersIterator,
  PrototypeTraits<prototypes::id::HeadersIterator>::Depth,
  sNativePropertyHooks,
  "[object HeadersIteratorPrototype]",
  JS::GetRealmIteratorPrototype
};

static const js::ClassOps sClassOps = {
  nullptr, /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* getProperty */
  nullptr,               /* setProperty */
  nullptr, /* enumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* hasInstance */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const js::ClassExtension sClassExtension = {
  nullptr, /* weakmapKeyDelegateOp */
  nullptr /* objectMovedOp */
};

static const DOMJSClass sClass = {
  { "HeadersIterator",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1),
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::HeadersIterator, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  IsBaseOf<nsISupports, mozilla::dom::IterableIterator<mozilla::dom::Headers> >::value,
  sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::IterableIterator<mozilla::dom::Headers>>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::IterableIterator<mozilla::dom::Headers>>::Get()
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

const JSClass*
GetJSClass()
{
  return sClass.ToJSClass();
}

bool
Wrap(JSContext* aCx, mozilla::dom::IterableIterator<mozilla::dom::Headers>* aObject, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  MOZ_ASSERT(static_cast<mozilla::dom::IterableIterator<mozilla::dom::Headers>*>(aObject) ==
             reinterpret_cast<mozilla::dom::IterableIterator<mozilla::dom::Headers>*>(aObject),
             "Multiple inheritance for mozilla::dom::IterableIterator<mozilla::dom::Headers> is broken.");
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));

  JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
  JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
  if (!canonicalProto) {
    return false;
  }
  JS::Rooted<JSObject*> proto(aCx);
  if (aGivenProto) {
    proto = aGivenProto;
    // Unfortunately, while aGivenProto was in the compartment of aCx
    // coming in, we changed compartments to that of "parent" so may need
    // to wrap the proto here.
    if (js::GetContextCompartment(aCx) != js::GetObjectCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

  BindingJSObjectCreator<mozilla::dom::IterableIterator<mozilla::dom::Headers>> creator(aCx);
  creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
  if (!aReflector) {
    return false;
  }



  creator.InitializationSucceeded();
  return true;
}

const NativePropertyHooks sNativePropertyHooks[] = { {
  nullptr,
  nullptr,
  nullptr,
  { sNativeProperties.Upcast(), nullptr },
  prototypes::id::HeadersIterator,
  constructors::id::_ID_Count,
  nullptr,
  &DefaultXrayExpandoObjectClass
} };

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, bool aDefineOnGlobal)
{
  JS::Rooted<JSObject*> parentProto(aCx, JS::GetRealmIteratorPrototype(aCx));
  if (!parentProto) {
    return;
  }

  static bool sIdsInited = false;
  if (!sIdsInited && NS_IsMainThread()) {
    if (!InitIds(aCx, sMethods, sMethods_ids)) {
      return;
    }
    sIdsInited = true;
  }

  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::HeadersIterator);
  JS::Heap<JSObject*>* interfaceCache = nullptr;
  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass.mBase, protoCache,
                              nullptr, nullptr, 0, nullptr,
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              nullptr, aDefineOnGlobal,
                              nullptr,
                              false);
}

JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  bool aDefineOnGlobal = true;

  /* Make sure our global is sane.  Hopefully we can remove this sometime */
  JSObject* global = JS::CurrentGlobalOrNull(aCx);
  if (!(js::GetObjectClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
    return nullptr;
  }

  /* Check to see whether the interface objects are already installed */
  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
  if (!protoAndIfaceCache.EntrySlotIfExists(prototypes::id::HeadersIterator)) {
    JS::Rooted<JSObject*> rootedGlobal(aCx, global);
    CreateInterfaceObjects(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
  }

  /*
   * The object might _still_ be null, but that's OK.
   *
   * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
   * traced by TraceProtoAndIfaceCache() and its contents are never
   * changed after they have been set.
   *
   * Calling address() avoids the read read barrier that does gray
   * unmarking, but it's not possible for the object to be gray here.
   */

  const JS::Heap<JSObject*>& entrySlot = protoAndIfaceCache.EntrySlotMustExist(prototypes::id::HeadersIterator);
  MOZ_ASSERT_IF(entrySlot, !JS::ObjectIsMarkedGray(entrySlot));
  return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}

} // namespace HeadersIteratorBinding



} // namespace dom
} // namespace mozilla
