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

#include <type_traits>
#include "ImageDataBinding.h"
#include "MainThreadUtils.h"
#include "WrapperFactory.h"
#include "XrayWrapper.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/experimental/JitInfo.h"
#include "js/shadow/Object.h"
#include "jsfriendapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/ImageData.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/StructuredCloneTags.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsJSUtils.h"

namespace mozilla::dom {

namespace binding_detail {}; // Just to make sure it's known as a namespace
using namespace mozilla::dom::binding_detail;


namespace ImageData_Binding {

MOZ_CAN_RUN_SCRIPT static bool
get_width(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ImageData", "width", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ImageData*>(void_self);
  uint32_t result(MOZ_KnownLive(self)->Width());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setNumber(result);
  return true;
}

static const JSJitInfo width_getterinfo = {
  { get_width },
  { prototypes::id::ImageData },
  { PrototypeTraits<prototypes::id::ImageData>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasNone, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_DOUBLE,  /* returnType.  Not relevant for setters. */
  true,  /* isInfallible. False in setters. */
  true,  /* isMovable.  Not relevant for setters. */
  true, /* 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. */
};

MOZ_CAN_RUN_SCRIPT static bool
get_height(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ImageData", "height", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ImageData*>(void_self);
  uint32_t result(MOZ_KnownLive(self)->Height());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setNumber(result);
  return true;
}

static const JSJitInfo height_getterinfo = {
  { get_height },
  { prototypes::id::ImageData },
  { PrototypeTraits<prototypes::id::ImageData>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasNone, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_DOUBLE,  /* returnType.  Not relevant for setters. */
  true,  /* isInfallible. False in setters. */
  true,  /* isMovable.  Not relevant for setters. */
  true, /* 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 bool
get_data(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ImageData", "data", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ImageData*>(void_self);
  // Have to either root across the getter call or reget after.
  bool isXray;
  JS::Rooted<JSObject*> slotStorage(cx, GetCachedSlotStorageObject(cx, obj, &isXray));
  if (!slotStorage) {
    return false;
  }
  const size_t slotIndex = isXray ? (DOM_EXPANDO_RESERVED_SLOTS + 0) : (DOM_INSTANCE_RESERVED_SLOTS + 0);
  MOZ_ASSERT(slotIndex < JSCLASS_RESERVED_SLOTS(JS::GetClass(slotStorage)));
  {
    // Scope for cachedVal
    JS::Value cachedVal = JS::GetReservedSlot(slotStorage, slotIndex);
    if (!cachedVal.isUndefined()) {
      args.rval().set(cachedVal);
      // The cached value is in the compartment of slotStorage,
      // so wrap into the caller compartment as needed.
      return MaybeWrapNonDOMObjectValue(cx, args.rval());
    }
  }

  JS::Rooted<JSObject*> result(cx);
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetData(cx, &result))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetData(cx, &result);
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  {
    JS::Rooted<JSObject*> conversionScope(cx, isXray ? JS::CurrentGlobalOrNull(cx) : slotStorage);
    JSAutoRealm ar(cx, conversionScope);
    do { // block we break out of when done wrapping
      JS::ExposeObjectToActiveJS(result);
      args.rval().setObject(*result);
      if (!MaybeWrapNonDOMObjectValue(cx, args.rval())) {
        return false;
      }
      break;
    } while (false);
  }
  { // And now store things in the realm of our slotStorage.
    JSAutoRealm ar(cx, slotStorage);
    // Make a copy so that we don't do unnecessary wrapping on args.rval().
    JS::Rooted<JS::Value> storedVal(cx, args.rval());
    if (!MaybeWrapNonDOMObjectValue(cx, &storedVal)) {
      return false;
    }
    JS::SetReservedSlot(slotStorage, slotIndex, storedVal);
  }
  // And now make sure args.rval() is in the caller realm.
  return MaybeWrapNonDOMObjectValue(cx, args.rval());
}

static const JSJitInfo data_getterinfo = {
  { get_data },
  { prototypes::id::ImageData },
  { PrototypeTraits<prototypes::id::ImageData>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasNone, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  true,  /* isMovable.  Not relevant for setters. */
  true, /* isEliminatable.  Not relevant for setters. */
  true, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  (DOM_INSTANCE_RESERVED_SLOTS + 0)   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) < 2, "There is no slot for us");

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::ImageData* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::ImageData>(obj);
  if (self) {
    JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
    ClearWrapper(self, self, obj);
    if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
      JS::RemoveAssociatedMemory(obj, mallocBytes,
                                 JS::MemoryUse::DOMBinding);
    }
    AddForDeferredFinalization<mozilla::dom::ImageData>(self);
  }
}

MOZ_GLOBINIT static const JSPropertySpec sAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("width", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &width_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("height", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &height_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("data", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &data_getterinfo, nullptr, nullptr),
  JS_PS_END
};


static const Prefable<const JSPropertySpec> sAttributes[] = {
  { nullptr, &sAttributes_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(3 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");


static uint16_t sNativeProperties_sortedPropertyIndices[3];
static PropertyInfo sNativeProperties_propertyInfos[3];

static const NativePropertiesN<1> sNativeProperties = {
  false, 0,
  false, 0,
  false, 0,
  true,  0 /* sAttributes */,
  false, 0,
  false, 0,
  false, 0,
  -1,
  3,
  sNativeProperties_sortedPropertyIndices,
  {
    { sAttributes, &sNativeProperties_propertyInfos[0] }
  }
};
static_assert(3 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

// This may allocate too many slots, because we only really need
// slots for our non-interface-typed members that we cache.  But
// allocating slots only for those would make the slot index
// computations much more complicated, so let's do this the simple
// way for now.
DEFINE_XRAY_EXPANDO_CLASS_WITH_OPS(static, sXrayExpandoObjectClass, 1,
                                   &xpc::XrayExpandoObjectClassOps);

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
  prototypes::id::ImageData,
  constructors::id::ImageData,
  &sXrayExpandoObjectClass
};

static bool
_constructor(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "ImageData constructor");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ImageData", "constructor", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::Rooted<JSObject*> obj(cx, &args.callee());
  if (!args.isConstructing()) {
    return ThrowConstructorWithoutNew(cx, "ImageData");
  }

  JS::Rooted<JSObject*> desiredProto(cx);
  if (!GetDesiredProto(cx, args,
                       prototypes::id::ImageData,
                       CreateInterfaceObjects,
                       &desiredProto)) {
    return false;
  }

  unsigned argcount = std::min(args.length(), 3u);
  switch (argcount) {
    case 2: {
      if (args[0].isObject()) {
        do {
          RootedSpiderMonkeyInterface<Uint8ClampedArray> arg0(cx);
          if (!arg0.Init(&args[0].toObject())) {
            break;
          }
          if (JS::IsArrayBufferViewShared(arg0.Obj())) {
            cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Argument 1");
            return false;
          }
          if (JS::IsLargeArrayBufferView(arg0.Obj())) {
            cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Argument 1");
            return false;
          }
          if (JS::IsResizableArrayBufferView(arg0.Obj())) {
            cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Argument 1");
            return false;
          }
          if (JS::IsImmutableArrayBufferView(arg0.Obj())) {
            cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Argument 1");
            return false;
          }
          GlobalObject global(cx, obj);
          if (global.Failed()) {
            return false;
          }

          bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
          uint32_t arg1;
          if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[1], "Argument 2", &arg1)) {
            return false;
          }
          Optional<uint32_t> arg2;
          if (args.hasDefined(2)) {
            arg2.Construct();
            if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[2], "Argument 3", &arg2.Value())) {
              return false;
            }
          }
          Maybe<JSAutoRealm> ar;
          if (objIsXray) {
            // Since our object is an Xray, we can just CheckedUnwrapStatic:
            // we know Xrays have no dynamic unwrap behavior.
            obj = js::CheckedUnwrapStatic(obj);
            if (!obj) {
              return false;
            }
            ar.emplace(cx, obj);
            if (!JS_WrapObject(cx, &desiredProto)) {
              return false;
            }
            if (!arg0.WrapIntoNewCompartment(cx)) {
              return false;
            }
          }
          FastErrorResult rv;
          auto result(StrongOrRawPtr<mozilla::dom::ImageData>(mozilla::dom::ImageData::Constructor(global, Constify(arg0), arg1, Constify(arg2), rv)));
          if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ImageData constructor"))) {
            return false;
          }
          MOZ_ASSERT(!JS_IsExceptionPending(cx));
          static_assert(!std::is_pointer_v<decltype(result)>,
                        "NewObject implies that we need to keep the object alive with a strong reference.");
          if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
            MOZ_ASSERT(JS_IsExceptionPending(cx));
            return false;
          }
          return true;
        } while (false);
      }
      GlobalObject global(cx, obj);
      if (global.Failed()) {
        return false;
      }

      bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
      uint32_t arg0;
      if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
        return false;
      }
      uint32_t arg1;
      if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[1], "Argument 2", &arg1)) {
        return false;
      }
      Maybe<JSAutoRealm> ar;
      if (objIsXray) {
        // Since our object is an Xray, we can just CheckedUnwrapStatic:
        // we know Xrays have no dynamic unwrap behavior.
        obj = js::CheckedUnwrapStatic(obj);
        if (!obj) {
          return false;
        }
        ar.emplace(cx, obj);
        if (!JS_WrapObject(cx, &desiredProto)) {
          return false;
        }
      }
      FastErrorResult rv;
      auto result(StrongOrRawPtr<mozilla::dom::ImageData>(mozilla::dom::ImageData::Constructor(global, arg0, arg1, rv)));
      if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ImageData constructor"))) {
        return false;
      }
      MOZ_ASSERT(!JS_IsExceptionPending(cx));
      static_assert(!std::is_pointer_v<decltype(result)>,
                    "NewObject implies that we need to keep the object alive with a strong reference.");
      if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
      break;
    }
    case 3: {
      GlobalObject global(cx, obj);
      if (global.Failed()) {
        return false;
      }

      bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
      RootedSpiderMonkeyInterface<Uint8ClampedArray> arg0(cx);
      if (args[0].isObject()) {
        if (!arg0.Init(&args[0].toObject())) {
          cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 1", "Uint8ClampedArray");
          return false;
        }
        if (JS::IsArrayBufferViewShared(arg0.Obj())) {
          cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Argument 1");
          return false;
        }
        if (JS::IsLargeArrayBufferView(arg0.Obj())) {
          cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Argument 1");
          return false;
        }
        if (JS::IsResizableArrayBufferView(arg0.Obj())) {
          cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Argument 1");
          return false;
        }
        if (JS::IsImmutableArrayBufferView(arg0.Obj())) {
          cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Argument 1");
          return false;
        }
      } else {
        cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
        return false;
      }
      uint32_t arg1;
      if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[1], "Argument 2", &arg1)) {
        return false;
      }
      Optional<uint32_t> arg2;
      if (args.hasDefined(2)) {
        arg2.Construct();
        if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[2], "Argument 3", &arg2.Value())) {
          return false;
        }
      }
      Maybe<JSAutoRealm> ar;
      if (objIsXray) {
        // Since our object is an Xray, we can just CheckedUnwrapStatic:
        // we know Xrays have no dynamic unwrap behavior.
        obj = js::CheckedUnwrapStatic(obj);
        if (!obj) {
          return false;
        }
        ar.emplace(cx, obj);
        if (!JS_WrapObject(cx, &desiredProto)) {
          return false;
        }
        if (!arg0.WrapIntoNewCompartment(cx)) {
          return false;
        }
      }
      FastErrorResult rv;
      auto result(StrongOrRawPtr<mozilla::dom::ImageData>(mozilla::dom::ImageData::Constructor(global, Constify(arg0), arg1, Constify(arg2), rv)));
      if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ImageData constructor"))) {
        return false;
      }
      MOZ_ASSERT(!JS_IsExceptionPending(cx));
      static_assert(!std::is_pointer_v<decltype(result)>,
                    "NewObject implies that we need to keep the object alive with a strong reference.");
      if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
      break;
    }
    default: {
      // Using nsPrintfCString here would require including that
      // header.  Let's not worry about it.
      nsAutoCString argCountStr;
      argCountStr.AppendPrintf("%u", args.length());
      return cx.ThrowErrorMessage<MSG_INVALID_OVERLOAD_ARGCOUNT>(argCountStr.get());
    }
  }
  MOZ_CRASH("We have an always-returning default case");
  return false;
}

