aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store/src/main/java/tools/refinery/store/map/Cursors.java
blob: 5e69e7afa4f7aa8eb2e0f8929e1430cca18554cd (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package tools.refinery.store.map;

import java.util.Iterator;
import java.util.Map;

public final class Cursors {
    private Cursors() {
        throw new IllegalStateException("This is a static utility class and should not be instantiated directly");
    }

    public static <K, V> Cursor<K, V> empty() {
        return new Empty<>();
    }

	public static <K, V> Cursor<K, V> singleton(K key, V value) {
		return new Singleton<>(key, value);
	}

	public static <K, V> Cursor<K, V> of(Iterator<Map.Entry<K, V>> iterator) {
		return new IteratorBasedCursor<>(iterator);
	}

	public static <K, V> Cursor<K, V> of(Map<K, V> map) {
		return of(map.entrySet().iterator());
	}

    private static class Empty<K, V> implements Cursor<K, V> {
        private boolean terminated = false;

        @Override
        public K getKey() {
            return null;
        }

        @Override
        public V getValue() {
            return null;
        }

        @Override
        public boolean isTerminated() {
            return terminated;
        }

        @Override
        public boolean move() {
            terminated = true;
            return false;
        }
    }

	private static class Singleton<K, V> implements Cursor<K, V> {
		private State state = State.INITIAL;
		private final K key;
		private final V value;

		public Singleton(K key, V value) {
			this.key = key;
			this.value = value;
		}

		@Override
		public K getKey() {
			if (state == State.STARTED) {
				return key;
			}
			return null;
		}

		@Override
		public V getValue() {
			if (state == State.STARTED) {
				return value;
			}
			return null;
		}

		@Override
		public boolean isTerminated() {
			return state == State.TERMINATED;
		}

		@Override
		public boolean move() {
			if (state == State.INITIAL) {
				state = State.STARTED;
				return true;
			}
			state = State.TERMINATED;
			return false;
		}


		private enum State {
			INITIAL,
			STARTED,
			TERMINATED
		}
	}
}