aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/viatra-runtime/src/main/java/tools/refinery/viatra/runtime/matchers/tuple/LeftInheritanceTuple1.java
blob: 611231760d445996f2e77af9aceecf80693cf3f5 (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
75
76
77
78
79
80
81
82
83
/*******************************************************************************
 * Copyright (c) 2010-2017, Gabor Bergmann, IncQueryLabs Ltd.
 * 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.matchers.tuple;

import java.util.Objects;

/**
 * @author Gabor Bergmann
 * @since 1.7
 */
public final class LeftInheritanceTuple1 extends BaseLeftInheritanceTuple {
    /**
     * A single substituted value after inheritedIndex. 
     */
    private final Object localElement;

    /**
     * @param ancestor
     * @param localElement
     */
    protected LeftInheritanceTuple1(Tuple ancestor, Object localElement) {
        super(ancestor);
        this.localElement = localElement;
        calcHash();
    }
    
    /**
     * @return number of elements
     */
    public int getSize() {
        return inheritedIndex + 1;
    }

    @Override
    public int getLocalSize() {
        return 1;
    }

    /**
     * @pre: 0 <= index < getSize()
     * 
     * @return the element at the specified index
     */
    public Object get(int index) {
        int local = index - inheritedIndex;
        if (local < 0) 
            return ancestor.get(index);
        else if (local == 0) return localElement;
        else throw raiseIndexingError(index);
    }

    /**
     * Optimized hash calculation
     */
    @Override
    void calcHash() {
        final int PRIME = 31;
        cachedHash = ancestor.hashCode();
        cachedHash = PRIME * cachedHash;
        if (localElement != null) cachedHash += localElement.hashCode();
    }

    /**
     * Optimized equals calculation (prediction: true, since hash values match)
     */    
    @Override
    protected boolean localEquals(BaseLeftInheritanceTuple other) {
        if (other instanceof LeftInheritanceTuple1) {
            LeftInheritanceTuple1 lit = (LeftInheritanceTuple1)other;
            return Objects.equals(this.localElement, lit.localElement);
        } else {
            return (1 == other.getLocalSize()) && 
                    Objects.equals(localElement, other.get(inheritedIndex));
        }
    }

}