1 package org.simantics.scl.runtime.tests;
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.LinkedHashSet;
7 import java.util.Random;
9 import org.junit.Assert;
10 import org.junit.Before;
11 import org.junit.Test;
12 import org.simantics.scl.runtime.chr.CHRHashIndex;
14 import gnu.trove.map.hash.TIntObjectHashMap;
15 import gnu.trove.set.hash.THashSet;
16 import gnu.trove.set.hash.TIntHashSet;
18 public class TestCHRHashIndex {
23 THashSet<Fact> aliveFacts = new THashSet<Fact>();
25 public static class Store {
26 CHRHashIndex bfIndex = new CHRHashIndex() {
28 protected boolean keyEquals(Object a, Object b) {
29 return ((Fact)a).a == ((Fact)b).a;
32 protected int keyHashCode(Object key) {
38 public static class Store2 {
39 TIntObjectHashMap<LinkedHashSet<Fact>> bfIndex = new TIntObjectHashMap<LinkedHashSet<Fact>>();
42 public static class Fact {
48 public Fact(int a, int b) {
53 public void add(Store store) {
54 bfNext = (Fact)store.bfIndex.addFreshAndReturnOld(this);
59 public void remove(Store store) {
62 store.bfIndex.removeKnownToExistKey(this);
65 store.bfIndex.replaceKnownToExistKey(this, bfNext);
69 bfPrev.bfNext = bfNext;
71 bfNext.bfPrev = bfPrev;
75 public List<Fact> get(Store store) {
76 Object r = store.bfIndex.getEqual(this);
78 return Collections.emptyList();
80 ArrayList<Fact> result = new ArrayList<Fact>();
81 for(Fact cur=(Fact)r;cur!=null;cur=cur.bfNext)
83 Collections.reverse(result);
88 public void add(Store2 store) {
89 LinkedHashSet<Fact> set = store.bfIndex.get(a);
91 set = new LinkedHashSet<>();
92 store.bfIndex.put(a, set);
97 public void remove(Store2 store) {
98 store.bfIndex.get(a).remove(this);
101 public List<Fact> get(Store2 store) {
102 LinkedHashSet<Fact> set = store.bfIndex.get(a);
104 return Collections.emptyList();
106 return new ArrayList<Fact>(set);
112 random = new Random(123L);
114 store2 = new Store2();
117 public Fact createFact(int maxA, int maxB) {
118 return new Fact(random.nextInt(maxA), random.nextInt(maxB));
121 public void add(Fact fact) {
124 aliveFacts.add(fact);
127 public void remove(Fact fact) {
130 aliveFacts.remove(fact);
133 public void checkConsistency() {
134 TIntHashSet keys = new TIntHashSet();
135 for(Fact fact : aliveFacts)
137 Fact temp = new Fact(0, 0);
138 for(int a : keys.toArray()) {
140 Assert.assertEquals(temp.get(store2), temp.get(store));
142 TIntHashSet keys2 = new TIntHashSet();
143 for(Fact fact : store.bfIndex.toArray(new Fact[keys.size()]))
145 Assert.assertEquals(keys, keys2);
149 public void testStore() {
151 System.out.println("Run " + i);
152 for(int j=0;j<1000000;++j)
153 add(createFact(10000, 1000000));
155 ArrayList<Fact> factArray = new ArrayList<Fact>(aliveFacts);
156 Collections.shuffle(factArray, random);
157 for(Fact fact : factArray.subList(100000, factArray.size()))