Avoid second map operation

This commit is contained in:
themode 2022-01-07 01:35:43 +01:00 committed by TheMode
parent edfcc50214
commit 51795ccbd1
2 changed files with 13 additions and 6 deletions

View File

@ -61,6 +61,7 @@ final class PaletteImpl implements Palette, Cloneable {
this.paletteToValueList.add(0); this.paletteToValueList.add(0);
this.valueToPaletteMap = new Int2IntOpenHashMap(1); this.valueToPaletteMap = new Int2IntOpenHashMap(1);
this.valueToPaletteMap.put(0, 0); this.valueToPaletteMap.put(0, 0);
this.valueToPaletteMap.defaultReturnValue(-1);
} }
@Override @Override
@ -362,18 +363,17 @@ final class PaletteImpl implements Palette, Cloneable {
private int getPaletteIndex(int value) { private int getPaletteIndex(int value) {
if (!hasPalette) return value; if (!hasPalette) return value;
final int lookup = valueToPaletteMap.getOrDefault(value, (short) -1); final int lastPaletteIndex = this.lastPaletteIndex;
if (lookup != -1) return lookup;
if (lastPaletteIndex >= maxPaletteSize(bitsPerEntry)) { if (lastPaletteIndex >= maxPaletteSize(bitsPerEntry)) {
// Palette is full, must resize // Palette is full, must resize
resize(bitsPerEntry + bitsIncrement); resize(bitsPerEntry + bitsIncrement);
return getPaletteIndex(value); return getPaletteIndex(value);
} }
final int paletteIndex = lastPaletteIndex++; final int lookup = valueToPaletteMap.putIfAbsent(value, lastPaletteIndex);
if (lookup != -1) return lookup;
this.lastPaletteIndex = lastPaletteIndex + 1;
this.paletteToValueList.add(value); this.paletteToValueList.add(value);
this.valueToPaletteMap.put(value, paletteIndex); return lastPaletteIndex;
return paletteIndex;
} }
int getSectionIndex(int x, int y, int z) { int getSectionIndex(int x, int y, int z) {

View File

@ -14,6 +14,13 @@ import static org.junit.jupiter.api.Assertions.*;
public class PaletteTest { public class PaletteTest {
@Test
public void singlePlacement() {
var palette = Palette.blocks();
palette.set(0, 0, 1, 1);
assertEquals(1, palette.get(0, 0, 1));
}
@Test @Test
public void placement() { public void placement() {
var palettes = testPalettes(); var palettes = testPalettes();