aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store/src/main/java/tools/refinery/store/tuple/Tuple.java
blob: aae7b3443b395451f3d1a20ec459973531099fd3 (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
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package tools.refinery.store.tuple;

import org.jetbrains.annotations.NotNull;

public sealed interface Tuple extends Comparable<Tuple> permits Tuple0, Tuple1, Tuple2, Tuple3, Tuple4, TupleN {
	int getSize();

	int get(int element);

	@Override
	default int compareTo(@NotNull Tuple other) {
		int size = getSize();
		int compareSize = Integer.compare(size, other.getSize());
		if (compareSize != 0) {
			return compareSize;
		}
		for (int i = 0; i < size; i++) {
			int compareElement = Integer.compare(get(i), other.get(i));
			if (compareElement != 0) {
				return compareElement;
			}
		}
		return 0;
	}

	static Tuple0 of() {
		return Tuple0.INSTANCE;
	}

	static Tuple1 of(int value) {
		return Tuple1.Cache.INSTANCE.getOrCreate(value);
	}

	static Tuple2 of(int value1, int value2) {
		return new Tuple2(value1, value2);
	}

	static Tuple3 of(int value1, int value2, int value3) {
		return new Tuple3(value1, value2, value3);
	}

	static Tuple4 of(int value1, int value2, int value3, int value4) {
		return new Tuple4(value1, value2, value3, value4);
	}

	static Tuple of(int... values) {
		return switch (values.length) {
			case 0 -> of();
			case 1 -> of(values[0]);
			case 2 -> of(values[0], values[1]);
			case 3 -> of(values[0], values[1], values[2]);
			case 4 -> of(values[0], values[1], values[2], values[3]);
			default -> new TupleN(values);
		};
	}
}