static const DOMInterfaceInfo sInterfaceObjectInfo = {
  { _constructor, &sNativePropertyHooks },
  JS::GetRealmFunctionPrototypeHandle,
  PrototypeTraits<prototypes::id::ImageData>::Depth,
  prototypes::id::ImageData,
  true,
  2,
  "ImageData",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "ImageDataPrototype",
    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,
  prototypes::id::ImageData,
  PrototypeTraits<prototypes::id::ImageData>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

static bool
Serialize(JSContext* aCx, JSStructuredCloneWriter* aWriter, JS::Handle<JSObject*> aObj)
{
  MOZ_ASSERT(IsDOMObject(aObj), "Non-DOM object passed");
  MOZ_ASSERT(GetDOMClass(aObj)->mSerializer == &Serialize,
             "Wrong object passed");
  return JS_WriteUint32Pair(aWriter, SCTAG_DOM_IMAGEDATA, 0) &&
         UnwrapDOMObject<mozilla::dom::ImageData>(aObj)->WriteStructuredClone(aCx, aWriter);
}

JSObject*
Deserialize(JSContext* aCx, nsIGlobalObject* aGlobal, JSStructuredCloneReader* aReader)
{
  // Protect the result from a moving GC in ~RefPtr
  JS::Rooted<JSObject*> result(aCx);
  {  // Scope for the RefPtr
    RefPtr<mozilla::dom::ImageData> obj = mozilla::dom::ImageData::ReadStructuredClone(aCx, aGlobal, aReader);
    if (!obj) {
      return nullptr;
    }
    result = obj->WrapObject(aCx, nullptr);
    if (!result) {
      return nullptr;
    }
  }
  return result;
}

static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx);

