Skip to content

Method: rematerialize(long)

1: package de.fhdw.gaming.ipspiel23.c4.domain;
2:
3: import de.fhdw.gaming.ipspiel23.c4.domain.impl.C4Position;
4:
5: /**
6: * This class provides methods to rematerialize and dematerialize {@link IC4Position} instances.
7: * <p>
8: * Note: We apply the principle of {@link https://en.wikipedia.org/wiki/Rematerialization} to
9: * memory management. Only instead of worrying about spilling registers to memory, we worry about
10: * spilling row and column stack values to the heap.
11: * </p>
12: * <p>
13: * This means that we dematerialize position objects to primitive long values for efficient storage
14: * in arrays and rematerialize them back into position objects when needed. This is done to prevent
15: * unnecessary heap allocations for position instances, reducing memory overhead and garbage collection
16: * pressure. Dematerialized positions allow for inlining of position instances in arrays for better
17: * cache locality and performance as they are value types.
18: * </p>
19: */
20: // C# has structs, Java does not. Therefore, we have this abomination.
21: public final class C4PositionMaterializer {
22:
23: /**
24: * The unused private ctor of this "static" class.
25: */
26: private C4PositionMaterializer() { }
27:
28: /**
29: * Rematerializes a dematerialized position from a primitive long value back into a position
30: * object.
31: * @param dematPosition The dematerialized position.
32: * @return The rematerialized position.
33: */
34: public static IC4Position rematerialize(final long dematPosition) {
35: return new C4Position((int) (dematPosition >> 32), (int) dematPosition);
36: }
37:
38: /**
39: * Dematerializes a position object into a primitive long value.
40: * @param position The position to dematerialize.
41: * @return The dematerialized position.
42: */
43: public static long dematerialize(final IC4Position position) {
44: return dematerialize(position.getRow(), position.getColumn());
45: }
46:
47: /**
48: * Dematerializes a position row and column index into a primitive long value.
49: * @param row The row of the position.
50: * @param column The column of the position.
51: * @return The dematerialized position.
52: */
53: public static long dematerialize(final int row, final int column) {
54: return ((long) row) << 32 | column;
55: }
56:
57: /**
58: * Gets the row.
59: * @param pos the position as a long.
60: * @return The row.
61: */
62: public static int getRow(final long pos) {
63: return (int) (pos >> 32);
64: }
65:
66: /**
67: * Gets the column.
68: * @param pos the position as a long.
69: * @return The column.
70: */
71: public static int getColumn(final long pos) {
72: return (int) pos;
73: }
74: }