/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * 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/. */ #include "js/WeakMapPtr.h" #include "gc/WeakMap-inl.h" // // Machinery for the externally-linkable JS::WeakMapPtr, which wraps js::WeakMap // for a few public data types. // using namespace js; namespace WeakMapDetails { template struct DataType {}; template <> struct DataType { using BarrieredType = HeapPtr; using HasherType = StableCellHasher; static JSObject* NullValue() { return nullptr; } }; template <> struct DataType { using BarrieredType = HeapPtr; static JS::Value NullValue() { return JS::UndefinedValue(); } }; template struct Utils { using KeyType = typename DataType::BarrieredType; using ValueType = typename DataType::BarrieredType; typedef WeakMap Type; using PtrType = Type*; static PtrType cast(void* ptr) { return static_cast(ptr); } }; } // namespace WeakMapDetails template void JS::WeakMapPtr::destroy() { MOZ_ASSERT(initialized()); js_delete(WeakMapDetails::Utils::cast(ptr)); ptr = nullptr; } template bool JS::WeakMapPtr::init(JSContext* cx) { MOZ_ASSERT(!initialized()); typename WeakMapDetails::Utils::PtrType map = cx->new_::Type>(cx); if (!map) { return false; } ptr = map; return true; } template void JS::WeakMapPtr::trace(JSTracer* trc) { MOZ_ASSERT(initialized()); return WeakMapDetails::Utils::cast(ptr)->trace(trc); } template V JS::WeakMapPtr::lookup(const K& key) { MOZ_ASSERT(initialized()); typename WeakMapDetails::Utils::Type::Ptr result = WeakMapDetails::Utils::cast(ptr)->lookup(key); if (!result) { return WeakMapDetails::DataType::NullValue(); } return result->value(); } template bool JS::WeakMapPtr::put(JSContext* cx, const K& key, const V& value) { MOZ_ASSERT(initialized()); return WeakMapDetails::Utils::cast(ptr)->put(key, value); } template V JS::WeakMapPtr::removeValue(const K& key) { typedef typename WeakMapDetails::Utils::Type Map; using Ptr = typename Map::Ptr; MOZ_ASSERT(initialized()); Map* map = WeakMapDetails::Utils::cast(ptr); if (Ptr result = map->lookup(key)) { V value = result->value(); map->remove(result); return value; } return WeakMapDetails::DataType::NullValue(); } // // Supported specializations of JS::WeakMap: // template class JS_PUBLIC_API JS::WeakMapPtr; #ifdef DEBUG // Nobody's using this at the moment, but we want to make sure it compiles. template class JS_PUBLIC_API JS::WeakMapPtr; #endif