static const JSClassOps sClassOps = {
  nullptr,               /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* enumerate */
  nullptr, /* newEnumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const DOMJSClass sClass = {
  { "ImageData",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_SKIP_NURSERY_FINALIZE | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::ImageData>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::ImageData, 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 },
  std::is_base_of_v<nsISupports, mozilla::dom::ImageData>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::ImageData>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::ImageData>::Get(),
  Serialize,
  NativeTypeHelpers<mozilla::dom::ImageData>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(2 >= 2,
              "Must have enough reserved slots.");

static bool
UpdateMemberSlots(JSContext* aCx, JS::Handle<JSObject*> aWrapper, mozilla::dom::ImageData* aObject)
{
  JS::Rooted<JS::Value> temp(aCx);
  JSJitGetterCallArgs args(&temp);

  static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) < JS::shadow::Object::MAX_FIXED_SLOTS,
                "Not enough fixed slots to fit 'ImageData.data.  Ion's visitGetDOMMemberV/visitGetDOMMemberT assume StoreInSlot things are all in fixed slots.");
  if (!get_data(aCx, aWrapper, aObject, args)) {
    return false;
  }
  // Getter handled setting our reserved slots

  return true;
}

bool
Wrap(JSContext* aCx, mozilla::dom::ImageData* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::ImageData>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::ImageData*>);
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));
  MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx));
  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");

  // If the wrapper cache contains a dead reflector then finalize that
  // now, ensuring that the finalizer for the old reflector always
  // runs before the new reflector is created and attached. This
  // avoids the awkward situation where there are multiple reflector
  // objects that contain pointers to the same native.

  if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) {
    _finalize(nullptr /* unused */, oldReflector);
    MOZ_ASSERT(!aCache->GetWrapperMaybeDead());
  }

  JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
  if (!global) {
    return false;
  }
  MOZ_ASSERT(JS_IsGlobalObject(global));
  JS::AssertObjectIsNotGray(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
    AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
    return true;
  }

  JSAutoRealm ar(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::GetCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

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

  aCache->SetWrapper(aReflector);
  if (!UpdateMemberSlots(aCx, aReflector, aObject)) {
    aCache->ReleaseWrapper(aObject);
    aCache->ClearWrapper();
    return false;
  }
  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;
}

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::ImageData);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::ImageData);

  JS::Handle<JSObject*> parentProto(JS::GetRealmObjectPrototypeHandle(aCx));
  if (!parentProto) {
    return;
  }

  JS::Handle<JSObject*> constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx));
  if (!constructorProto) {
    return;
  }

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              constructorProto, &sInterfaceObjectInfo, 2, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "ImageData",
                              aDefineOnGlobal != DefineInterfaceProperty::No,
                              nullptr,
                              false,
                              nullptr);
}

static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  return GetPerInterfaceObjectHandle(aCx, prototypes::id::ImageData,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

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

  return GetPerInterfaceObjectHandle(aCx, constructors::id::ImageData,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace ImageData_Binding



} // namespace mozilla::dom
