summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/data/Lazy.java
blob: 45293e2ee334de06e3e47df4e577cd05866ae5b7 (plain)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* 
 * esodata - data structures and other things, of varying utility
 * Copyright 2022, Ben Culkin
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *   
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package bjc.data;

import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

import bjc.data.internals.BoundLazy;
import bjc.funcdata.FunctionalList;
import bjc.funcdata.ListEx;

/**
 * A holder that holds a means to create a value, but doesn't actually compute
 * the value until it's needed.
 *
 * @author ben
 *
 * @param <ContainedType>
 *                        The type of the value being held.
 */
public class Lazy<ContainedType> implements Holder<ContainedType> {
	/* The supplier of the type. */
	private Supplier<ContainedType> valueSupplier;
	/* The actual type value. */
	private ContainedType heldValue;
	/* Whether the value has been created. */
	private boolean valueMaterialized;

	/* The list of pending actions on the value. */
	private ListEx<UnaryOperator<ContainedType>> actions = new FunctionalList<>();

	/**
	 * Create a new lazy value from the specified seed value.
	 *
	 * @param value
	 *              The seed value to use.
	 */
	public Lazy(final ContainedType value) {
		heldValue = value;

		valueMaterialized = true;
	}

	/**
	 * Create a new lazy value from the specified value source.
	 *
	 * @param supp
	 *             The source of a value to use.
	 */
	public Lazy(final Supplier<ContainedType> supp) {
		valueSupplier = new SingleSupplier<>(supp);

		valueMaterialized = false;
	}

	/* Create a new value from a supplier and a list of actions. */
	private Lazy(final Supplier<ContainedType> supp,
			final ListEx<UnaryOperator<ContainedType>> pendingActions) {
		valueSupplier = supp;

		actions = pendingActions;
	}

	@Override
	public <BoundType> Holder<BoundType>
			bind(final Function<ContainedType, Holder<BoundType>> binder) {
		final ListEx<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>();

		for (UnaryOperator<ContainedType> action : actions) {
			pendingActions.add(action);
		}
		

		final Supplier<ContainedType> supplier = () -> {
			if (valueMaterialized) return heldValue;
			else                   return valueSupplier.get();
		};

		return new BoundLazy<>(() -> new Lazy<>(supplier, pendingActions), binder);
	}

	@Override
	public <NewType> Function<ContainedType, Holder<NewType>>
			lift(final Function<ContainedType, NewType> func) {
		return val -> new Lazy<>(func.apply(val));
	}

	@Override
	public <MappedType> Holder<MappedType>
			map(final Function<ContainedType, MappedType> mapper) {
		final ListEx<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>();
		
		for (UnaryOperator<ContainedType> action : actions) {
			pendingActions.add(action);
		}

		return new Lazy<>(() -> {
			ContainedType currVal = heldValue;

			if (!valueMaterialized) {
				currVal = valueSupplier.get();
			}

			return pendingActions.reduceAux(currVal,
					UnaryOperator<ContainedType>::apply,
					value -> mapper.apply(value));
		});
	}

	@Override
	public String toString() {
		if (valueMaterialized) {
			if (actions.isEmpty()) {
				return String.format("value[v='%s']", heldValue);
			} else {
				return String.format("value[v='%s'] (has %d pending transforms)",
						heldValue, actions.getSize());
			}
		}

		if (actions.isEmpty()) {
			return"(unmaterialized)";
		} else {
			return String.format("(unmaterialized; has %d pending transforms",
					actions.getSize());
		}
	}

	@Override
	public Holder<ContainedType>
			transform(final UnaryOperator<ContainedType> transformer) {
		actions.add(transformer);

		return this;
	}

	@Override
	public <UnwrappedType> UnwrappedType
			unwrap(final Function<ContainedType, UnwrappedType> unwrapper) {
		if (!valueMaterialized) {
			heldValue = valueSupplier.get();

			valueMaterialized = true;
		}

		for (UnaryOperator<ContainedType> action : actions) {
			heldValue = action.apply(heldValue);	
		}

		actions = new FunctionalList<>();

		return unwrapper.apply(heldValue);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;

		result = prime * result + (actions == null ? 0 : actions.hashCode());
		result = prime * result + (heldValue == null ? 0 : heldValue.hashCode());
		result = prime * result + (valueMaterialized ? 1231 : 1237);

		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj)               return true;
		if (obj == null)               return false;
		if (!(obj instanceof Lazy<?>)) return false;

		final Lazy<?> other = (Lazy<?>) obj;

		if (valueMaterialized != other.valueMaterialized)
			return false;

		if (valueMaterialized) {
			if (heldValue == null) {
				if (other.heldValue != null) return false;
			} else if (!heldValue.equals(other.heldValue)) {
				return false;
			}
		} else {
			return false;
		}

		if (actions == null) {
			if (other.actions != null) return false;
		} else if (actions.getSize() > 0 || other.actions.getSize() > 0) {
			return false;
		}

		return true;
	}

	/**
	 * Create a new lazy container with an already present value.
	 * 
	 * @param <ContainedType> The type of the contained value.
	 * 
	 * @param val The value for the lazy container.
	 *
	 * @return A new lazy container holding that value.
	 */
	public static <ContainedType> Lazy<ContainedType> lazy(final ContainedType val) {
		return new Lazy<>(val);
	}

	/**
	 * Create a new lazy container with a suspended value.
	 *
	 * @param <ContainedType> The type of the contained value.
	 * 
	 * @param supp The suspended value for the lazy container.
	 *
	 * @return A new lazy container that will un-suspend the value when necessary.
	 */
	public static <ContainedType> Lazy<ContainedType>
			lazy(final Supplier<ContainedType> supp) {
		return new Lazy<>(supp);
	}
}