aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/network/indexer/DefaultMessageIndexer.java
blob: da9bc47e6907b8070bb30baf5d126b82c6f93ee9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*******************************************************************************
 * Copyright (c) 2010-2018, Tamas Szabo, Istvan Rath and Daniel Varro
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-v20.html.
 * 
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/
package tools.refinery.viatra.runtime.rete.network.indexer;

import java.util.Collections;
import java.util.Map;

import tools.refinery.viatra.runtime.matchers.tuple.Tuple;
import tools.refinery.viatra.runtime.matchers.util.CollectionsFactory;

/**
 * @author Tamas Szabo
 * @since 2.0
 */
public class DefaultMessageIndexer implements MessageIndexer {

	protected final Map<Tuple, Integer> indexer;

	public DefaultMessageIndexer() {
		this.indexer = CollectionsFactory.createMap();
	}

	public Map<Tuple, Integer> getTuples() {
		return Collections.unmodifiableMap(this.indexer);
	}

	@Override
	public int getCount(final Tuple update) {
		final Integer count = getTuples().get(update);
		if (count == null) {
			return 0;
		} else {
			return count;
		}
	}

	@Override
	public void insert(final Tuple update) {
		update(update, 1);
	}

	@Override
	public void delete(final Tuple update) {
		update(update, -1);
	}

	@Override
	public void update(final Tuple update, final int delta) {
		final Integer oldCount = this.indexer.get(update);
		final int newCount = (oldCount == null ? 0 : oldCount) + delta;
		if (newCount == 0) {
			this.indexer.remove(update);
		} else {
			this.indexer.put(update, newCount);
		}
	}

	@Override
	public boolean isEmpty() {
		return this.indexer.isEmpty();
	}

	@Override
	public void clear() {
		this.indexer.clear();
	}

}