void WebPreferences::setInstance(WebPreferences* instance, BSTR identifier)
{
    if (!identifier || !instance)
        return;
    WTF::String identifierString(identifier, SysStringLen(identifier));
    webPreferencesInstances.add(identifierString, instance);
}
Exemple #2
0
static void testMapMove()
{
	// Add 1000..1999 to a HashMap.
	HashMap<Uptr, Uptr> a;
	for(Uptr i = 0;i < 1000;++i)
	{
		a.add(i + 1000, i);
	}

	// Move the map to a new HashMap.
	HashMap<Uptr, Uptr> b {std::move(a)};

	// Test that the new HashMap contains the expected numbers.
	for(Uptr i = 0;i < 1000;++i)
	{
		errorUnless(!b.get(i));
		errorUnless(*b.get(i + 1000) == i);
		errorUnless(!b.get(i + 2000));
	}

	// Test moving the map to itself.
	b = std::move(b);
	
	// Test that the map wasn't changed by the move-to-self.
	for(Uptr i = 0;i < 1000;++i)
	{
		errorUnless(!b.get(i));
		errorUnless(*b.get(i + 1000) == i);
		errorUnless(!b.get(i + 2000));
	}
}
Exemple #3
0
static NEVER_INLINE void populateCSSPropertyWithSVGDOMNameToAnimatedPropertyTypeMap(HashMap<QualifiedName::QualifiedNameImpl*, AnimatedPropertyType>& map)
{
    using namespace HTMLNames;
    using namespace SVGNames;

    struct TableEntry {
        const QualifiedName& attributeName;
        AnimatedPropertyType type;
    };

    static const TableEntry table[] = {
        { cxAttr, AnimatedLength },
        { cyAttr, AnimatedLength },
        { rAttr, AnimatedLength },
        { rxAttr, AnimatedLength },
        { ryAttr, AnimatedLength },
        { SVGNames::heightAttr, AnimatedLength },
        { SVGNames::widthAttr, AnimatedLength },
        { xAttr, AnimatedLength },
        { yAttr, AnimatedLength },
    };

    for (auto& entry : table)
        map.add(entry.attributeName.impl(), entry.type);
}
TEST(TestHashMapRemove, addedItemThenRemoveItemHashMapShouldHave0items)
{
    HashMap Test;
    Test.add("Ford", "Tang");
    Test.remove("Ford");
    ASSERT_EQ(0, Test.size());
}
Exemple #5
0
bool IDBObjectStoreBackendLevelDB::makeIndexWriters(PassRefPtr<IDBTransactionBackendLevelDB> transaction, IDBBackingStore* backingStore, int64_t databaseId, const IDBObjectStoreMetadata& objectStore, PassRefPtr<IDBKey> primaryKey, bool keyWasGenerated, const Vector<int64_t>& indexIds, const Vector<IDBDatabaseBackendInterface::IndexKeys>& indexKeys, Vector<OwnPtr<IndexWriter> >* indexWriters, String* errorMessage, bool& completed)
{
    ASSERT(indexIds.size() == indexKeys.size());
    completed = false;

    HashMap<int64_t, IDBDatabaseBackendInterface::IndexKeys> indexKeyMap;
    for (size_t i = 0; i < indexIds.size(); ++i)
        indexKeyMap.add(indexIds[i], indexKeys[i]);

    for (IDBObjectStoreMetadata::IndexMap::const_iterator it = objectStore.indexes.begin(); it != objectStore.indexes.end(); ++it) {

        const IDBIndexMetadata& index = it->value;

        IDBDatabaseBackendInterface::IndexKeys keys = indexKeyMap.get(it->key);
        // If the objectStore is using autoIncrement, then any indexes with an identical keyPath need to also use the primary (generated) key as a key.
        if (keyWasGenerated && (index.keyPath == objectStore.keyPath))
            keys.append(primaryKey);

        OwnPtr<IndexWriter> indexWriter(adoptPtr(new IndexWriter(index, keys)));
        bool canAddKeys = false;
        bool backingStoreSuccess = indexWriter->verifyIndexKeys(*backingStore, transaction->backingStoreTransaction(), databaseId, objectStore.id, index.id, canAddKeys, primaryKey.get(), errorMessage);
        if (!backingStoreSuccess)
            return false;
        if (!canAddKeys)
            return true;

        indexWriters->append(indexWriter.release());
    }

    completed = true;
    return true;
}
Exemple #6
0
void HTMLImport::recalcTreeState(HTMLImport* root)
{
    HashMap<RawPtr<HTMLImport>, HTMLImportState> snapshot;
    Vector<RawPtr<HTMLImport> > updated;

    for (HTMLImport* i = root; i; i = traverseNext(i)) {
        snapshot.add(i, i->state());
        i->m_state = HTMLImportState::invalidState();
    }

    // The post-visit DFS order matters here because
    // HTMLImportStateResolver in recalcState() Depends on
    // |m_state| of its children and precedents of ancestors.
    // Accidental cycle dependency of state computation is prevented
    // by invalidateCachedState() and isStateCacheValid() check.
    for (HTMLImport* i = traverseFirstPostOrder(root); i; i = traverseNextPostOrder(i)) {
        ASSERT(!i->m_state.isValid());
        i->m_state = HTMLImportStateResolver(i).resolve();

        HTMLImportState newState = i->state();
        HTMLImportState oldState = snapshot.get(i);
        // Once the state reaches Ready, it shouldn't go back.
        ASSERT(!oldState.isReady() || oldState <= newState);
        if (newState != oldState)
            updated.append(i);
    }

    for (size_t i = 0; i < updated.size(); ++i)
        updated[i]->stateDidChange();
}
void WebNotificationManagerProxy::providerDidCloseNotifications(API::Array* globalNotificationIDs)
{
    HashMap<WebPageProxy*, Vector<uint64_t>> pageNotificationIDs;
    
    size_t size = globalNotificationIDs->size();
    for (size_t i = 0; i < size; ++i) {
        auto it = m_globalNotificationMap.find(globalNotificationIDs->at<API::UInt64>(i)->value());
        if (it == m_globalNotificationMap.end())
            continue;

        if (WebPageProxy* webPage = WebProcessProxy::webPage(it->value.first)) {
            auto pageIt = pageNotificationIDs.find(webPage);
            if (pageIt == pageNotificationIDs.end()) {
                Vector<uint64_t> newVector;
                newVector.reserveInitialCapacity(size);
                pageIt = pageNotificationIDs.add(webPage, WTF::move(newVector)).iterator;
            }

            uint64_t pageNotificationID = it->value.second;
            pageIt->value.append(pageNotificationID);
        }

        m_notifications.remove(it->value);
        m_globalNotificationMap.remove(it);
    }

    for (auto it = pageNotificationIDs.begin(), end = pageNotificationIDs.end(); it != end; ++it)
        it->key->process().send(Messages::WebNotificationManager::DidCloseNotifications(it->value), 0);
}
void WebFrameLoaderClient::dispatchWillSubmitForm(PassRefPtr<FormState> formState, FramePolicyFunction function)
{
    WebView* webView = m_webFrame->webView();
    Frame* coreFrame = core(m_webFrame);
    ASSERT(coreFrame);

    COMPtr<IWebFormDelegate> formDelegate;

    if (FAILED(webView->formDelegate(&formDelegate))) {
        function(PolicyUse);
        return;
    }

    COMPtr<IDOMElement> formElement(AdoptCOM, DOMElement::createInstance(formState->form()));

    HashMap<String, String> formValuesMap;
    const StringPairVector& textFieldValues = formState->textFieldValues();
    size_t size = textFieldValues.size();
    for (size_t i = 0; i < size; ++i)
        formValuesMap.add(textFieldValues[i].first, textFieldValues[i].second);

    COMPtr<IPropertyBag> formValuesPropertyBag(AdoptCOM, COMPropertyBag<String>::createInstance(formValuesMap));

    COMPtr<WebFrame> sourceFrame(kit(formState->sourceDocument()->frame()));
    if (SUCCEEDED(formDelegate->willSubmitForm(m_webFrame, sourceFrame.get(), formElement.get(), formValuesPropertyBag.get(), setUpPolicyListener(function).get())))
        return;

    // FIXME: Add a sane default implementation
    function(PolicyUse);
}
Exemple #9
0
void EventPath::calculateTreeScopePrePostOrderNumbers()
{
    // Precondition:
    //   - TreeScopes in m_treeScopeEventContexts must be *connected* in the same tree of trees.
    //   - The root tree must be included.
    HashMap<const TreeScope*, TreeScopeEventContext*> treeScopeEventContextMap;
    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i)
        treeScopeEventContextMap.add(&m_treeScopeEventContexts[i]->treeScope(), m_treeScopeEventContexts[i].get());
    TreeScopeEventContext* rootTree = 0;
    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
        TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
        // Use olderShadowRootOrParentTreeScope here for parent-child relationships.
        // See the definition of trees of trees in the Shado DOM spec: http://w3c.github.io/webcomponents/spec/shadow/
        TreeScope* parent = treeScopeEventContext->treeScope().olderShadowRootOrParentTreeScope();
        if (!parent) {
            ASSERT(!rootTree);
            rootTree = treeScopeEventContext;
            continue;
        }
        ASSERT(treeScopeEventContextMap.find(parent) != treeScopeEventContextMap.end());
        treeScopeEventContextMap.find(parent)->value->addChild(*treeScopeEventContext);
    }
    ASSERT(rootTree);
    rootTree->calculatePrePostOrderNumber(0);
}
void LocalStorageDatabase::updateDatabase()
{
    if (m_isClosed)
        return;

    ASSERT(m_didScheduleDatabaseUpdate);
    m_didScheduleDatabaseUpdate = false;

    HashMap<String, String> changedItems;
    if (m_changedItems.size() <= maximumItemsToUpdate) {
        // There are few enough changed items that we can just always write all of them.
        m_changedItems.swap(changedItems);
        updateDatabaseWithChangedItems(changedItems);
        m_disableSuddenTerminationWhileWritingToLocalStorage = nullptr;
    } else {
        for (int i = 0; i < maximumItemsToUpdate; ++i) {
            auto it = m_changedItems.begin();
            changedItems.add(it->key, it->value);

            m_changedItems.remove(it);
        }

        ASSERT(changedItems.size() <= maximumItemsToUpdate);

        // Reschedule the update for the remaining items.
        scheduleDatabaseUpdate();
        updateDatabaseWithChangedItems(changedItems);
    }
}
void AvailabilityMap::prune()
{
    if (m_heap.isEmpty())
        return;
    
    HashSet<Node*> possibleNodes;
    
    for (unsigned i = m_locals.size(); i--;) {
        if (m_locals[i].hasNode())
            possibleNodes.add(m_locals[i].node());
    }

    int oldPossibleNodesSize;
    do {
        oldPossibleNodesSize = possibleNodes.size();
        for (auto pair : m_heap) {
            if (pair.value.hasNode() && possibleNodes.contains(pair.key.base()))
                possibleNodes.add(pair.value.node());
        }
    } while (oldPossibleNodesSize != possibleNodes.size());
    
    HashMap<PromotedHeapLocation, Availability> newHeap;
    for (auto pair : m_heap) {
        if (possibleNodes.contains(pair.key.base()))
            newHeap.add(pair.key, pair.value);
    }
    m_heap = newHeap;
}
void findGoodTouchTargets(const IntRect& touchBox, LocalFrame* mainFrame, Vector<IntRect>& goodTargets, Vector<Node*>& highlightNodes)
{
    goodTargets.clear();

    int touchPointPadding = ceil(max(touchBox.width(), touchBox.height()) * 0.5);

    IntPoint touchPoint = touchBox.center();
    IntPoint contentsPoint = mainFrame->view()->windowToContents(touchPoint);

    HitTestResult result = mainFrame->eventHandler().hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
    const ListHashSet<RefPtr<Node> >& hitResults = result.rectBasedTestResult();

    // Blacklist nodes that are container of disambiguated nodes.
    // It is not uncommon to have a clickable <div> that contains other clickable objects.
    // This heuristic avoids excessive disambiguation in that case.
    HashSet<Node*> blackList;
    for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
        // Ignore any Nodes that can't be clicked on.
        RenderObject* renderer = it->get()->renderer();
        if (!renderer || !it->get()->willRespondToMouseClickEvents())
            continue;

        // Blacklist all of the Node's containers.
        for (RenderBlock* container = renderer->containingBlock(); container; container = container->containingBlock()) {
            Node* containerNode = container->node();
            if (!containerNode)
                continue;
            if (!blackList.add(containerNode).isNewEntry)
                break;
        }
    }

    HashMap<Node*, TouchTargetData> touchTargets;
    float bestScore = 0;
    for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
        for (Node* node = it->get(); node; node = node->parentNode()) {
            if (blackList.contains(node))
                continue;
            if (node->isDocumentNode() || isHTMLHtmlElement(*node) || isHTMLBodyElement(*node))
                break;
            if (node->willRespondToMouseClickEvents()) {
                TouchTargetData& targetData = touchTargets.add(node, TouchTargetData()).storedValue->value;
                targetData.windowBoundingBox = boundingBoxForEventNodes(node);
                targetData.score = scoreTouchTarget(touchPoint, touchPointPadding, targetData.windowBoundingBox);
                bestScore = max(bestScore, targetData.score);
                break;
            }
        }
    }

    for (HashMap<Node*, TouchTargetData>::iterator it = touchTargets.begin(); it != touchTargets.end(); ++it) {
        // Currently the scoring function uses the overlap area with the fat point as the score.
        // We ignore the candidates that has less than 1/2 overlap (we consider not really ambiguous enough) than the best candidate to avoid excessive popups.
        if (it->value.score < bestScore * 0.5)
            continue;
        goodTargets.append(it->value.windowBoundingBox);
        highlightNodes.append(it->key);
    }
}
void BinaryPropertyListPlan::writeString(const String& string)
{
    ++m_currentAggregateSize;
    if (!m_strings.add(string, m_currentObjectReference).isNewEntry)
        return;
    ++m_currentObjectReference;
    writeStringObject(string);
}
TEST(TestHashMapCopyConstructor, copyHashMapHasSameData)
{
    HashMap first;
    first.add("Ford", "Tang");
    HashMap second = first;
    ASSERT_EQ(first.size(), second.size());
    ASSERT_EQ(first.contains("Ford"), second.contains("Ford"));
    ASSERT_EQ(first.value("Ford"), second.value("Ford"));
}
static void scanDirectoryForDicionaries(const char* directoryPath, HashMap<AtomicString, Vector<String>>& availableLocales)
{
    for (const auto& filePath : listDirectory(directoryPath, "hyph_*.dic")) {
        String locale = extractLocaleFromDictionaryFilePath(filePath).convertToASCIILowercase();
        availableLocales.add(locale, Vector<String>()).iterator->value.append(filePath);

        String localeReplacingUnderscores = String(locale);
        localeReplacingUnderscores.replace('_', '-');
        if (locale != localeReplacingUnderscores)
            availableLocales.add(localeReplacingUnderscores, Vector<String>()).iterator->value.append(filePath);

        size_t dividerPosition = localeReplacingUnderscores.find('-');
        if (dividerPosition != notFound) {
            localeReplacingUnderscores.truncate(dividerPosition);
            availableLocales.add(localeReplacingUnderscores, Vector<String>()).iterator->value.append(filePath);
        }
    }
}
Exemple #16
0
static void setLiveValues(HashMap<Node*, AbstractValue>& values, HashSet<Node*>& live)
{
    values.clear();
    
    HashSet<Node*>::iterator iter = live.begin();
    HashSet<Node*>::iterator end = live.end();
    for (; iter != end; ++iter)
        values.add(*iter, AbstractValue());
}
void streamInsertionOthersTest() {
    Vector<int> v;
    v.add(14);
    v.add(42);
    cout << "Vector: " << v << endl;

    Stack<int> s;
    s.add(14);
    s.add(42);
    cout << "Stack: " << s << endl;

    Queue<int> q;
    q.add(14);
    q.add(42);
    cout << "Queue: " << q << endl;

    PriorityQueue<int> pq;
    pq.add(14, 1);
    pq.add(42, 2);
    cout << "PriorityQueue: " << pq << endl;

    Grid<int> grid;
    grid.resize(2, 2);
    grid.fill(14);
    cout << "Grid: " << grid << endl;

    Map<string, Vector<int>> map;
    map.add("corfu", v);
    cout << "Map<string, Vector>: " << map << endl;

    HashMap<Stack<int>, Vector<int>> hashmap;
    hashmap.add(s, v);
    cout << "Map<Stack, Vector>: " << hashmap << endl;

    Set<int> set;
    set.add(14);
    set.add(42);
    cout << "Set: " << set << endl;

    HashSet<Set<int>> hashset;
    hashset.add(set);
    cout << "HashSet<Set>: " << hashset << endl;

    Graph<DumbNode, DumbEdge> graph;
    graph.addNode("a");
    graph.addNode("b");
    graph.addNode("c");
    graph.addNode("d");
    graph.addNode("e");
    graph.addArc("a", "b");
    graph.addArc("a", "d");
    graph.addArc("b", "c");
    graph.addArc("b", "d");
    graph.addArc("c", "b");
    graph.addArc("c", "e");
    cout << "Graph: " << graph << endl;
}
Exemple #18
0
// Compiles a list of subtargets of all the relevant target nodes.
void compileSubtargetList(const NodeList& intersectedNodes, SubtargetGeometryList& subtargets, NodeFilter nodeFilter)
{
    // Find candidates responding to tap gesture events in O(n) time.
    HashMap<Node*, Node*> responderMap;
    HashSet<Node*> ancestorsToRespondersSet;
    Vector<Node*> candidates;

    // A node matching the NodeFilter is called a responder. Candidate nodes must either be a
    // responder or have an ancestor that is a responder.
    // This iteration tests all ancestors at most once by caching earlier results.
    unsigned length = intersectedNodes.length();
    for (unsigned i = 0; i < length; ++i) {
        Node* const node = intersectedNodes.item(i);
        Vector<Node*> visitedNodes;
        Node* respondingNode = 0;
        for (Node* visitedNode = node; visitedNode; visitedNode = visitedNode->parentOrHostNode()) {
            // Check if we already have a result for a common ancestor from another candidate.
            respondingNode = responderMap.get(visitedNode);
            if (respondingNode)
                break;
            visitedNodes.append(visitedNode);
            // Check if the node filter applies, which would mean we have found a responding node.
            if (nodeFilter(visitedNode)) {
                respondingNode = visitedNode;
                // Continue the iteration to collect the ancestors of the responder, which we will need later.
                for (visitedNode = visitedNode->parentOrHostNode(); visitedNode; visitedNode = visitedNode->parentOrHostNode()) {
                    pair<HashSet<Node*>::iterator, bool> addResult = ancestorsToRespondersSet.add(visitedNode);
                    if (!addResult.second)
                        break;
                }
                break;
            }
        }
        // Insert the detected responder for all the visited nodes.
        for (unsigned j = 0; j < visitedNodes.size(); j++)
            responderMap.add(visitedNodes[j], respondingNode);

        if (respondingNode)
            candidates.append(node);
    }

    // We compile the list of component absolute quads instead of using the bounding rect
    // to be able to perform better hit-testing on inline links on line-breaks.
    length = candidates.size();
    for (unsigned i = 0; i < length; i++) {
        Node* candidate = candidates[i];
        // Skip nodes who's responders are ancestors of other responders. This gives preference to
        // the inner-most event-handlers. So that a link is always preferred even when contained
        // in an element that monitors all click-events.
        Node* respondingNode = responderMap.get(candidate);
        ASSERT(respondingNode);
        if (ancestorsToRespondersSet.contains(respondingNode))
            continue;
        appendSubtargetsForNodeToList(candidate, subtargets);
    }
}
TEST(TestHashMapAdd, added10itemsShouldHave10items)
{
    HashMap Test;
    Test.add("Ford", "Tang");
    Test.add("Diana", "Chang");
    Test.add("Bronx", "Cat");
    Test.add("Alora", "Cat");
    Test.add("Bailey", "Cat");
    Test.add("Araceli", "Garcia");
    Test.add("Ray", "Chou");
    Test.add("Sam", "Guy");
    Test.add("Hua", "Man");
    Test.add("Michael", "Dude");
    Test.add("Ford", "Tang");
    ASSERT_EQ(10, Test.size());
}
Exemple #20
0
CanvasTexture::CanvasTexture(int layerId)
    : m_size()
    , m_layerId(layerId)
    , m_texture(0)
    , m_surfaceTexture(0)
    , m_ANW(0)
    , m_hasValidTexture(false)
    , m_useHwAcceleration(true)
{
    s_textures.add(m_layerId, this);
}
Exemple #21
0
static NEVER_INLINE void populateSVGFactoryMap(HashMap<AtomicStringImpl*, SVGConstructorFunction>& map)
{
    struct TableEntry {
        const QualifiedName& name;
        SVGConstructorFunction function;
    };

    static const TableEntry table[] = {
        { aTag, aConstructor },
        { animateTag, animateConstructor },
        { animateColorTag, animatecolorConstructor },
        { animateMotionTag, animatemotionConstructor },
        { animateTransformTag, animatetransformConstructor },
        { circleTag, circleConstructor },
        { clipPathTag, clippathConstructor },
        { cursorTag, cursorConstructor },
        { defsTag, defsConstructor },
        { descTag, descConstructor },
        { ellipseTag, ellipseConstructor },
        { foreignObjectTag, foreignobjectConstructor },
        { gTag, gConstructor },
        { imageTag, imageConstructor },
        { lineTag, lineConstructor },
        { linearGradientTag, lineargradientConstructor },
        { markerTag, markerConstructor },
        { maskTag, maskConstructor },
        { metadataTag, metadataConstructor },
        { mpathTag, mpathConstructor },
        { pathTag, pathConstructor },
        { patternTag, patternConstructor },
        { polygonTag, polygonConstructor },
        { polylineTag, polylineConstructor },
        { radialGradientTag, radialgradientConstructor },
        { rectTag, rectConstructor },
        { scriptTag, scriptConstructor },
        { setTag, setConstructor },
        { stopTag, stopConstructor },
        { styleTag, styleConstructor },
        { svgTag, svgConstructor },
        { switchTag, switchConstructor },
        { symbolTag, symbolConstructor },
        { textTag, textConstructor },
        { textPathTag, textpathConstructor },
        { titleTag, titleConstructor },
        { trefTag, trefConstructor },
        { tspanTag, tspanConstructor },
        { useTag, useConstructor },
        { viewTag, viewConstructor },
    };

    for (unsigned i = 0; i < WTF_ARRAY_LENGTH(table); ++i)
        map.add(table[i].name.localName().impl(), table[i].function);
}
Exemple #22
0
HRESULT STDMETHODCALLTYPE WebURLResponse::allHeaderFields( 
    /* [retval][out] */ IPropertyBag** headerFields)
{
    ASSERT(m_response.isHTTP());

    HashMap<String, String, CaseFoldingHash> fields;
    for (const auto& keyValuePair : m_response.httpHeaderFields())
        fields.add(keyValuePair.key, keyValuePair.value);

    *headerFields = COMPropertyBag<String, String, CaseFoldingHash>::adopt(fields);
    return S_OK;
}
Exemple #23
0
HRESULT WebCoreStatistics::memoryStatistics(IPropertyBag** statistics)
{
    if (!statistics)
        return E_POINTER;

    WTF::FastMallocStatistics fastMallocStatistics = WTF::fastMallocStatistics();

    JSLockHolder lock(JSDOMWindow::commonVM());
    unsigned long long heapSize = JSDOMWindow::commonVM().heap.size();
    unsigned long long heapFree = JSDOMWindow::commonVM().heap.capacity() - heapSize;
    GlobalMemoryStatistics globalMemoryStats = globalMemoryStatistics();

    HashMap<String, unsigned long long, CaseFoldingHash> fields;
    fields.add("FastMallocReservedVMBytes", static_cast<unsigned long long>(fastMallocStatistics.reservedVMBytes));
    fields.add("FastMallocCommittedVMBytes", static_cast<unsigned long long>(fastMallocStatistics.committedVMBytes));
    fields.add("FastMallocFreeListBytes", static_cast<unsigned long long>(fastMallocStatistics.freeListBytes));
    fields.add("JavaScriptHeapSize", heapSize);
    fields.add("JavaScriptFreeSize", heapFree);
    fields.add("JavaScriptStackSize", static_cast<unsigned long long>(globalMemoryStats.stackBytes));
    fields.add("JavaScriptJITSize", static_cast<unsigned long long>(globalMemoryStats.JITBytes));

    *statistics = COMPropertyBag<unsigned long long, String, CaseFoldingHash>::adopt(fields);

    return S_OK;
}
Exemple #24
0
void process(int x, int i)
{
	HashT h(x, i);
	bool found;
	HashT *stored = hm.add(h, found);

	if (found) {
		if (stored->v > last) last = stored->v;
		stored->v = i;
	}
	int grp = i - last;
	if (grp > ans) ans = grp;
}
static String cachedStorageDirectory(DWORD pathIdentifier)
{
    static HashMap<DWORD, String> directories;

    HashMap<DWORD, String>::iterator it = directories.find(pathIdentifier);
    if (it != directories.end())
        return it->second;

    String directory = storageDirectory(pathIdentifier);
    directories.add(pathIdentifier, directory);

    return directory;
}
Exemple #26
0
String PluginDatabase::MIMETypeForExtension(const String& extension) const
{
    if (extension.isEmpty())
        return String();

    PluginSet::const_iterator end = m_plugins.end();
    String mimeType;
    Vector<PluginPackage*, 2> pluginChoices;
    HashMap<PluginPackage*, String> mimeTypeForPlugin;

    for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) {
        if (!(*it)->isEnabled())
            continue;

        MIMEToExtensionsMap::const_iterator mime_end = (*it)->mimeToExtensions().end();

        for (MIMEToExtensionsMap::const_iterator mime_it = (*it)->mimeToExtensions().begin(); mime_it != mime_end; ++mime_it) {
            mimeType = mime_it->first;
            PluginPackage* preferredPlugin = m_preferredPlugins.get(mimeType).get();
            const Vector<String>& extensions = mime_it->second;
            bool foundMapping = false;
            for (unsigned i = 0; i < extensions.size(); i++) {
                if (equalIgnoringCase(extensions[i], extension)) {
                    PluginPackage* plugin = (*it).get();

                    if (preferredPlugin && PluginPackage::equal(*plugin, *preferredPlugin))
                        return mimeType;

#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE)
                    if (!plugin->ensurePluginLoaded())
                        continue;
#endif
                    pluginChoices.append(plugin);
                    mimeTypeForPlugin.add(plugin, mimeType);
                    foundMapping = true;
                    break;
                }
            }
            if (foundMapping)
                break;
        }
    }

    if (pluginChoices.isEmpty())
        return String();

    qsort(pluginChoices.data(), pluginChoices.size(), sizeof(PluginPackage*), PluginDatabase::preferredPluginCompare);

    return mimeTypeForPlugin.get(pluginChoices[0]);
}
Exemple #27
0
inline unsigned CalculationValueMap::insert(Ref<CalculationValue>&& value)
{
    ASSERT(m_nextAvailableHandle);

    // The leakRef below is balanced by the adoptRef in the deref member function.
    Entry leakedValue = value.leakRef();

    // FIXME: This monotonically increasing handle generation scheme is potentially wasteful
    // of the handle space. Consider reusing empty handles. https://bugs.webkit.org/show_bug.cgi?id=80489
    while (!m_map.isValidKey(m_nextAvailableHandle) || !m_map.add(m_nextAvailableHandle, leakedValue).isNewEntry)
        ++m_nextAvailableHandle;

    return m_nextAvailableHandle++;
}
Exemple #28
0
HRESULT WebURLResponse::allHeaderFields(_COM_Outptr_opt_ IPropertyBag** headerFields)
{
    ASSERT(m_response.isHTTP());

    if (!headerFields)
        return E_POINTER;

    HashMap<String, String, CaseFoldingHash> fields;
    for (const auto& keyValuePair : m_response.httpHeaderFields())
        fields.add(keyValuePair.key, keyValuePair.value);

    *headerFields = COMPropertyBag<String, String, CaseFoldingHash>::adopt(fields);
    return S_OK;
}
Exemple #29
0
 LogarithmSolver(Long m): p(m) {
     block_size = 0;
     while (block_size * block_size <= p - 1) {
         block_size ++;
     }
     g = find_primitive_root(p);
     baby_step = pow_mod(g, p - 2, p);
     giant_step = pow_mod(g, block_size, p);
     Long current = 1 % p;
     for (Long i = 0; i < block_size; ++ i) {
         giant_steps.add(current, block_size * i);
         current = (current * giant_step) % p;
     }
 }
void BinaryPropertyListPlan::writeInteger(int integer)
{
    ASSERT(integer >= 0);
    ++m_currentAggregateSize;
    if (!integer) {
        if (m_integerZeroObjectReference != invalidObjectReference())
            return;
        m_integerZeroObjectReference = m_currentObjectReference;
    } else {
        if (!m_integers.add(integer, m_currentObjectReference).isNewEntry)
            return;
    }
    ++m_currentObjectReference;
    m_byteCount += integerByteCount(integer);
}