diff --git a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/AbstractPlatformGridResource.java b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/AbstractPlatformGridResource.java index f633c8021..01ebaa119 100644 --- a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/AbstractPlatformGridResource.java +++ b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/AbstractPlatformGridResource.java @@ -2,39 +2,40 @@ import com.refinedmods.refinedstorage.api.grid.view.GridResourceAttributeKey; import com.refinedmods.refinedstorage.api.grid.view.GridView; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedResource; +import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Set; +import javax.annotation.Nullable; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.3.0") -public abstract class AbstractPlatformGridResource implements PlatformGridResource { - protected final ResourceAmount resourceAmount; +public abstract class AbstractPlatformGridResource implements PlatformGridResource { + protected final T resource; private final String name; private final Map> attributes; private boolean zeroed; - protected AbstractPlatformGridResource(final ResourceAmount resourceAmount, + protected AbstractPlatformGridResource(final T resource, final String name, final Map> attributes) { - this.resourceAmount = resourceAmount; + this.resource = resource; this.name = name; this.attributes = attributes; } @Override public Optional getTrackedResource(final GridView view) { - return view.getTrackedResource(resourceAmount.getResource()); + return view.getTrackedResource(resource); } @Override - public long getAmount() { - return resourceAmount.getAmount(); + public long getAmount(final GridView view) { + return view.getAmount(resource); } @Override @@ -57,10 +58,16 @@ public void setZeroed(final boolean zeroed) { this.zeroed = zeroed; } + @Nullable + @Override + public PlatformResourceKey getResourceForRecipeMods() { + return resource; + } + @Override public String toString() { return "AbstractPlatformGridResource{" - + "resourceAmount=" + resourceAmount + + "resource=" + resource + ", name='" + name + '\'' + ", attributes=" + attributes + ", zeroed=" + zeroed diff --git a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/PlatformGridResource.java b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/PlatformGridResource.java index 9436be8f2..40e9a03cd 100644 --- a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/PlatformGridResource.java +++ b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/grid/view/PlatformGridResource.java @@ -2,10 +2,12 @@ import com.refinedmods.refinedstorage.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage.api.grid.view.GridResource; +import com.refinedmods.refinedstorage.api.grid.view.GridView; import com.refinedmods.refinedstorage.common.api.grid.GridScrollMode; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage.common.api.support.resource.ResourceType; import java.util.List; import java.util.Optional; @@ -28,9 +30,11 @@ void onScroll(GridScrollMode scrollMode, void render(GuiGraphics graphics, int x, int y); - String getDisplayedAmount(); + String getDisplayedAmount(GridView view); - String getAmountInTooltip(); + String getAmountInTooltip(GridView view); + + boolean belongsToResourceType(ResourceType resourceType); List getTooltip(); @@ -38,9 +42,9 @@ void onScroll(GridScrollMode scrollMode, int getRegistryId(); - List getExtractionHints(); + List getExtractionHints(GridView view); @Nullable @API(status = API.Status.INTERNAL) - PlatformResourceKey getUnderlyingResource(); + PlatformResourceKey getResourceForRecipeMods(); } diff --git a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/storage/root/FuzzyRootStorage.java b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/storage/root/FuzzyRootStorage.java index 9f6f516b3..74ad368b4 100644 --- a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/storage/root/FuzzyRootStorage.java +++ b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/storage/root/FuzzyRootStorage.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage.common.api.storage.root; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; @@ -10,5 +9,5 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.4") public interface FuzzyRootStorage extends RootStorage { - Collection getFuzzy(ResourceKey resource); + Collection getFuzzy(ResourceKey resource); } diff --git a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/ResourceType.java b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/ResourceType.java index ad0d97054..1e8d34bfa 100644 --- a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/ResourceType.java +++ b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/ResourceType.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage.api.grid.view.GridResource; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.Actor; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; @@ -33,9 +33,7 @@ public interface ResourceType { double getDisplayAmount(long amount); - Optional toGridResource(ResourceAmount resourceAmount); - - boolean isGridResourceBelonging(GridResource gridResource); + Optional toGridResource(ResourceKey resource); long getInterfaceExportLimit(); diff --git a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/list/FuzzyResourceList.java b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/list/FuzzyResourceList.java index 0842d3181..082e82808 100644 --- a/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/list/FuzzyResourceList.java +++ b/refinedstorage-common-api/src/main/java/com/refinedmods/refinedstorage/common/api/support/resource/list/FuzzyResourceList.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage.common.api.support.resource.list; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; import com.refinedmods.refinedstorage.common.api.support.resource.FuzzyModeNormalizer; @@ -17,5 +16,5 @@ public interface FuzzyResourceList extends ResourceList { * @param resource the resource, doesn't matter if it's normalized or not * @return a list of fuzzy matched variants, or empty list if none found */ - Collection getFuzzy(ResourceKey resource); + Collection getFuzzy(ResourceKey resource); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/CraftingPatternClientTooltipComponent.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/CraftingPatternClientTooltipComponent.java index e06c204a1..52c833fb3 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/CraftingPatternClientTooltipComponent.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/CraftingPatternClientTooltipComponent.java @@ -49,14 +49,14 @@ public CraftingPatternClientTooltipComponent(final int width, this.width = width; this.height = height; this.craftingPattern = craftingPattern; - final ItemResource outputResource = craftingPattern.output().getResource() instanceof ItemResource itemResource + final ItemResource outputResource = craftingPattern.output().resource() instanceof ItemResource itemResource ? itemResource : null; this.outputStack = outputResource != null - ? outputResource.toItemStack(craftingPattern.output().getAmount()) + ? outputResource.toItemStack(craftingPattern.output().amount()) : null; this.outputText = outputResource != null - ? Component.literal(String.format("%dx ", craftingPattern.output().getAmount())) + ? Component.literal(String.format("%dx ", craftingPattern.output().amount())) .append(outputResource.toItemStack().getHoverName()) .withStyle(ChatFormatting.GRAY) : null; } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternGridBlockEntity.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternGridBlockEntity.java index cf5e736fc..7881f4a9b 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternGridBlockEntity.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternGridBlockEntity.java @@ -244,11 +244,11 @@ private ItemStack createProcessingPattern() { final ItemStack result = createPatternStack(PatternType.PROCESSING); final List> inputs = new ArrayList<>(); for (int i = 0; i < processingInput.size(); ++i) { - inputs.add(Optional.ofNullable(processingInput.get(i)).map(ResourceAmount::copy)); + inputs.add(Optional.ofNullable(processingInput.get(i))); } final List> outputs = new ArrayList<>(); for (int i = 0; i < processingOutput.size(); ++i) { - outputs.add(Optional.ofNullable(processingOutput.get(i)).map(ResourceAmount::copy)); + outputs.add(Optional.ofNullable(processingOutput.get(i))); } final ProcessingPatternState patternProcessingState = new ProcessingPatternState( inputs, diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternRendering.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternRendering.java index 165abc671..ca1143815 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternRendering.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/PatternRendering.java @@ -28,12 +28,12 @@ public static Optional getOutput(final ItemStack stack) { } return RefinedStorageApi.INSTANCE.getPattern(stack, level).map(pattern -> { if (pattern instanceof CraftingPattern craftingPattern - && craftingPattern.output().getResource() instanceof ItemResource itemResource) { + && craftingPattern.output().resource() instanceof ItemResource itemResource) { return itemResource.toItemStack(); } if (pattern instanceof ProcessingPattern processingPattern && processingPattern.outputs().size() == 1 - && processingPattern.outputs().getFirst().getResource() instanceof ItemResource itemResource) { + && processingPattern.outputs().getFirst().resource() instanceof ItemResource itemResource) { return itemResource.toItemStack(); } return null; diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternClientTooltipComponent.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternClientTooltipComponent.java index 5131a51a2..b3a04f21e 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternClientTooltipComponent.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternClientTooltipComponent.java @@ -60,14 +60,14 @@ private static List getOutputText(final ProcessingPatternState state) private static Component getOutputText(final ResourceAmount resourceAmount) { final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering( - resourceAmount.getResource() + resourceAmount.resource() ); final String displayAmount = rendering.getDisplayedAmount( - resourceAmount.getAmount(), + resourceAmount.amount(), false ); return Component.literal(String.format("%sx ", displayAmount)) - .append(rendering.getDisplayName(resourceAmount.getResource())) + .append(rendering.getDisplayName(resourceAmount.resource())) .withStyle(ChatFormatting.GRAY); } @@ -113,10 +113,10 @@ private void renderMatrixSlots(final int x, graphics.blitSprite(SLOT, slotX, slotY, 18, 18); slots.get(idx).ifPresent(resourceAmount -> { final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering( - resourceAmount.getResource() + resourceAmount.resource() ); - rendering.render(resourceAmount.getResource(), graphics, slotX + 1, slotY + 1); - AbstractBaseScreen.renderResourceAmount(graphics, slotX + 1, slotY + 1, resourceAmount.getAmount(), + rendering.render(resourceAmount.resource(), graphics, slotX + 1, slotY + 1); + AbstractBaseScreen.renderResourceAmount(graphics, slotX + 1, slotY + 1, resourceAmount.amount(), rendering); }); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternState.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternState.java index afa7d0f76..d006c71b4 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternState.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/autocrafting/ProcessingPatternState.java @@ -36,12 +36,12 @@ public record ProcessingPatternState( List getFlatInputs() { final ResourceList list = ResourceListImpl.orderPreserving(); inputs.forEach(input -> input.ifPresent(list::add)); - return new ArrayList<>(list.getAll()); + return new ArrayList<>(list.copyState()); } List getFlatOutputs() { final ResourceList list = ResourceListImpl.orderPreserving(); outputs.forEach(output -> output.ifPresent(list::add)); - return new ArrayList<>(list.getAll()); + return new ArrayList<>(list.copyState()); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/detector/FuzzyDetectorAmountStrategy.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/detector/FuzzyDetectorAmountStrategy.java index f6745d320..d5ef6830a 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/detector/FuzzyDetectorAmountStrategy.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/detector/FuzzyDetectorAmountStrategy.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage.api.network.Network; import com.refinedmods.refinedstorage.api.network.impl.node.detector.AbstractDetectorAmountStrategy; import com.refinedmods.refinedstorage.api.network.impl.node.detector.DetectorAmountStrategy; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.api.storage.root.FuzzyRootStorage; @@ -23,7 +22,7 @@ public long getAmount(final Network network, final ResourceKey configuredResourc } return fuzzyRootStorage.getFuzzy(configuredResource) .stream() - .mapToLong(ResourceAmount::getAmount) + .mapToLong(rootStorage::get) .sum(); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/exporter/FuzzyExporterTransferStrategy.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/exporter/FuzzyExporterTransferStrategy.java index 0c9d5db4c..1b160d739 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/exporter/FuzzyExporterTransferStrategy.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/exporter/FuzzyExporterTransferStrategy.java @@ -1,14 +1,12 @@ package com.refinedmods.refinedstorage.common.exporter; import com.refinedmods.refinedstorage.api.network.impl.node.exporter.ExporterTransferStrategyImpl; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.InsertableStorage; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.api.storage.root.FuzzyRootStorage; import java.util.Collection; -import java.util.stream.Collectors; public class FuzzyExporterTransferStrategy extends ExporterTransferStrategyImpl { public FuzzyExporterTransferStrategy(final InsertableStorage destination, final long transferQuota) { @@ -18,11 +16,7 @@ public FuzzyExporterTransferStrategy(final InsertableStorage destination, final @Override protected Collection expand(final ResourceKey resource, final RootStorage rootStorage) { if (rootStorage instanceof FuzzyRootStorage fuzzyRootStorage) { - return fuzzyRootStorage - .getFuzzy(resource) - .stream() - .map(ResourceAmount::getResource) - .collect(Collectors.toSet()); + return fuzzyRootStorage.getFuzzy(resource); } return super.expand(resource, rootStorage); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/AbstractGridContainerMenu.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/AbstractGridContainerMenu.java index 51d45f07c..45fdf9efa 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/AbstractGridContainerMenu.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/AbstractGridContainerMenu.java @@ -22,6 +22,7 @@ import com.refinedmods.refinedstorage.common.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridInsertionStrategy; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridScrollingStrategy; +import com.refinedmods.refinedstorage.common.api.grid.view.PlatformGridResource; import com.refinedmods.refinedstorage.common.api.storage.PlayerActor; import com.refinedmods.refinedstorage.common.api.support.registry.PlatformRegistry; import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; @@ -39,7 +40,7 @@ import java.util.Map; import java.util.Set; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import javax.annotation.Nullable; import net.minecraft.server.level.ServerPlayer; @@ -100,10 +101,10 @@ protected AbstractGridContainerMenu( this.active = gridData.active(); final GridViewBuilder viewBuilder = createViewBuilder(); - gridData.resources().forEach(gridResource -> viewBuilder.withResource( - gridResource.resourceAmount().getResource(), - gridResource.resourceAmount().getAmount(), - gridResource.trackedResource().orElse(null) + gridData.resources().forEach(resource -> viewBuilder.withResource( + resource.resourceAmount().resource(), + resource.resourceAmount().amount(), + resource.trackedResource().orElse(null) )); this.view = viewBuilder.build(); @@ -137,12 +138,13 @@ protected AbstractGridContainerMenu( initStrategies((ServerPlayer) playerInventory.player); } - private Predicate filterResourceType() { - return gridResource -> Platform.INSTANCE.getConfig().getGrid().getResourceType().flatMap(resourceTypeId -> + private BiPredicate filterResourceType() { + return (v, resource) -> resource instanceof PlatformGridResource platformResource + && Platform.INSTANCE.getConfig().getGrid().getResourceType().flatMap(resourceTypeId -> RefinedStorageApi.INSTANCE .getResourceTypeRegistry() .get(resourceTypeId) - .map(type -> type.isGridResourceBelonging(gridResource)) + .map(platformResource::belongsToResourceType) ).orElse(true); } @@ -199,7 +201,7 @@ private boolean onSearchTextChanged(final String text) { view.setFilterAndSort(QUERY_PARSER.parse(text).and(filterResourceType())); return true; } catch (GridQueryParserException e) { - view.setFilterAndSort(resource -> false); + view.setFilterAndSort((v, resource) -> false); return false; } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridContainerMenu.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridContainerMenu.java index fd65608e6..5155a8448 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridContainerMenu.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridContainerMenu.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage.common.grid; import com.refinedmods.refinedstorage.api.grid.view.GridResource; +import com.refinedmods.refinedstorage.api.grid.view.GridView; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; import com.refinedmods.refinedstorage.common.content.Menus; import com.refinedmods.refinedstorage.common.grid.view.ItemGridResource; @@ -14,8 +15,8 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.BiPredicate; import java.util.function.Consumer; -import java.util.function.Predicate; import javax.annotation.Nullable; import net.minecraft.world.Container; @@ -35,7 +36,7 @@ public class CraftingGridContainerMenu extends AbstractGridContainerMenu { @Nullable private Consumer activenessListener; @Nullable - private Predicate filterBeforeFilteringBasedOnCraftingMatrixItems; + private BiPredicate filterBeforeFilteringBasedOnCraftingMatrixItems; public CraftingGridContainerMenu(final int syncId, final Inventory playerInventory, @@ -149,9 +150,9 @@ public void transferRecipe(final List> recipe) { public void filterBasedOnCraftingMatrixItems() { final Set craftingMatrixItems = getCraftingMatrixItems(); filterBeforeFilteringBasedOnCraftingMatrixItems = getView().setFilterAndSort( - gridResource -> gridResource instanceof ItemGridResource itemGridResource - && itemGridResource.getUnderlyingResource() != null - && craftingMatrixItems.contains((ItemResource) itemGridResource.getUnderlyingResource()) + (view, gridResource) -> gridResource instanceof ItemGridResource itemGridResource + && itemGridResource.getResourceForRecipeMods() != null + && craftingMatrixItems.contains((ItemResource) itemGridResource.getResourceForRecipeMods()) ); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridSourceImpl.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridSourceImpl.java index 08f3ade93..483dc69a3 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridSourceImpl.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/CraftingGridSourceImpl.java @@ -1,7 +1,6 @@ package com.refinedmods.refinedstorage.common.grid; import com.refinedmods.refinedstorage.api.network.storage.StorageNetworkComponent; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.common.support.CraftingMatrix; @@ -151,10 +150,6 @@ private void addPlayerInventoryItemsIntoList(final Player player, final Resource } private Comparator sortByHighestAvailableFirst(final ResourceList available) { - return Comparator.comparingLong(resource -> getAvailableAmount(available, resource)).reversed(); - } - - private long getAvailableAmount(final ResourceList available, final ItemResource resource) { - return available.get(resource).map(ResourceAmount::getAmount).orElse(0L); + return Comparator.comparingLong(available::get).reversed(); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypes.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypes.java index 9d38f3f33..29f2d5e4f 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypes.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypes.java @@ -10,7 +10,7 @@ import java.util.function.Function; public enum GridSortingTypes implements GridSortingType { - QUANTITY(view -> Comparator.comparingLong(GridResource::getAmount)), + QUANTITY(view -> Comparator.comparingLong(value -> value.getAmount(view))), NAME(view -> Comparator.comparing(GridResource::getName)), ID(view -> (a, b) -> { if (a instanceof PlatformGridResource aa && b instanceof PlatformGridResource bb) { diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/SnapshotCraftingGridRefillContext.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/SnapshotCraftingGridRefillContext.java index 2aae5c9e4..cd22c8832 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/SnapshotCraftingGridRefillContext.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/SnapshotCraftingGridRefillContext.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage.common.grid; import com.refinedmods.refinedstorage.api.core.Action; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; @@ -49,15 +50,18 @@ private void addAvailableItem(final RootStorage rootStorage, final ItemStack craftingMatrixStack) { final ItemResource craftingMatrixResource = ItemResource.ofItemStack(craftingMatrixStack); // a single resource can occur multiple times in a recipe, only add it once - if (available.get(craftingMatrixResource).isEmpty()) { - rootStorage.get(craftingMatrixResource).ifPresent(available::add); + if (!available.contains(craftingMatrixResource)) { + final long amount = rootStorage.get(craftingMatrixResource); + if (amount > 0) { + available.add(craftingMatrixResource, amount); + } } } @Override public boolean extract(final ItemResource resource, final Player player) { return blockEntity.getNetwork().map(network -> { - final boolean isAvailable = available.get(resource).isPresent(); + final boolean isAvailable = available.contains(resource); if (isAvailable) { available.remove(resource, 1); used.add(resource, 1); @@ -72,6 +76,9 @@ public void close() { } private void extractUsedItems(final RootStorage rootStorage) { - used.getAll().forEach(u -> rootStorage.extract(u.getResource(), u.getAmount(), Action.EXECUTE, playerActor)); + for (final ResourceKey usedResource : used.getAll()) { + final long amountUsed = used.get(usedResource); + rootStorage.extract(usedResource, amountUsed, Action.EXECUTE, playerActor); + } } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/screen/AbstractGridScreen.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/screen/AbstractGridScreen.java index 90a62268e..811da35ec 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/screen/AbstractGridScreen.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/screen/AbstractGridScreen.java @@ -262,7 +262,7 @@ private void renderAmount(final GuiGraphics graphics, if (!(resource instanceof PlatformGridResource platformResource)) { return; } - final String text = resource.isZeroed() ? "0" : platformResource.getDisplayedAmount(); + final String text = resource.isZeroed() ? "0" : platformResource.getDisplayedAmount(getMenu().getView()); final int color = resource.isZeroed() ? requireNonNullElse(ChatFormatting.RED.getColor(), 15) : requireNonNullElse(ChatFormatting.WHITE.getColor(), 15); @@ -319,7 +319,7 @@ private void renderHoveredResourceTooltip(final GuiGraphics graphics, addDetailedTooltip(view, platformResource, processedLines); } if (!platformResource.isZeroed()) { - processedLines.addAll(platformResource.getExtractionHints()); + processedLines.addAll(platformResource.getExtractionHints(getMenu().getView())); } Platform.INSTANCE.renderTooltip(graphics, processedLines, mouseX, mouseY); } @@ -327,7 +327,9 @@ private void renderHoveredResourceTooltip(final GuiGraphics graphics, private void addDetailedTooltip(final GridView view, final PlatformGridResource platformResource, final List lines) { - final String amountInTooltip = platformResource.isZeroed() ? "0" : platformResource.getAmountInTooltip(); + final String amountInTooltip = platformResource.isZeroed() + ? "0" + : platformResource.getAmountInTooltip(getMenu().getView()); lines.add(new SmallTextClientTooltipComponent( createTranslation("misc", "total", amountInTooltip).withStyle(ChatFormatting.GRAY) )); diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractFluidGridResourceFactory.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractFluidGridResourceFactory.java index 76083fcfe..27fa5fb16 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractFluidGridResourceFactory.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractFluidGridResourceFactory.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage.api.grid.view.GridResource; import com.refinedmods.refinedstorage.api.grid.view.GridResourceFactory; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.common.support.resource.FluidResource; import java.util.Optional; @@ -15,8 +15,8 @@ public abstract class AbstractFluidGridResourceFactory implements GridResourceFactory { @Override - public Optional apply(final ResourceAmount resourceAmount) { - if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + public Optional apply(final ResourceKey resource) { + if (!(resource instanceof FluidResource fluidResource)) { return Optional.empty(); } final String name = getName(fluidResource); @@ -25,7 +25,7 @@ public Optional apply(final ResourceAmount resourceAmount) { final Set tags = getTags(fluidResource.fluid()); final String tooltip = getTooltip(fluidResource); return Optional.of(new FluidGridResource( - resourceAmount, + fluidResource, name, modId, modName, diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractItemGridResourceFactory.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractItemGridResourceFactory.java index ad6b897bd..fe3af6975 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractItemGridResourceFactory.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/AbstractItemGridResourceFactory.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage.api.grid.view.GridResource; import com.refinedmods.refinedstorage.api.grid.view.GridResourceFactory; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.common.support.resource.ItemResource; import java.util.Optional; @@ -18,8 +18,8 @@ public abstract class AbstractItemGridResourceFactory implements GridResourceFactory { @Override - public Optional apply(final ResourceAmount resourceAmount) { - if (!(resourceAmount.getResource() instanceof ItemResource itemResource)) { + public Optional apply(final ResourceKey resource) { + if (!(resource instanceof ItemResource itemResource)) { return Optional.empty(); } final Item item = itemResource.item(); @@ -30,7 +30,7 @@ public Optional apply(final ResourceAmount resourceAmount) { final Set tags = getTags(item); final String tooltip = getTooltip(itemStack); return Optional.of(new ItemGridResource( - resourceAmount, + itemResource, itemStack, name, modId, diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/CompositeGridResourceFactory.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/CompositeGridResourceFactory.java index fe82452de..fad231cfa 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/CompositeGridResourceFactory.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/CompositeGridResourceFactory.java @@ -2,7 +2,7 @@ import com.refinedmods.refinedstorage.api.grid.view.GridResource; import com.refinedmods.refinedstorage.api.grid.view.GridResourceFactory; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.common.api.support.registry.PlatformRegistry; import com.refinedmods.refinedstorage.common.api.support.resource.ResourceType; @@ -16,10 +16,10 @@ public CompositeGridResourceFactory(final PlatformRegistry resourc } @Override - public Optional apply(final ResourceAmount resourceAmount) { + public Optional apply(final ResourceKey resource) { return resourceTypeRegistry.getAll() .stream() - .flatMap(type -> type.toGridResource(resourceAmount).stream()) + .flatMap(type -> type.toGridResource(resource).stream()) .findFirst(); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/FluidGridResource.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/FluidGridResource.java index bd042f156..9571ec6dc 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/FluidGridResource.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/FluidGridResource.java @@ -1,23 +1,23 @@ package com.refinedmods.refinedstorage.common.grid.view; import com.refinedmods.refinedstorage.api.grid.operations.GridExtractMode; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.grid.view.GridView; import com.refinedmods.refinedstorage.common.Platform; import com.refinedmods.refinedstorage.common.api.grid.GridResourceAttributeKeys; import com.refinedmods.refinedstorage.common.api.grid.GridScrollMode; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage.common.api.grid.view.AbstractPlatformGridResource; -import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage.common.api.support.resource.ResourceType; import com.refinedmods.refinedstorage.common.support.resource.FluidResource; import com.refinedmods.refinedstorage.common.support.resource.FluidResourceRendering; +import com.refinedmods.refinedstorage.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage.common.support.tooltip.MouseClientTooltipComponent; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import javax.annotation.Nullable; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; @@ -25,24 +25,22 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.inventory.tooltip.TooltipComponent; -public class FluidGridResource extends AbstractPlatformGridResource { - private final FluidResource fluidResource; +public class FluidGridResource extends AbstractPlatformGridResource { private final int id; - public FluidGridResource(final ResourceAmount resourceAmount, + public FluidGridResource(final FluidResource resource, final String name, final String modId, final String modName, final Set tags, final String tooltip) { - super(resourceAmount, name, Map.of( + super(resource, name, Map.of( GridResourceAttributeKeys.MOD_ID, Set.of(modId), GridResourceAttributeKeys.MOD_NAME, Set.of(modName), GridResourceAttributeKeys.TAGS, tags, GridResourceAttributeKeys.TOOLTIP, Set.of(tooltip) )); - this.fluidResource = (FluidResource) resourceAmount.getResource(); - this.id = BuiltInRegistries.FLUID.getId(fluidResource.fluid()); + this.id = BuiltInRegistries.FLUID.getId(resource.fluid()); } @Override @@ -51,25 +49,19 @@ public int getRegistryId() { } @Override - public List getExtractionHints() { - return Platform.INSTANCE.getFilledBucket(fluidResource).map(bucket -> MouseClientTooltipComponent.item( + public List getExtractionHints(final GridView view) { + return Platform.INSTANCE.getFilledBucket(resource).map(bucket -> MouseClientTooltipComponent.item( MouseClientTooltipComponent.Type.LEFT, bucket, null )).stream().toList(); } - @Nullable - @Override - public PlatformResourceKey getUnderlyingResource() { - return fluidResource; - } - @Override public void onExtract(final GridExtractMode extractMode, final boolean cursor, final GridExtractionStrategy extractionStrategy) { - extractionStrategy.onExtract(fluidResource, extractMode, cursor); + extractionStrategy.onExtract(resource, extractMode, cursor); } @Override @@ -79,22 +71,27 @@ public void onScroll(final GridScrollMode scrollMode, final GridScrollingStrateg @Override public void render(final GuiGraphics graphics, final int x, final int y) { - Platform.INSTANCE.getFluidRenderer().render(graphics.pose(), x, y, fluidResource); + Platform.INSTANCE.getFluidRenderer().render(graphics.pose(), x, y, resource); + } + + @Override + public String getDisplayedAmount(final GridView view) { + return FluidResourceRendering.formatWithUnits(getAmount(view)); } @Override - public String getDisplayedAmount() { - return FluidResourceRendering.formatWithUnits(getAmount()); + public String getAmountInTooltip(final GridView view) { + return FluidResourceRendering.format(getAmount(view)); } @Override - public String getAmountInTooltip() { - return FluidResourceRendering.format(getAmount()); + public boolean belongsToResourceType(final ResourceType resourceType) { + return resourceType == ResourceTypes.FLUID; } @Override public List getTooltip() { - return Platform.INSTANCE.getFluidRenderer().getTooltip(fluidResource); + return Platform.INSTANCE.getFluidRenderer().getTooltip(resource); } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/ItemGridResource.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/ItemGridResource.java index da0b5d98c..c5497557e 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/ItemGridResource.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/grid/view/ItemGridResource.java @@ -1,22 +1,22 @@ package com.refinedmods.refinedstorage.common.grid.view; import com.refinedmods.refinedstorage.api.grid.operations.GridExtractMode; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.grid.view.GridView; import com.refinedmods.refinedstorage.common.api.grid.GridResourceAttributeKeys; import com.refinedmods.refinedstorage.common.api.grid.GridScrollMode; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridExtractionStrategy; import com.refinedmods.refinedstorage.common.api.grid.strategy.GridScrollingStrategy; import com.refinedmods.refinedstorage.common.api.grid.view.AbstractPlatformGridResource; import com.refinedmods.refinedstorage.common.api.support.AmountFormatting; -import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; +import com.refinedmods.refinedstorage.common.api.support.resource.ResourceType; import com.refinedmods.refinedstorage.common.support.resource.ItemResource; +import com.refinedmods.refinedstorage.common.support.resource.ResourceTypes; import com.refinedmods.refinedstorage.common.support.tooltip.MouseClientTooltipComponent; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -28,26 +28,24 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -public class ItemGridResource extends AbstractPlatformGridResource { +public class ItemGridResource extends AbstractPlatformGridResource { private final int id; private final ItemStack itemStack; - private final ItemResource itemResource; - public ItemGridResource(final ResourceAmount resourceAmount, + public ItemGridResource(final ItemResource resource, final ItemStack itemStack, final String name, final String modId, final String modName, final Set tags, final String tooltip) { - super(resourceAmount, name, Map.of( + super(resource, name, Map.of( GridResourceAttributeKeys.MOD_ID, Set.of(modId), GridResourceAttributeKeys.MOD_NAME, Set.of(modName), GridResourceAttributeKeys.TAGS, tags, GridResourceAttributeKeys.TOOLTIP, Set.of(tooltip) )); - this.itemResource = (ItemResource) resourceAmount.getResource(); - this.id = Item.getId(itemResource.item()); + this.id = Item.getId(resource.item()); this.itemStack = itemStack; } @@ -55,20 +53,15 @@ public ItemStack getItemStack() { return itemStack; } - @Nullable - @Override - public PlatformResourceKey getUnderlyingResource() { - return itemResource; - } - @Override public int getRegistryId() { return id; } @Override - public List getExtractionHints() { - final long extractableAmount = Math.min(getAmount(), itemStack.getMaxStackSize()); + public List getExtractionHints(final GridView view) { + final long amount = getAmount(view); + final long extractableAmount = Math.min(amount, itemStack.getMaxStackSize()); final long halfExtractionAmount = extractableAmount == 1 ? 1 : extractableAmount / 2; return List.of( MouseClientTooltipComponent.itemWithDecorations( @@ -88,12 +81,12 @@ public List getExtractionHints() { public void onExtract(final GridExtractMode extractMode, final boolean cursor, final GridExtractionStrategy extractionStrategy) { - extractionStrategy.onExtract(itemResource, extractMode, cursor); + extractionStrategy.onExtract(resource, extractMode, cursor); } @Override public void onScroll(final GridScrollMode scrollMode, final GridScrollingStrategy scrollingStrategy) { - scrollingStrategy.onScroll(itemResource, scrollMode, -1); + scrollingStrategy.onScroll(resource, scrollMode, -1); } @Override @@ -104,13 +97,18 @@ public void render(final GuiGraphics graphics, final int x, final int y) { } @Override - public String getDisplayedAmount() { - return AmountFormatting.formatWithUnits(getAmount()); + public String getDisplayedAmount(final GridView view) { + return AmountFormatting.formatWithUnits(getAmount(view)); + } + + @Override + public String getAmountInTooltip(final GridView view) { + return AmountFormatting.format(getAmount(view)); } @Override - public String getAmountInTooltip() { - return AmountFormatting.format(getAmount()); + public boolean belongsToResourceType(final ResourceType resourceType) { + return resourceType == ResourceTypes.ITEM; } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/iface/ExportedResourcesContainer.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/iface/ExportedResourcesContainer.java index afff56c66..b1df46029 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/iface/ExportedResourcesContainer.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/iface/ExportedResourcesContainer.java @@ -12,7 +12,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.stream.Collectors; import javax.annotation.Nullable; public class ExportedResourcesContainer extends ResourceContainerImpl implements InterfaceExportState { @@ -42,11 +41,7 @@ public Collection expandExportCandidates(final RootStorage rootStor if (!(rootStorage instanceof FuzzyRootStorage fuzzyRootStorage)) { return Collections.singletonList(resource); } - return fuzzyRootStorage - .getFuzzy(resource) - .stream() - .map(ResourceAmount::getResource) - .collect(Collectors.toSet()); + return fuzzyRootStorage.getFuzzy(resource); } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/StorageCodecs.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/StorageCodecs.java index 9ec837f8f..cfd0c8031 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/StorageCodecs.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/StorageCodecs.java @@ -67,7 +67,7 @@ static StorageData ofSameTypeStorage( ? Optional.of(limitedStorage.getCapacity()) : Optional.empty(); final List> resources = storage.getAll().stream() - .filter(resourceAmount -> valid.test(resourceAmount.getResource())) + .filter(resourceAmount -> valid.test(resourceAmount.resource())) .map(resourceAmount -> getResource(storage, caster, resourceAmount)) .toList(); return new StorageData<>(capacity, resources); @@ -79,8 +79,8 @@ private static StorageResource getResource( final ResourceAmount resourceAmount ) { return new StorageResource<>( - caster.apply(resourceAmount.getResource()), - resourceAmount.getAmount(), + caster.apply(resourceAmount.resource()), + resourceAmount.amount(), getChanged(storage, resourceAmount) ); } @@ -90,7 +90,7 @@ private static Optional getChanged(final Storage storage, if (!(storage instanceof TrackedStorage trackedStorage)) { return Optional.empty(); } - return trackedStorage.findTrackedResourceByActorType(resourceAmount.getResource(), PlayerActor.class) + return trackedStorage.findTrackedResourceByActorType(resourceAmount.resource(), PlayerActor.class) .map(StorageChangedByAt::ofTrackedResource); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/portablegrid/PortableGrid.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/portablegrid/PortableGrid.java index 22e2c6dde..90d548274 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/portablegrid/PortableGrid.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storage/portablegrid/PortableGrid.java @@ -106,7 +106,7 @@ public List getResources(final Class act final RootStorage rootStorage = storage.getRootStorage(); return rootStorage.getAll().stream().map(resource -> new TrackedResourceAmount( resource, - rootStorage.findTrackedResourceByActorType(resource.getResource(), actorType).orElse(null) + rootStorage.findTrackedResourceByActorType(resource.resource(), actorType).orElse(null) )).toList(); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storagemonitor/StorageMonitorBlockEntity.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storagemonitor/StorageMonitorBlockEntity.java index 443fd19d2..052685ee9 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storagemonitor/StorageMonitorBlockEntity.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/storagemonitor/StorageMonitorBlockEntity.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage.api.network.Network; import com.refinedmods.refinedstorage.api.network.impl.node.SimpleNetworkNode; import com.refinedmods.refinedstorage.api.network.storage.StorageNetworkComponent; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.Platform; @@ -102,9 +101,12 @@ private long getAmount() { private long getAmount(final Network network, final ResourceKey configuredResource) { final RootStorage rootStorage = network.getComponent(StorageNetworkComponent.class); if (!filter.isFuzzyMode() || !(rootStorage instanceof FuzzyRootStorage fuzzyRootStorage)) { - return rootStorage.get(configuredResource).map(ResourceAmount::getAmount).orElse(0L); + return rootStorage.get(configuredResource); } - return fuzzyRootStorage.getFuzzy(configuredResource).stream().mapToLong(ResourceAmount::getAmount).sum(); + return fuzzyRootStorage.getFuzzy(configuredResource) + .stream() + .mapToLong(rootStorage::get) + .sum(); } public void extract(final Player player) { diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/AbstractBaseScreen.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/AbstractBaseScreen.java index 713e825c2..a1c8f07e6 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/AbstractBaseScreen.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/AbstractBaseScreen.java @@ -250,7 +250,7 @@ private List getResourceSlotHelpTooltip(final ItemStack resourceSlot.getPrimaryResourceFactory().create(carried).ifPresent(primaryResourceInstance -> lines.add( MouseClientTooltipComponent.resource( MouseClientTooltipComponent.Type.LEFT, - primaryResourceInstance.getResource(), + primaryResourceInstance.resource(), null ) )); @@ -258,7 +258,7 @@ private List getResourceSlotHelpTooltip(final ItemStack final var result = alternativeResourceFactory.create(carried); result.ifPresent(alternativeResourceInstance -> lines.add(MouseClientTooltipComponent.resource( MouseClientTooltipComponent.Type.RIGHT, - alternativeResourceInstance.getResource(), + alternativeResourceInstance.resource(), null ))); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/network/component/PlatformStorageNetworkComponent.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/network/component/PlatformStorageNetworkComponent.java index 0ed1f5fd8..fffbad02c 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/network/component/PlatformStorageNetworkComponent.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/network/component/PlatformStorageNetworkComponent.java @@ -1,7 +1,6 @@ package com.refinedmods.refinedstorage.common.support.network.component; import com.refinedmods.refinedstorage.api.network.impl.storage.StorageNetworkComponentImpl; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.common.api.storage.root.FuzzyRootStorage; @@ -23,7 +22,7 @@ private PlatformStorageNetworkComponent(final FuzzyResourceList fuzzyResourceLis } @Override - public Collection getFuzzy(final ResourceKey resource) { + public Collection getFuzzy(final ResourceKey resource) { return fuzzyResourceList.getFuzzy(resource); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/FluidResourceType.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/FluidResourceType.java index 30e19026d..acfbf46b4 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/FluidResourceType.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/FluidResourceType.java @@ -3,13 +3,12 @@ import com.refinedmods.refinedstorage.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage.api.grid.operations.GridOperationsImpl; import com.refinedmods.refinedstorage.api.grid.view.GridResource; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.Actor; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.Platform; import com.refinedmods.refinedstorage.common.api.support.resource.AbstractResourceType; import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; -import com.refinedmods.refinedstorage.common.grid.view.FluidGridResource; import com.refinedmods.refinedstorage.common.support.TextureIds; import java.util.Optional; @@ -32,13 +31,8 @@ class FluidResourceType extends AbstractResourceType { } @Override - public Optional toGridResource(final ResourceAmount resourceAmount) { - return Platform.INSTANCE.getFluidGridResourceFactory().apply(resourceAmount); - } - - @Override - public boolean isGridResourceBelonging(final GridResource gridResource) { - return gridResource instanceof FluidGridResource; + public Optional toGridResource(final ResourceKey resource) { + return Platform.INSTANCE.getFluidGridResourceFactory().apply(resource); } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ItemResourceType.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ItemResourceType.java index db994cb0b..be6006f86 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ItemResourceType.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ItemResourceType.java @@ -3,13 +3,12 @@ import com.refinedmods.refinedstorage.api.grid.operations.GridOperations; import com.refinedmods.refinedstorage.api.grid.operations.GridOperationsImpl; import com.refinedmods.refinedstorage.api.grid.view.GridResource; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.Actor; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.Platform; import com.refinedmods.refinedstorage.common.api.support.resource.AbstractResourceType; import com.refinedmods.refinedstorage.common.api.support.resource.PlatformResourceKey; -import com.refinedmods.refinedstorage.common.grid.view.ItemGridResource; import com.refinedmods.refinedstorage.common.support.TextureIds; import java.util.Optional; @@ -32,13 +31,8 @@ class ItemResourceType extends AbstractResourceType { } @Override - public Optional toGridResource(final ResourceAmount resourceAmount) { - return Platform.INSTANCE.getItemGridResourceFactory().apply(resourceAmount); - } - - @Override - public boolean isGridResourceBelonging(final GridResource gridResource) { - return gridResource instanceof ItemGridResource; + public Optional toGridResource(final ResourceKey resource) { + return Platform.INSTANCE.getItemGridResourceFactory().apply(resource); } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceCodecs.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceCodecs.java index 2c1e07eaa..2ebd5e36f 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceCodecs.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceCodecs.java @@ -37,8 +37,8 @@ public final class ResourceCodecs { .codec() .dispatch(PlatformResourceKey::getResourceType, ResourceType::getMapCodec); public static final Codec AMOUNT_CODEC = RecordCodecBuilder.create(instance -> instance.group( - CODEC.fieldOf("resource").forGetter(resourceAmount -> (PlatformResourceKey) resourceAmount.getResource()), - Codec.LONG.fieldOf("amount").forGetter(ResourceAmount::getAmount) + CODEC.fieldOf("resource").forGetter(resourceAmount -> (PlatformResourceKey) resourceAmount.resource()), + Codec.LONG.fieldOf("amount").forGetter(ResourceAmount::amount) ).apply(instance, ResourceAmount::new)); public static final Codec> AMOUNT_OPTIONAL_CODEC = AMOUNT_CODEC.optionalFieldOf("resource") .codec(); @@ -64,12 +64,12 @@ public void encode(final RegistryFriendlyByteBuf buf, final PlatformResourceKey }; public static final StreamCodec AMOUNT_STREAM_CODEC = StreamCodec.of( (buf, resourceAmount) -> { - final ResourceKey resourceKey = resourceAmount.getResource(); + final ResourceKey resourceKey = resourceAmount.resource(); if (!(resourceKey instanceof PlatformResourceKey platformResourceKey)) { throw new DecoderException("Cannot encode non-platform resource key"); } STREAM_CODEC.encode(buf, platformResourceKey); - buf.writeLong(resourceAmount.getAmount()); + buf.writeLong(resourceAmount.amount()); }, buf -> { final PlatformResourceKey resourceKey = STREAM_CODEC.decode(buf); diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerImpl.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerImpl.java index 8e62a7724..287d1865d 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerImpl.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerImpl.java @@ -95,7 +95,7 @@ public long getAmount(final int index) { if (slot == null) { return 0; } - return slot.getResourceAmount().getAmount(); + return slot.getResourceAmount().amount(); } @Override @@ -116,7 +116,7 @@ public void setAmount(final int index, final long amount) { if (slot == null) { return; } - final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(slot.getResourceAmount().getResource())); + final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(slot.getResourceAmount().resource())); if (newAmount == 0) { remove(index); } else { @@ -190,7 +190,7 @@ public Set getUniqueResources() { if (slot == null) { continue; } - result.add(slot.getResourceAmount().getResource()); + result.add(slot.getResourceAmount().resource()); } return result; } @@ -203,7 +203,7 @@ public List getResources() { if (slot == null) { continue; } - result.add(slot.getResourceAmount().getResource()); + result.add(slot.getResourceAmount().resource()); } return result; } @@ -290,7 +290,7 @@ public long insert(final ResourceKey resource, final long amount, final Action a final ResourceAmount slot = get(i); if (slot == null) { remainder -= insertIntoEmptySlot(i, platformResource, action, remainder); - } else if (slot.getResource().equals(resource)) { + } else if (slot.resource().equals(resource)) { remainder -= insertIntoExistingSlot( i, platformResource, @@ -322,7 +322,7 @@ private long insertIntoExistingSlot(final int slotIndex, final Action action, final long amount, final ResourceAmount existing) { - final long spaceRemaining = resource.getInterfaceExportLimit() - existing.getAmount(); + final long spaceRemaining = resource.getInterfaceExportLimit() - existing.amount(); final long inserted = Math.min(spaceRemaining, amount); if (action == Action.EXECUTE) { grow(slotIndex, inserted); @@ -335,11 +335,11 @@ public long extract(final ResourceKey resource, final long amount, final Action long extracted = 0; for (int i = 0; i < size(); ++i) { final ResourceAmount slotContents = get(i); - if (slotContents == null || !resource.equals(slotContents.getResource())) { + if (slotContents == null || !resource.equals(slotContents.resource())) { continue; } final long stillNeeded = amount - extracted; - final long toExtract = Math.min(slotContents.getAmount(), stillNeeded); + final long toExtract = Math.min(slotContents.amount(), stillNeeded); if (action == Action.EXECUTE) { shrink(i, toExtract); } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerSlot.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerSlot.java index b8eff1aed..fed125bb0 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerSlot.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/ResourceContainerSlot.java @@ -13,8 +13,8 @@ class ResourceContainerSlot { ResourceContainerSlot(final ResourceAmount resourceAmount) { this.resourceAmount = resourceAmount; - this.stackRepresentation = resourceAmount.getResource() instanceof ItemResource itemResource - ? itemResource.toItemStack(resourceAmount.getAmount()) + this.stackRepresentation = resourceAmount.resource() instanceof ItemResource itemResource + ? itemResource.toItemStack(resourceAmount.amount()) : ItemStack.EMPTY; } @@ -23,7 +23,7 @@ ResourceAmount getResourceAmount() { } PlatformResourceKey getPlatformResource() { - return (PlatformResourceKey) resourceAmount.getResource(); + return (PlatformResourceKey) resourceAmount.resource(); } ItemStack getStackRepresentation() { @@ -31,7 +31,7 @@ ItemStack getStackRepresentation() { } ResourceContainerSlot withAmount(final long newAmount) { - return new ResourceContainerSlot(new ResourceAmount(resourceAmount.getResource(), newAmount)); + return new ResourceContainerSlot(new ResourceAmount(resourceAmount.resource(), newAmount)); } @Override diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImpl.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImpl.java index ad6eb1bff..71f2254cf 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImpl.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImpl.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage.common.support.resource.list; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.AbstractProxyResourceList; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; @@ -16,7 +15,7 @@ import java.util.Set; public class FuzzyResourceListImpl extends AbstractProxyResourceList implements FuzzyResourceList { - private final Map> normalizedFuzzyMap = new HashMap<>(); + private final Map> normalizedFuzzyMap = new HashMap<>(); public FuzzyResourceListImpl(final ResourceList delegate) { super(delegate); @@ -31,8 +30,7 @@ public OperationResult add(final ResourceKey resource, final long amount) { private void addToIndex(final ResourceKey resource, final OperationResult result) { if (resource instanceof FuzzyModeNormalizer normalizer) { - normalizedFuzzyMap.computeIfAbsent(normalizer.normalize(), k -> new HashSet<>()) - .add(result.resourceAmount()); + normalizedFuzzyMap.computeIfAbsent(normalizer.normalize(), k -> new HashSet<>()).add(result.resource()); } } @@ -51,21 +49,25 @@ private void removeFromIndex(final ResourceKey resource, final OperationResult r return; } final ResourceKey normalized = normalizer.normalize(); - final Collection index = normalizedFuzzyMap.get(normalized); + final Collection index = normalizedFuzzyMap.get(normalized); if (index == null) { return; } - index.remove(result.resourceAmount()); + index.remove(result.resource()); if (index.isEmpty()) { normalizedFuzzyMap.remove(normalized); } } @Override - public Collection getFuzzy(final ResourceKey resource) { + public Collection getFuzzy(final ResourceKey resource) { if (resource instanceof FuzzyModeNormalizer normalizer) { - return normalizedFuzzyMap.getOrDefault(normalizer.normalize(), Collections.emptySet()); + return Collections.unmodifiableCollection( + normalizedFuzzyMap.getOrDefault(normalizer.normalize(), Collections.emptySet()) + ); } - return normalizedFuzzyMap.getOrDefault(resource, Collections.emptySet()); + return Collections.unmodifiableCollection( + normalizedFuzzyMap.getOrDefault(resource, Collections.emptySet()) + ); } } diff --git a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/tooltip/ResourceClientTooltipComponent.java b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/tooltip/ResourceClientTooltipComponent.java index c5bb0b3a4..4a43b83f1 100644 --- a/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/tooltip/ResourceClientTooltipComponent.java +++ b/refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/support/tooltip/ResourceClientTooltipComponent.java @@ -33,8 +33,8 @@ public int getWidth(final Font font) { @Override public void renderImage(final Font font, final int x, final int y, final GuiGraphics graphics) { - RefinedStorageApi.INSTANCE.getResourceRendering(resourceAmount.getResource()).render( - resourceAmount.getResource(), + RefinedStorageApi.INSTANCE.getResourceRendering(resourceAmount.resource()).render( + resourceAmount.resource(), graphics, x, y @@ -50,10 +50,10 @@ public void renderImage(final Font font, final int x, final int y, final GuiGrap private static Component getNameWithAmount(final ResourceAmount resourceAmount) { final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering( - resourceAmount.getResource() + resourceAmount.resource() ); - final String amount = rendering.getDisplayedAmount(resourceAmount.getAmount(), true); - final Component displayName = rendering.getDisplayName(resourceAmount.getResource()); + final String amount = rendering.getDisplayedAmount(resourceAmount.amount(), true); + final Component displayName = rendering.getDisplayName(resourceAmount.resource()); if (amount.isEmpty()) { return displayName; } diff --git a/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypesTest.java b/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypesTest.java index 3d22021ab..76a93c453 100644 --- a/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypesTest.java +++ b/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/grid/GridSortingTypesTest.java @@ -49,7 +49,7 @@ void setUp() { viewBuilder = new GridViewBuilderImpl( FACTORY, view -> Comparator.comparing(GridResource::getName), - view -> Comparator.comparing(GridResource::getAmount) + view -> Comparator.comparingLong(resource -> resource.getAmount(view)) ); dirt = new ItemResource(Items.DIRT, DataComponentPatch.EMPTY); stone = new ItemResource(Items.STONE, DataComponentPatch.EMPTY); diff --git a/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImplTest.java b/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImplTest.java index d067faa78..5660e7a86 100644 --- a/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImplTest.java +++ b/refinedstorage-common/src/test/java/com/refinedmods/refinedstorage/common/support/resource/list/FuzzyResourceListImplTest.java @@ -1,13 +1,12 @@ package com.refinedmods.refinedstorage.common.support.resource.list; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.common.SetupMinecraft; import com.refinedmods.refinedstorage.common.api.support.resource.list.FuzzyResourceList; import com.refinedmods.refinedstorage.common.support.resource.ItemResource; import java.util.Collection; -import java.util.Optional; import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.component.DataComponents; @@ -37,7 +36,6 @@ void setUp() { } @Test - @SuppressWarnings("AssertBetweenInconvertibleTypes") void testRetrievingFuzzy() { // Arrange sut.add(DUMMY_A, 5); @@ -52,48 +50,45 @@ void testRetrievingFuzzy() { sut.add(DUMMY_D, 15); // Act - final Optional strictA = sut.get(DUMMY_A); - final Optional strictB = sut.get(DUMMY_B); - final Optional strictC = sut.get(DUMMY_C); - final Optional strictD = sut.get(DUMMY_D); - final Optional strictE = sut.get(DUMMY_E); - - final Collection fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection fuzzyE = sut.getFuzzy(DUMMY_E); + final long strictA = sut.get(DUMMY_A); + final long strictB = sut.get(DUMMY_B); + final long strictC = sut.get(DUMMY_C); + final long strictD = sut.get(DUMMY_D); + final long strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert - assertThat(strictA).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_A, 1)); - assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_B, 15)); - assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_C, 20)); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); - assertThat(strictE).isNotPresent(); + assertThat(strictA).isEqualTo(1); + assertThat(strictB).isEqualTo(15); + assertThat(strictC).isEqualTo(20); + assertThat(strictD).isEqualTo(25); + assertThat(strictE).isZero(); assertThat(fuzzyA).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_A, 1), - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) + DUMMY_A, + DUMMY_B, + DUMMY_C ); assertThat(fuzzyB).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_A, 1), - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) + DUMMY_A, + DUMMY_B, + DUMMY_C ); assertThat(fuzzyC).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_A, 1), - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) - ); - assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_D, 25) + DUMMY_A, + DUMMY_B, + DUMMY_C ); + assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactly(DUMMY_D); assertThat(fuzzyE).isEmpty(); } @Test - @SuppressWarnings("AssertBetweenInconvertibleTypes") void shouldRemoveEntireResourceFromFuzzyIndexAfterRemoval() { // Arrange sut.add(DUMMY_A, 5); @@ -110,36 +105,33 @@ void shouldRemoveEntireResourceFromFuzzyIndexAfterRemoval() { sut.add(DUMMY_D, 15); // Act - final Optional strictA = sut.get(DUMMY_A); - final Optional strictB = sut.get(DUMMY_B); - final Optional strictC = sut.get(DUMMY_C); - final Optional strictD = sut.get(DUMMY_D); - final Optional strictE = sut.get(DUMMY_E); - - final Collection fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection fuzzyE = sut.getFuzzy(DUMMY_E); + final long strictA = sut.get(DUMMY_A); + final long strictB = sut.get(DUMMY_B); + final long strictC = sut.get(DUMMY_C); + final long strictD = sut.get(DUMMY_D); + final long strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert - assertThat(strictA).isNotPresent(); - assertThat(strictB).isNotPresent(); - assertThat(strictC).isNotPresent(); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); - assertThat(strictE).isNotPresent(); + assertThat(strictA).isZero(); + assertThat(strictB).isZero(); + assertThat(strictC).isZero(); + assertThat(strictD).isEqualTo(25); + assertThat(strictE).isZero(); assertThat(fuzzyA).isEmpty(); assertThat(fuzzyB).isEmpty(); assertThat(fuzzyC).isEmpty(); - assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_D, 25) - ); + assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactly(DUMMY_D); assertThat(fuzzyE).isEmpty(); } @Test - @SuppressWarnings("AssertBetweenInconvertibleTypes") void shouldRemoveSingleResourceFromFuzzyIndexAfterRemoval() { // Arrange sut.add(DUMMY_A, 5); @@ -154,40 +146,38 @@ void shouldRemoveSingleResourceFromFuzzyIndexAfterRemoval() { sut.add(DUMMY_D, 15); // Act - final Optional strictA = sut.get(DUMMY_A); - final Optional strictB = sut.get(DUMMY_B); - final Optional strictC = sut.get(DUMMY_C); - final Optional strictD = sut.get(DUMMY_D); - final Optional strictE = sut.get(DUMMY_E); - - final Collection fuzzyA = sut.getFuzzy(DUMMY_A); - final Collection fuzzyB = sut.getFuzzy(DUMMY_B); - final Collection fuzzyC = sut.getFuzzy(DUMMY_C); - final Collection fuzzyD = sut.getFuzzy(DUMMY_D); - final Collection fuzzyE = sut.getFuzzy(DUMMY_E); + final long strictA = sut.get(DUMMY_A); + final long strictB = sut.get(DUMMY_B); + final long strictC = sut.get(DUMMY_C); + final long strictD = sut.get(DUMMY_D); + final long strictE = sut.get(DUMMY_E); + + final Collection fuzzyA = sut.getFuzzy(DUMMY_A); + final Collection fuzzyB = sut.getFuzzy(DUMMY_B); + final Collection fuzzyC = sut.getFuzzy(DUMMY_C); + final Collection fuzzyD = sut.getFuzzy(DUMMY_D); + final Collection fuzzyE = sut.getFuzzy(DUMMY_E); // Assert - assertThat(strictA).isNotPresent(); - assertThat(strictB).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_B, 15)); - assertThat(strictC).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_C, 20)); - assertThat(strictD).get().usingRecursiveComparison().isEqualTo(new ResourceAmount(DUMMY_D, 25)); - assertThat(strictE).isNotPresent(); + assertThat(strictA).isZero(); + assertThat(strictB).isEqualTo(15); + assertThat(strictC).isEqualTo(20); + assertThat(strictD).isEqualTo(25); + assertThat(strictE).isZero(); assertThat(fuzzyA).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) + DUMMY_B, + DUMMY_C ); assertThat(fuzzyB).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) + DUMMY_B, + DUMMY_C ); assertThat(fuzzyC).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_B, 15), - new ResourceAmount(DUMMY_C, 20) - ); - assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount(DUMMY_D, 25) + DUMMY_B, + DUMMY_C ); + assertThat(fuzzyD).usingRecursiveFieldByFieldElementComparator().containsExactly(DUMMY_D); assertThat(fuzzyE).isEmpty(); } } diff --git a/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/PlatformImpl.java b/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/PlatformImpl.java index 6cdaf7999..840267efc 100644 --- a/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/PlatformImpl.java +++ b/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/PlatformImpl.java @@ -175,7 +175,7 @@ public Optional drainContainer(final ItemStack container) @Override public Optional fillContainer(final ItemStack container, final ResourceAmount resourceAmount) { - if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + if (!(resourceAmount.resource() instanceof FluidResource fluidResource)) { return Optional.empty(); } final SimpleSingleStackStorage interceptingStorage = new SimpleSingleStackStorage(container); @@ -186,7 +186,7 @@ public Optional fillContainer(final ItemStack container, return Optional.empty(); } try (Transaction tx = Transaction.openOuter()) { - final long inserted = storage.insert(toFluidVariant(fluidResource), resourceAmount.getAmount(), tx); + final long inserted = storage.insert(toFluidVariant(fluidResource), resourceAmount.amount(), tx); return Optional.of(new FluidOperationResult( interceptingStorage.getStack(), fluidResource, diff --git a/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/support/resource/ResourceContainerFluidStorageAdapter.java b/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/support/resource/ResourceContainerFluidStorageAdapter.java index ab9b06a3e..222d680db 100644 --- a/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/support/resource/ResourceContainerFluidStorageAdapter.java +++ b/refinedstorage-fabric/src/main/java/com/refinedmods/refinedstorage/fabric/support/resource/ResourceContainerFluidStorageAdapter.java @@ -88,11 +88,11 @@ private StorageViewImpl(final int index) { public long extract(final FluidVariant resource, final long maxAmount, final TransactionContext transaction) { final ResourceAmount resourceAmount = resourceContainer.get(index); if (resourceAmount == null - || !(resourceAmount.getResource() instanceof FluidResource fluidResource) + || !(resourceAmount.resource() instanceof FluidResource fluidResource) || !resource.equals(toFluidVariant(fluidResource))) { return 0; } - final long extracted = Math.min(maxAmount, resourceAmount.getAmount()); + final long extracted = Math.min(maxAmount, resourceAmount.amount()); if (extracted > 0) { updateSnapshots(transaction); } diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/operations/GridOperationsImpl.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/operations/GridOperationsImpl.java index d4b1d3476..5816432d4 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/operations/GridOperationsImpl.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/operations/GridOperationsImpl.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage.api.grid.operations; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.Actor; import com.refinedmods.refinedstorage.api.storage.ExtractableStorage; @@ -53,7 +52,7 @@ private long getExtractableAmount(final ResourceKey resource, final GridExtractM } private long getExtractableAmount(final ResourceKey resource) { - final long totalSize = rootStorage.get(resource).map(ResourceAmount::getAmount).orElse(0L); + final long totalSize = rootStorage.get(resource); final long maxAmount = maxAmountProvider.applyAsLong(resource); return Math.min(totalSize, maxAmount); } diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParser.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParser.java index d188611e1..cb8396fd2 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParser.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParser.java @@ -1,12 +1,13 @@ package com.refinedmods.refinedstorage.api.grid.query; import com.refinedmods.refinedstorage.api.grid.view.GridResource; +import com.refinedmods.refinedstorage.api.grid.view.GridView; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") public interface GridQueryParser { - Predicate parse(String query) throws GridQueryParserException; + BiPredicate parse(String query) throws GridQueryParserException; } diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImpl.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImpl.java index a7a3e6ea0..4e957a183 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImpl.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImpl.java @@ -2,6 +2,7 @@ import com.refinedmods.refinedstorage.api.grid.view.GridResource; import com.refinedmods.refinedstorage.api.grid.view.GridResourceAttributeKey; +import com.refinedmods.refinedstorage.api.grid.view.GridView; import com.refinedmods.refinedstorage.query.lexer.Lexer; import com.refinedmods.refinedstorage.query.lexer.LexerException; import com.refinedmods.refinedstorage.query.lexer.LexerTokenMappings; @@ -25,7 +26,6 @@ import java.util.Map; import java.util.Set; import java.util.function.BiPredicate; -import java.util.function.Predicate; import org.apiguardian.api.API; @@ -44,9 +44,9 @@ public GridQueryParserImpl(final LexerTokenMappings tokenMappings, } @Override - public Predicate parse(final String query) throws GridQueryParserException { + public BiPredicate parse(final String query) throws GridQueryParserException { if (query.trim().isEmpty()) { - return resource -> true; + return (view, resource) -> true; } final List tokens = getTokens(query); final List nodes = getNodes(tokens); @@ -73,15 +73,15 @@ private List getNodes(final List tokens) throws GridQueryParserExce } } - private Predicate implicitAnd(final List nodes) throws GridQueryParserException { - final List> conditions = new ArrayList<>(); + private BiPredicate implicitAnd(final List nodes) throws GridQueryParserException { + final List> conditions = new ArrayList<>(); for (final Node node : nodes) { conditions.add(parseNode(node)); } return and(conditions); } - private Predicate parseNode(final Node node) throws GridQueryParserException { + private BiPredicate parseNode(final Node node) throws GridQueryParserException { return switch (node) { case LiteralNode literalNode -> parseLiteral(literalNode); case UnaryOpNode unaryOpNode -> parseUnaryOp(unaryOpNode); @@ -91,7 +91,7 @@ private Predicate parseNode(final Node node) throws GridQueryParse }; } - private Predicate parseBinOp(final BinOpNode node) throws GridQueryParserException { + private BiPredicate parseBinOp(final BinOpNode node) throws GridQueryParserException { final String operator = node.binOp().content(); if ("&&".equals(operator)) { return parseAndBinOpNode(node); @@ -102,24 +102,26 @@ private Predicate parseBinOp(final BinOpNode node) throws GridQuer } } - private Predicate parseAndBinOpNode(final BinOpNode node) throws GridQueryParserException { + private BiPredicate parseAndBinOpNode(final BinOpNode node) + throws GridQueryParserException { return and(Arrays.asList( parseNode(node.left()), parseNode(node.right()) )); } - private Predicate parseOrBinOpNode(final BinOpNode node) throws GridQueryParserException { + private BiPredicate parseOrBinOpNode(final BinOpNode node) + throws GridQueryParserException { return or(Arrays.asList( parseNode(node.left()), parseNode(node.right()) )); } - private Predicate parseUnaryOp(final UnaryOpNode node) throws GridQueryParserException { + private BiPredicate parseUnaryOp(final UnaryOpNode node) throws GridQueryParserException { final String operator = node.operator().content(); final Node content = node.node(); - final Predicate predicate; + final BiPredicate predicate; if ("!".equals(operator)) { predicate = not(parseNode(content)); @@ -146,8 +148,7 @@ private Predicate parseUnaryOp(final UnaryOpNode node) throws Grid return predicate; } - private static Predicate count(final Node node, - final BiPredicate predicate) + private static BiPredicate count(final Node node, final BiPredicate predicate) throws GridQueryParserException { if (!(node instanceof LiteralNode)) { throw new GridQueryParserException("Count filtering expects a literal", null); @@ -159,12 +160,14 @@ private static Predicate count(final Node node, final long wantedCount = Long.parseLong(((LiteralNode) node).token().content()); - return resource -> predicate.test(resource.getAmount(), wantedCount); + return (view, resource) -> predicate.test(resource.getAmount(view), wantedCount); } - private static Predicate attributeMatch(final Set keys, - final String query) { - return resource -> keys + private static BiPredicate attributeMatch( + final Set keys, + final String query + ) { + return (view, resource) -> keys .stream() .map(resource::getAttribute) .flatMap(Collection::stream) @@ -175,14 +178,14 @@ private static String normalize(final String value) { return value.trim().toLowerCase(Locale.ROOT); } - private static Predicate parseLiteral(final LiteralNode node) { - return resource -> normalize(resource.getName()).contains(normalize(node.token().content())); + private static BiPredicate parseLiteral(final LiteralNode node) { + return (view, resource) -> normalize(resource.getName()).contains(normalize(node.token().content())); } - private static Predicate and(final List> chain) { - return resource -> { - for (final Predicate predicate : chain) { - if (!predicate.test(resource)) { + private static BiPredicate and(final List> chain) { + return (view, resource) -> { + for (final BiPredicate predicate : chain) { + if (!predicate.test(view, resource)) { return false; } } @@ -190,10 +193,10 @@ private static Predicate and(final List> c }; } - private static Predicate or(final List> chain) { - return resource -> { - for (final Predicate predicate : chain) { - if (predicate.test(resource)) { + private static BiPredicate or(final List> chain) { + return (view, resource) -> { + for (final BiPredicate predicate : chain) { + if (predicate.test(view, resource)) { return true; } } @@ -201,7 +204,7 @@ private static Predicate or(final List> ch }; } - private static Predicate not(final Predicate predicate) { - return resource -> !predicate.test(resource); + private static BiPredicate not(final BiPredicate predicate) { + return (view, resource) -> !predicate.test(view, resource); } } diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResource.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResource.java index 2407f4987..20b613552 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResource.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResource.java @@ -14,7 +14,7 @@ public interface GridResource { Optional getTrackedResource(GridView view); - long getAmount(); + long getAmount(GridView view); String getName(); diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceFactory.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceFactory.java index 14bde3f3b..64289636b 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceFactory.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceFactory.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage.api.grid.view; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage.api.resource.ResourceKey; import java.util.Optional; @@ -13,12 +13,10 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.6") public interface GridResourceFactory { /** - * Transforms a {@link ResourceAmount} into a {@link GridResource}. - * It's important to keep the {@link ResourceAmount} instance around to - * get updated resource amounts from the {@link GridView} backing list. + * Transforms a {@link com.refinedmods.refinedstorage.api.resource.ResourceKey} into a {@link GridResource}. * - * @param resourceAmount the resource amount from the backing list + * @param resource the resource * @return the grid resource, if applicable */ - Optional apply(ResourceAmount resourceAmount); + Optional apply(ResourceKey resource); } diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridView.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridView.java index 9f25238cc..df1f422c9 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridView.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridView.java @@ -6,7 +6,7 @@ import java.util.List; import java.util.Optional; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import javax.annotation.Nullable; import org.apiguardian.api.API; @@ -38,7 +38,7 @@ public interface GridView { * @param predicate the filter * @return the previous filtering predicate */ - Predicate setFilterAndSort(Predicate predicate); + BiPredicate setFilterAndSort(BiPredicate predicate); /** * Preventing sorting means that the changes will still arrive at the backing list and view list, but, @@ -64,6 +64,12 @@ public interface GridView { */ Optional getTrackedResource(ResourceKey resource); + /** + * @param resource the resource + * @return the amount in the view, or zero if not present + */ + long getAmount(ResourceKey resource); + /** * Sorts the view list. * Applies sorting and filtering rules. diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImpl.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImpl.java index 9c0eed56f..6f84f5c7e 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImpl.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImpl.java @@ -1,10 +1,8 @@ package com.refinedmods.refinedstorage.api.grid.view; import com.refinedmods.refinedstorage.api.core.CoreValidations; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.ResourceList; -import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedResource; import java.util.ArrayList; @@ -14,7 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import javax.annotation.Nullable; import org.apiguardian.api.API; @@ -35,7 +33,7 @@ public class GridViewImpl implements GridView { private GridSortingType sortingType; private GridSortingDirection sortingDirection = GridSortingDirection.ASCENDING; - private Predicate filter = resource -> true; + private BiPredicate filter = (view, resource) -> true; @Nullable private Runnable listener; private boolean preventSorting; @@ -70,8 +68,8 @@ public void setSortingType(final GridSortingType sortingType) { } @Override - public Predicate setFilterAndSort(final Predicate predicate) { - final Predicate previousPredicate = filter; + public BiPredicate setFilterAndSort(final BiPredicate predicate) { + final BiPredicate previousPredicate = filter; this.filter = predicate; sort(); return previousPredicate; @@ -94,6 +92,11 @@ public Optional getTrackedResource(final ResourceKey resource) return Optional.ofNullable(trackedResources.get(resource)); } + @Override + public long getAmount(final ResourceKey resource) { + return backingList.get(resource); + } + @Override public void sort() { LOGGER.info("Sorting grid view"); @@ -101,11 +104,11 @@ public void sort() { viewListIndex.clear(); final List newViewList = new ArrayList<>(); - for (final ResourceAmount backingListItem : backingList.getAll()) { - resourceFactory.apply(backingListItem).ifPresent(gridResource -> { - if (filter.test(gridResource)) { + for (final ResourceKey resource : backingList.getAll()) { + resourceFactory.apply(resource).ifPresent(gridResource -> { + if (filter.test(this, gridResource)) { newViewList.add(gridResource); - viewListIndex.put(backingListItem.getResource(), gridResource); + viewListIndex.put(resource, gridResource); } }); } @@ -158,7 +161,7 @@ private void reinsertZeroedResourceIntoViewList(final ResourceKey resource, final ResourceList.OperationResult operationResult, final GridResource oldGridResource) { LOGGER.debug("{} was zeroed, unzeroing", resource); - final GridResource newResource = resourceFactory.apply(operationResult.resourceAmount()).orElseThrow(); + final GridResource newResource = resourceFactory.apply(operationResult.resource()).orElseThrow(); viewListIndex.put(resource, newResource); final int index = CoreValidations.validateNotNegative( viewList.indexOf(oldGridResource), @@ -198,8 +201,8 @@ private void updateExistingResourceInViewList(final ResourceKey resource, private void handleChangeForNewResource(final ResourceKey resource, final ResourceList.OperationResult operationResult) { - final GridResource gridResource = resourceFactory.apply(operationResult.resourceAmount()).orElseThrow(); - if (filter.test(gridResource)) { + final GridResource gridResource = resourceFactory.apply(operationResult.resource()).orElseThrow(); + if (filter.test(this, gridResource)) { LOGGER.debug("Filter allowed, actually adding {}", resource); viewListIndex.put(resource, gridResource); addIntoView(gridResource); @@ -249,9 +252,7 @@ public List getViewList() { @Override public ResourceList copyBackingList() { - final ResourceList copy = ResourceListImpl.create(); - backingList.getAll().forEach(copy::add); - return copy; + return backingList.copy(); } @Override diff --git a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/watcher/GridWatcherRegistration.java b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/watcher/GridWatcherRegistration.java index 5dae822b6..03ce20edb 100644 --- a/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/watcher/GridWatcherRegistration.java +++ b/refinedstorage-grid-api/src/main/java/com/refinedmods/refinedstorage/api/grid/watcher/GridWatcherRegistration.java @@ -19,20 +19,17 @@ class GridWatcherRegistration { void attach(final RootStorage rootStorage, final boolean replay) { this.listener = change -> watcher.onChanged( - change.resourceAmount().getResource(), + change.resource(), change.change(), - rootStorage.findTrackedResourceByActorType( - change.resourceAmount().getResource(), - actorType - ).orElse(null) + rootStorage.findTrackedResourceByActorType(change.resource(), actorType).orElse(null) ); rootStorage.addListener(listener); if (replay) { rootStorage.getAll().forEach(resourceAmount -> watcher.onChanged( - resourceAmount.getResource(), - resourceAmount.getAmount(), + resourceAmount.resource(), + resourceAmount.amount(), rootStorage.findTrackedResourceByActorType( - resourceAmount.getResource(), + resourceAmount.resource(), actorType ).orElse(null) )); diff --git a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImplTest.java b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImplTest.java index 21879ac19..8d69ad560 100644 --- a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImplTest.java +++ b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/query/GridQueryParserImplTest.java @@ -3,15 +3,19 @@ import com.refinedmods.refinedstorage.api.grid.view.FakeGridResourceAttributeKeys; import com.refinedmods.refinedstorage.api.grid.view.GridResource; import com.refinedmods.refinedstorage.api.grid.view.GridResourceAttributeKey; +import com.refinedmods.refinedstorage.api.grid.view.GridResourceImpl; import com.refinedmods.refinedstorage.api.grid.view.GridView; +import com.refinedmods.refinedstorage.api.grid.view.GridViewImpl; +import com.refinedmods.refinedstorage.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage.query.lexer.LexerTokenMappings; import com.refinedmods.refinedstorage.query.parser.ParserOperatorMappings; +import java.util.Comparator; +import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.function.Predicate; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -28,49 +32,57 @@ class GridQueryParserImplTest { FakeGridResourceAttributeKeys.UNARY_OPERATOR_TO_ATTRIBUTE_KEY_MAPPING ); + private final GridView view = new GridViewImpl( + resource -> Optional.of(new GridResourceImpl(resource)), + ResourceListImpl.create(), + new HashMap<>(), + v -> Comparator.comparing(GridResource::getName), + v -> Comparator.comparingLong(resource -> resource.getAmount(v)) + ); + @ParameterizedTest @ValueSource(strings = {"", " "}) void testEmptyQuery(final String query) throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(query); + final var predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isTrue(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isTrue(); } @ParameterizedTest @ValueSource(strings = {"dirt", "Dirt", "DiRt", "Di", "irt"}) void testNameQuery(final String query) throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(query); + final var predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isFalse(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isFalse(); } @ParameterizedTest @ValueSource(strings = {"@refined", "@\"Refined Storage\"", "@ReFiNe", "@Storage", "@rs", "@RS"}) void testModQuery(final String query) throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(query); + final var predicate = queryParser.parse(query); // Assert - assertThat(predicate.test(new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isFalse(); + assertThat(predicate.test(view, new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isFalse(); } @ParameterizedTest @ValueSource(strings = {"$underwater", "$UnDerWate", "$water", "$unrelated", "$UNREL", "$laTed"}) void testTagQuery(final String query) throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(query); + final var predicate = queryParser.parse(query); // Assert - assertThat(predicate.test( + assertThat(predicate.test(view, new R("Sponge", 1, "mc", "Minecraft", Set.of("underwater", "unrelated")))).isTrue(); - assertThat(predicate.test(new R("Dirt", 1, "mc", "Minecraft", Set.of("transparent")))).isFalse(); + assertThat(predicate.test(view, new R("Dirt", 1, "mc", "Minecraft", Set.of("transparent")))).isFalse(); } @Test @@ -86,154 +98,154 @@ void testAttributeQueryWithInvalidNode() { @Test void testImplicitAndQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("DirT di RT"); + final var predicate = queryParser.parse("DirT di RT"); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isFalse(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isFalse(); } @Test void testImplicitAndQueryInParenthesis() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("(DirT di RT) || (sto stone)"); + final var predicate = queryParser.parse("(DirT di RT) || (sto stone)"); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isFalse(); - assertThat(predicate.test(new R("Stone"))).isTrue(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isFalse(); + assertThat(predicate.test(view, new R("Stone"))).isTrue(); } @Test void testImplicitAndQueryWithUnaryOperator() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("@minecraft >5"); + final var predicate = queryParser.parse("@minecraft >5"); // Assert - assertThat(predicate.test(new R("Dirt", 6, "minecraft", "Minecraft", Set.of()))).isTrue(); - assertThat(predicate.test(new R("Glass", 5, "minecraft", "Minecraft", Set.of()))).isFalse(); - assertThat(predicate.test(new R("Sponge", 5, "rs", "Refined Storage", Set.of()))).isFalse(); - assertThat(predicate.test(new R("Cobblestone", 6, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(view, new R("Dirt", 6, "minecraft", "Minecraft", Set.of()))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 5, "minecraft", "Minecraft", Set.of()))).isFalse(); + assertThat(predicate.test(view, new R("Sponge", 5, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(view, new R("Cobblestone", 6, "rs", "Refined Storage", Set.of()))).isFalse(); } @Test void testAndQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("DirT && di && RT"); + final var predicate = queryParser.parse("DirT && di && RT"); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isFalse(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isFalse(); } @Test void testOrQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("dir || glass || StoNe"); + final var predicate = queryParser.parse("dir || glass || StoNe"); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isTrue(); - assertThat(predicate.test(new R("Stone"))).isTrue(); - assertThat(predicate.test(new R("Cobblestone"))).isTrue(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isTrue(); + assertThat(predicate.test(view, new R("Stone"))).isTrue(); + assertThat(predicate.test(view, new R("Cobblestone"))).isTrue(); - assertThat(predicate.test(new R("Sponge"))).isFalse(); - assertThat(predicate.test(new R("Furnace"))).isFalse(); + assertThat(predicate.test(view, new R("Sponge"))).isFalse(); + assertThat(predicate.test(view, new R("Furnace"))).isFalse(); } @Test void testSimpleNotQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("!stone"); + final var predicate = queryParser.parse("!stone"); // Assert - assertThat(predicate.test(new R("Dirt"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isTrue(); + assertThat(predicate.test(view, new R("Dirt"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isTrue(); - assertThat(predicate.test(new R("Stone"))).isFalse(); - assertThat(predicate.test(new R("Cobblestone"))).isFalse(); + assertThat(predicate.test(view, new R("Stone"))).isFalse(); + assertThat(predicate.test(view, new R("Cobblestone"))).isFalse(); } @Test void testNotQueryWithMultipleOrParts() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("!(stone || dirt)"); + final var predicate = queryParser.parse("!(stone || dirt)"); // Assert - assertThat(predicate.test(new R("Sponge"))).isTrue(); - assertThat(predicate.test(new R("Glass"))).isTrue(); + assertThat(predicate.test(view, new R("Sponge"))).isTrue(); + assertThat(predicate.test(view, new R("Glass"))).isTrue(); - assertThat(predicate.test(new R("Stone"))).isFalse(); - assertThat(predicate.test(new R("Dirt"))).isFalse(); + assertThat(predicate.test(view, new R("Stone"))).isFalse(); + assertThat(predicate.test(view, new R("Dirt"))).isFalse(); } @Test void testComplexModQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse( + final var predicate = queryParser.parse( "((spo || buck) && @refined) || (glass && @mine)" ); // Assert - assertThat(predicate.test(new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new R("Bucket", 1, "rs", "Refined Storage", Set.of()))).isTrue(); - assertThat(predicate.test(new R("Saddle", 1, "rs", "Refined Storage", Set.of()))).isFalse(); + assertThat(predicate.test(view, new R("Sponge", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(view, new R("Bucket", 1, "rs", "Refined Storage", Set.of()))).isTrue(); + assertThat(predicate.test(view, new R("Saddle", 1, "rs", "Refined Storage", Set.of()))).isFalse(); - assertThat(predicate.test(new R("Glass", 1, "mc", "Minecraft", Set.of()))).isTrue(); - assertThat(predicate.test(new R("Furnace", 1, "mc", "Minecraft", Set.of()))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 1, "mc", "Minecraft", Set.of()))).isTrue(); + assertThat(predicate.test(view, new R("Furnace", 1, "mc", "Minecraft", Set.of()))).isFalse(); } @Test void testLessThanUnaryCountQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("<5"); + final var predicate = queryParser.parse("<5"); // Assert - assertThat(predicate.test(new R("Glass", 5))).isFalse(); - assertThat(predicate.test(new R("Glass", 4))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 5))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 4))).isTrue(); } @Test void testLessThanEqualsUnaryCountQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("<=5"); + final var predicate = queryParser.parse("<=5"); // Assert - assertThat(predicate.test(new R("Glass", 6))).isFalse(); - assertThat(predicate.test(new R("Glass", 5))).isTrue(); - assertThat(predicate.test(new R("Glass", 4))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 6))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 5))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 4))).isTrue(); } @Test void testGreaterThanUnaryCountQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(">5"); + final var predicate = queryParser.parse(">5"); // Assert - assertThat(predicate.test(new R("Glass", 5))).isFalse(); - assertThat(predicate.test(new R("Glass", 6))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 5))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 6))).isTrue(); } @Test void testGreaterThanEqualsUnaryCountQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse(">=5"); + final var predicate = queryParser.parse(">=5"); // Assert - assertThat(predicate.test(new R("Glass", 4))).isFalse(); - assertThat(predicate.test(new R("Glass", 5))).isTrue(); - assertThat(predicate.test(new R("Glass", 6))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 4))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 5))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 6))).isTrue(); } @Test void testEqualsUnaryCountQuery() throws GridQueryParserException { // Act - final Predicate predicate = queryParser.parse("=5"); + final var predicate = queryParser.parse("=5"); // Assert - assertThat(predicate.test(new R("Glass", 4))).isFalse(); - assertThat(predicate.test(new R("Glass", 5))).isTrue(); - assertThat(predicate.test(new R("Glass", 6))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 4))).isFalse(); + assertThat(predicate.test(view, new R("Glass", 5))).isTrue(); + assertThat(predicate.test(view, new R("Glass", 6))).isFalse(); } @ParameterizedTest @@ -295,7 +307,7 @@ public Optional getTrackedResource(final GridView view) { } @Override - public long getAmount() { + public long getAmount(final GridView view) { return amount; } diff --git a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceImpl.java b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceImpl.java index 28ef989e6..ae11dd59e 100644 --- a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceImpl.java +++ b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridResourceImpl.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage.api.grid.view; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedResource; @@ -9,20 +8,16 @@ import java.util.Optional; import java.util.Set; -class GridResourceImpl implements GridResource { - private final ResourceAmount resourceAmountRef; +public class GridResourceImpl implements GridResource { + private final ResourceKey resource; private final Map> attributes; private boolean zeroed; - GridResourceImpl(final ResourceKey resource, final long amount) { - this(new ResourceAmount(resource, amount)); - } - - GridResourceImpl(final ResourceAmount resourceAmountRef) { - this.resourceAmountRef = resourceAmountRef; + public GridResourceImpl(final ResourceKey resource) { + this.resource = resource; this.attributes = Map.of( - FakeGridResourceAttributeKeys.MOD_ID, Set.of(resourceAmountRef.getResource().toString()), - FakeGridResourceAttributeKeys.MOD_NAME, Set.of(resourceAmountRef.getResource().toString()) + FakeGridResourceAttributeKeys.MOD_ID, Set.of(resource.toString()), + FakeGridResourceAttributeKeys.MOD_NAME, Set.of(resource.toString()) ); } @@ -33,17 +28,17 @@ public GridResourceImpl zeroed() { @Override public Optional getTrackedResource(final GridView view) { - return view.getTrackedResource(resourceAmountRef.getResource()); + return view.getTrackedResource(resource); } @Override - public long getAmount() { - return resourceAmountRef.getAmount(); + public long getAmount(final GridView view) { + return view.getAmount(resource); } @Override public String getName() { - return resourceAmountRef.getResource().toString(); + return resource.toString(); } @Override @@ -63,6 +58,6 @@ public void setZeroed(final boolean zeroed) { @Override public String toString() { - return resourceAmountRef.getResource().toString(); + return resource.toString(); } } diff --git a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImplTest.java b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImplTest.java index 2837dd328..7b5efb742 100644 --- a/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImplTest.java +++ b/refinedstorage-grid-api/src/test/java/com/refinedmods/refinedstorage/api/grid/view/GridViewImplTest.java @@ -7,7 +7,7 @@ import java.util.Comparator; import java.util.Optional; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,14 +28,14 @@ class GridViewImplTest { @BeforeEach void setUp() { - viewBuilder = getViewBuilder(resourceAmount -> Optional.of(new GridResourceImpl(resourceAmount))); + viewBuilder = getViewBuilder(resource -> Optional.of(new GridResourceImpl(resource))); } private static GridViewBuilderImpl getViewBuilder(final GridResourceFactory resourceFactory) { return new GridViewBuilderImpl( resourceFactory, view -> Comparator.comparing(GridResource::getName), - view -> Comparator.comparing(GridResource::getAmount) + view -> Comparator.comparingLong(resource -> resource.getAmount(view)) ); } @@ -57,8 +57,8 @@ void shouldAddResourcesWithSameNameButDifferentIdentity() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceWithMetadata(new ResourceAmount(new ResourceWithMetadata(A, 1), 1)), - new GridResourceWithMetadata(new ResourceAmount(new ResourceWithMetadata(A, 2), 1)) + new GridResourceWithMetadata(new ResourceWithMetadata(A, 1)), + new GridResourceWithMetadata(new ResourceWithMetadata(A, 2)) ); } @@ -75,9 +75,9 @@ void shouldPreserveOrderWhenSortingAndTwoResourcesHaveTheSameQuantity() { view.onChange(C, 2, null); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(B, 15), - new GridResourceImpl(A, 15), - new GridResourceImpl(C, 2) + new GridResourceImpl(B), + new GridResourceImpl(A), + new GridResourceImpl(C) ); view.onChange(A, -15, null); @@ -87,9 +87,9 @@ void shouldPreserveOrderWhenSortingAndTwoResourcesHaveTheSameQuantity() { view.onChange(B, 15, null); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(B, 15), - new GridResourceImpl(A, 15), - new GridResourceImpl(C, 2) + new GridResourceImpl(B), + new GridResourceImpl(A), + new GridResourceImpl(C) ); } @@ -115,11 +115,15 @@ void shouldLoadResourcesAndRetrieveTrackedResourcesProperly() { assertThat(a).get().usingRecursiveComparison().isEqualTo(new TrackedResource("RaoulA", 2)); assertThat(b).isEmpty(); assertThat(d).isEmpty(); - assertThat(backingList.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(backingList.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(A, 2), new ResourceAmount(B, 2), new ResourceAmount(D, 1) ); + assertThat(view.getAmount(A)).isEqualTo(2); + assertThat(view.getAmount(B)).isEqualTo(2); + assertThat(view.getAmount(C)).isZero(); + assertThat(view.getAmount(D)).isEqualTo(1); } @Test @@ -140,11 +144,11 @@ void shouldInsertNewResource() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 12), - new GridResourceImpl(B, 15) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), @@ -152,6 +156,9 @@ void shouldInsertNewResource() { new ResourceAmount(B, 15) ); verify(listener, times(1)).run(); + assertThat(view.getAmount(A)).isEqualTo(12); + assertThat(view.getAmount(B)).isEqualTo(15); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -162,19 +169,21 @@ void shouldSetFilterAndSort() { .withResource(B, 10, null) .build(); - final Predicate filterA = resource -> resource.getName().equals(A.name()); - final Predicate filterB = resource -> resource.getName().equals(B.name()); + final BiPredicate filterA = (v, resource) -> resource.getName().equals(A.name()); + final BiPredicate filterB = (v, resource) -> resource.getName().equals(B.name()); // Act - final Predicate previousFilter1 = view.setFilterAndSort(filterA); - final Predicate previousFilter2 = view.setFilterAndSort(filterB); + final BiPredicate previousFilter1 = view.setFilterAndSort(filterA); + final BiPredicate previousFilter2 = view.setFilterAndSort(filterB); // Assert assertThat(previousFilter1).isNotNull(); assertThat(previousFilter2).isEqualTo(filterA); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(B, 10) + new GridResourceImpl(B) ); + assertThat(view.getAmount(A)).isEqualTo(10); + assertThat(view.getAmount(B)).isEqualTo(10); } @Test @@ -185,7 +194,7 @@ void shouldNotInsertNewResourceWhenFilteringProhibitsIt() { .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals(A.name())); + view.setFilterAndSort((v, resource) -> !resource.getName().equals(A.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); @@ -195,10 +204,13 @@ void shouldNotInsertNewResourceWhenFilteringProhibitsIt() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(B, 15) + new GridResourceImpl(D), + new GridResourceImpl(B) ); verify(listener, never()).run(); + assertThat(view.getAmount(A)).isEqualTo(12); + assertThat(view.getAmount(B)).isEqualTo(15); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -240,11 +252,11 @@ void shouldUpdateExistingResource() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(B, 11), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(B), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), @@ -252,6 +264,9 @@ void shouldUpdateExistingResource() { new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); + assertThat(view.getAmount(A)).isEqualTo(15); + assertThat(view.getAmount(B)).isEqualTo(11); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -263,7 +278,7 @@ void shouldNotUpdateExistingResourceWhenFilteringProhibitsIt() { .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals(B.name())); + view.setFilterAndSort((v, resource) -> !resource.getName().equals(B.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); @@ -273,10 +288,10 @@ void shouldNotUpdateExistingResourceWhenFilteringProhibitsIt() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(B, 11), @@ -284,6 +299,9 @@ void shouldNotUpdateExistingResourceWhenFilteringProhibitsIt() { new ResourceAmount(A, 15) ); verify(listener, never()).run(); + assertThat(view.getAmount(A)).isEqualTo(15); + assertThat(view.getAmount(B)).isEqualTo(11); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -302,9 +320,9 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(B, 6), - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(B), + new GridResourceImpl(D), + new GridResourceImpl(A) ); final boolean changed = view.setPreventSorting(true); @@ -316,11 +334,11 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(B, 11), - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(B), + new GridResourceImpl(D), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(B, 11), @@ -333,11 +351,11 @@ void shouldNotReorderExistingResourceWhenPreventingSorting() { view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(B, 11), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(B), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(B, 11), @@ -389,11 +407,11 @@ void shouldUpdateExistingResourceWhenPerformingPartialRemoval() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(B, 13), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(B), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), @@ -401,6 +419,9 @@ void shouldUpdateExistingResourceWhenPerformingPartialRemoval() { new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); + assertThat(view.getAmount(A)).isEqualTo(15); + assertThat(view.getAmount(B)).isEqualTo(13); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -412,7 +433,7 @@ void shouldNotUpdateExistingResourceWhenPerformingPartialRemovalAndFilteringProh .withResource(D, 10, null) .build(); - view.setFilterAndSort(resource -> !resource.getName().equals(B.name())); + view.setFilterAndSort((v, resource) -> !resource.getName().equals(B.name())); final Runnable listener = mock(Runnable.class); view.setListener(listener); @@ -422,10 +443,13 @@ void shouldNotUpdateExistingResourceWhenPerformingPartialRemovalAndFilteringProh // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(A) ); verify(listener, never()).run(); + assertThat(view.getAmount(A)).isEqualTo(15); + assertThat(view.getAmount(B)).isEqualTo(13); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -444,9 +468,9 @@ void shouldNotReorderExistingResourceWhenPerformingPartialRemovalAndPreventingSo // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 20) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); view.setPreventSorting(true); @@ -455,18 +479,18 @@ void shouldNotReorderExistingResourceWhenPerformingPartialRemovalAndPreventingSo verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 13) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); view.setPreventSorting(false); view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(B, 13), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(B), + new GridResourceImpl(A) ); } @@ -489,16 +513,19 @@ void shouldRemoveExistingResourceCompletely() { // Assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), new ResourceAmount(A, 15) ); verify(listener, times(1)).run(); + assertThat(view.getAmount(A)).isEqualTo(15); + assertThat(view.getAmount(B)).isZero(); + assertThat(view.getAmount(D)).isEqualTo(10); } @Test @@ -517,9 +544,9 @@ void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting( // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 20) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); view.setPreventSorting(true); @@ -527,11 +554,11 @@ void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting( verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 20).zeroed() + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B).zeroed() ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), @@ -542,10 +569,10 @@ void shouldNotReorderWhenRemovingExistingResourceCompletelyAndPreventingSorting( view.sort(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15) + new GridResourceImpl(D), + new GridResourceImpl(A) ); - assertThat(view.copyBackingList().getAll()) + assertThat(view.copyBackingList().copyState()) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder( new ResourceAmount(D, 10), @@ -569,9 +596,9 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource // Act & assert assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 20) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); // Delete the item @@ -580,9 +607,9 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 20).zeroed() + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B).zeroed() ); // Re-insert the item @@ -590,9 +617,9 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 5) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); // Re-insert the item again @@ -600,9 +627,9 @@ void shouldReuseExistingResourceWhenPreventingSortingAndRemovingExistingResource verify(listener, never()).run(); assertThat(view.getViewList()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new GridResourceImpl(D, 10), - new GridResourceImpl(A, 15), - new GridResourceImpl(B, 8) + new GridResourceImpl(D), + new GridResourceImpl(A), + new GridResourceImpl(B) ); } @@ -620,18 +647,21 @@ void shouldClear() { // Assert assertThat(view.getViewList()).isEmpty(); - assertThat(view.copyBackingList().getAll()).isEmpty(); + assertThat(view.copyBackingList().copyState()).isEmpty(); assertThat(view.getTrackedResource(A)).isEmpty(); assertThat(view.getTrackedResource(B)).isEmpty(); assertThat(view.getTrackedResource(D)).isEmpty(); + assertThat(view.getAmount(A)).isZero(); + assertThat(view.getAmount(B)).isZero(); + assertThat(view.getAmount(D)).isZero(); } private record ResourceWithMetadata(ResourceKey resource, int metadata) implements ResourceKey { } private static class GridResourceWithMetadata extends GridResourceImpl { - GridResourceWithMetadata(final ResourceAmount resourceAmount) { - super(resourceAmount); + GridResourceWithMetadata(final ResourceKey resource) { + super(resource); } } } diff --git a/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/PlatformImpl.java b/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/PlatformImpl.java index 8c8cf08ab..1e91d7032 100644 --- a/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/PlatformImpl.java +++ b/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/PlatformImpl.java @@ -155,11 +155,11 @@ public Optional drainContainer(final ItemStack container) @Override public Optional fillContainer(final ItemStack container, final ResourceAmount resourceAmount) { - if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + if (!(resourceAmount.resource() instanceof FluidResource fluidResource)) { return Optional.empty(); } return FluidUtil.getFluidHandler(container).map(handler -> { - final FluidStack fluidStack = toFluidStack(fluidResource, resourceAmount.getAmount()); + final FluidStack fluidStack = toFluidStack(fluidResource, resourceAmount.amount()); final long filled = handler.fill(fluidStack, IFluidHandler.FluidAction.EXECUTE); return new FluidOperationResult(handler.getContainer(), fluidResource, filled); }); diff --git a/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/support/resource/ResourceContainerFluidHandlerAdapter.java b/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/support/resource/ResourceContainerFluidHandlerAdapter.java index d14f2cbd7..f05f44227 100644 --- a/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/support/resource/ResourceContainerFluidHandlerAdapter.java +++ b/refinedstorage-neoforge/src/main/java/com/refinedmods/refinedstorage/neoforge/support/resource/ResourceContainerFluidHandlerAdapter.java @@ -30,10 +30,10 @@ public int getTanks() { @Override public FluidStack getFluidInTank(final int tank) { final ResourceAmount resourceAmount = container.get(tank); - if (resourceAmount == null || !(resourceAmount.getResource() instanceof FluidResource fluidResource)) { + if (resourceAmount == null || !(resourceAmount.resource() instanceof FluidResource fluidResource)) { return FluidStack.EMPTY; } - return toFluidStack(fluidResource, resourceAmount.getAmount()); + return toFluidStack(fluidResource, resourceAmount.amount()); } @Override diff --git a/refinedstorage-neoforge/src/test/java/com/refinedmods/refinedstorage/common/GameTestUtil.java b/refinedstorage-neoforge/src/test/java/com/refinedmods/refinedstorage/common/GameTestUtil.java index b78757abb..2c68b9160 100644 --- a/refinedstorage-neoforge/src/test/java/com/refinedmods/refinedstorage/common/GameTestUtil.java +++ b/refinedstorage-neoforge/src/test/java/com/refinedmods/refinedstorage/common/GameTestUtil.java @@ -174,23 +174,23 @@ private static Runnable resourceContainerContainsExactly(final GameTestHelper he final boolean contains = IntStream.range(0, container.size()) .mapToObj(container::get) .anyMatch(resource -> resource != null - && resource.getResource().equals(expectedStack.getResource()) - && resource.getAmount() == expectedStack.getAmount()); + && resource.resource().equals(expectedStack.resource()) + && resource.amount() == expectedStack.amount()); helper.assertTrue(contains, "Expected resource is missing from " + displayName.getString() + ": " - + expectedStack + " with count: " + expectedStack.getAmount()); + + expectedStack + " with count: " + expectedStack.amount()); } for (int i = 0; i < container.size(); i++) { final ResourceAmount resource = container.get(i); if (resource != null) { final boolean wasExpected = Arrays.stream(expected).anyMatch( - expectedResource -> expectedResource.getResource().equals(resource.getResource()) - && expectedResource.getAmount() == resource.getAmount() + expectedResource -> expectedResource.resource().equals(resource.resource()) + && expectedResource.amount() == resource.amount() ); helper.assertTrue(wasExpected, "Unexpected resource found in " + displayName.getString() + ": " - + resource.getResource() + " with count: " + resource.getAmount()); + + resource.resource() + " with count: " + resource.amount()); } } }; @@ -206,18 +206,18 @@ public static Runnable containerContainsExactly(final GameTestHelper helper, for (final ResourceAmount expectedStack : expected) { final boolean contains = IntStream.range(0, containerBlockEntity.getContainerSize()) .mapToObj(containerBlockEntity::getItem) - .anyMatch(inContainer -> asResource(inContainer).equals(expectedStack.getResource()) - && inContainer.getCount() == expectedStack.getAmount()); + .anyMatch(inContainer -> asResource(inContainer).equals(expectedStack.resource()) + && inContainer.getCount() == expectedStack.amount()); helper.assertTrue(contains, "Expected resource is missing from container: " - + expectedStack + " with count: " + expectedStack.getAmount()); + + expectedStack + " with count: " + expectedStack.amount()); } for (int i = 0; i < containerBlockEntity.getContainerSize(); i++) { final ItemStack inContainer = containerBlockEntity.getItem(i); if (!inContainer.isEmpty()) { final boolean wasExpected = Arrays.stream(expected).anyMatch( - expectedStack -> expectedStack.getResource().equals(asResource(inContainer)) - && expectedStack.getAmount() == inContainer.getCount() + expectedStack -> expectedStack.resource().equals(asResource(inContainer)) + && expectedStack.amount() == inContainer.getCount() ); helper.assertTrue(wasExpected, "Unexpected resource found in container: " + inContainer.getDescriptionId() + " with count: " + inContainer.getCount()); @@ -234,14 +234,14 @@ public static Runnable storageContainsExactly(final GameTestHelper helper, for (final ResourceAmount expectedResource : expected) { final boolean contains = storage.getAll() .stream() - .anyMatch(inStorage -> inStorage.getResource().equals(expectedResource.getResource()) - && inStorage.getAmount() == expectedResource.getAmount()); + .anyMatch(inStorage -> inStorage.resource().equals(expectedResource.resource()) + && inStorage.amount() == expectedResource.amount()); helper.assertTrue(contains, "Expected resource is missing from storage: " + expectedResource); } for (final ResourceAmount inStorage : storage.getAll()) { final boolean wasExpected = Arrays.stream(expected).anyMatch( - expectedResource -> expectedResource.getResource().equals(inStorage.getResource()) - && expectedResource.getAmount() == inStorage.getAmount() + expectedResource -> expectedResource.resource().equals(inStorage.resource()) + && expectedResource.amount() == inStorage.amount() ); helper.assertTrue(wasExpected, "Unexpected resource found in storage: " + inStorage); } diff --git a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/detector/DetectorAmountStrategyImpl.java b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/detector/DetectorAmountStrategyImpl.java index d07e877fe..9bda0b721 100644 --- a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/detector/DetectorAmountStrategyImpl.java +++ b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/detector/DetectorAmountStrategyImpl.java @@ -1,15 +1,11 @@ package com.refinedmods.refinedstorage.api.network.impl.node.detector; import com.refinedmods.refinedstorage.api.network.Network; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; public class DetectorAmountStrategyImpl extends AbstractDetectorAmountStrategy { @Override public long getAmount(final Network network, final ResourceKey configuredResource) { - return getRootStorage(network) - .get(configuredResource) - .map(ResourceAmount::getAmount) - .orElse(0L); + return getRootStorage(network).get(configuredResource); } } diff --git a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/relay/RelayOutputStorage.java b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/relay/RelayOutputStorage.java index 96f1756f5..90674582f 100644 --- a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/relay/RelayOutputStorage.java +++ b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/relay/RelayOutputStorage.java @@ -65,16 +65,16 @@ private void reset(final Runnable action) { void setDelegate(@Nullable final StorageNetworkComponent delegate) { if (this.delegate != null) { parentComposites.forEach(parent -> getAll().forEach(resourceAmount -> parent.removeFromCache( - resourceAmount.getResource(), - resourceAmount.getAmount() + resourceAmount.resource(), + resourceAmount.amount() ))); this.delegate.removeListener(this); } this.delegate = delegate; if (delegate != null) { parentComposites.forEach(parent -> getAll().forEach(resourceAmount -> parent.addToCache( - resourceAmount.getResource(), - resourceAmount.getAmount() + resourceAmount.resource(), + resourceAmount.amount() ))); delegate.addListener(this); } @@ -142,7 +142,7 @@ public Collection getAll() { } return delegate.getAll() .stream() - .filter(resourceAmount -> filter.isAllowed(resourceAmount.getResource())) + .filter(resourceAmount -> filter.isAllowed(resourceAmount.resource())) .toList(); } @@ -153,8 +153,8 @@ public long getStored() { } return delegate.getAll() .stream() - .filter(resourceAmount -> filter.isAllowed(resourceAmount.getResource())) - .mapToLong(ResourceAmount::getAmount) + .filter(resourceAmount -> filter.isAllowed(resourceAmount.resource())) + .mapToLong(ResourceAmount::amount) .sum(); } @@ -163,7 +163,7 @@ public void onChanged(final ResourceList.OperationResult change) { if (delegate != null && delegate.contains(delegate)) { return; } - final ResourceKey resource = change.resourceAmount().getResource(); + final ResourceKey resource = change.resource(); if (!filter.isAllowed(resource)) { return; } diff --git a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/storagetransfer/StorageTransferNetworkNode.java b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/storagetransfer/StorageTransferNetworkNode.java index a6d0bcbf3..7216fd858 100644 --- a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/storagetransfer/StorageTransferNetworkNode.java +++ b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/node/storagetransfer/StorageTransferNetworkNode.java @@ -121,11 +121,11 @@ private boolean transfer(final Storage source, final Storage destination, final long remainder = transferQuota; final Collection sourceContents = new LinkedHashSet<>(source.getAll()); for (final ResourceAmount resourceAmount : sourceContents) { - final ResourceKey resource = resourceAmount.getResource(); + final ResourceKey resource = resourceAmount.resource(); if (!filter.isAllowed(resource)) { continue; } - final long amount = Math.min(remainder, resourceAmount.getAmount()); + final long amount = Math.min(remainder, resourceAmount.amount()); final long transferred = TransferHelper.transfer(resource, amount, actor, source, destination, source); remainder -= transferred; if (remainder == 0) { @@ -136,7 +136,7 @@ private boolean transfer(final Storage source, final Storage destination, final } private boolean hasNoExtractableResources(final Storage source) { - return source.getAll().stream().noneMatch(resourceAmount -> filter.isAllowed(resourceAmount.getResource())); + return source.getAll().stream().noneMatch(resourceAmount -> filter.isAllowed(resourceAmount.resource())); } private boolean storageIsFull(final Storage storage) { diff --git a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/storage/StorageNetworkComponentImpl.java b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/storage/StorageNetworkComponentImpl.java index d0535d17c..1d4babcbb 100644 --- a/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/storage/StorageNetworkComponentImpl.java +++ b/refinedstorage-network/src/main/java/com/refinedmods/refinedstorage/api/network/impl/storage/StorageNetworkComponentImpl.java @@ -43,7 +43,7 @@ public void onContainerRemoved(final NetworkNodeContainer container) { public List getResources(final Class actorType) { return getAll().stream().map(resourceAmount -> new TrackedResourceAmount( resourceAmount, - findTrackedResourceByActorType(resourceAmount.getResource(), actorType).orElse(null) + findTrackedResourceByActorType(resourceAmount.resource(), actorType).orElse(null) )).toList(); } diff --git a/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java b/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java index a04702497..89489c30e 100644 --- a/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java +++ b/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/externalstorage/ExternalStorageNetworkNodeTest.java @@ -592,7 +592,7 @@ private AtomicBoolean trackWhetherResourceHasChangedAndTrackedResourceIsAvailabl ) { final AtomicBoolean found = new AtomicBoolean(); networkStorage.addListener(change -> { - if (change.resourceAmount().getResource().equals(A)) { + if (change.resource().equals(A)) { found.set(networkStorage.findTrackedResourceByActorType(A, FakeActor.class).isPresent()); } }); diff --git a/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/iface/InterfaceExportStateImpl.java b/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/iface/InterfaceExportStateImpl.java index 3cdcf0350..115fd22b2 100644 --- a/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/iface/InterfaceExportStateImpl.java +++ b/refinedstorage-network/src/test/java/com/refinedmods/refinedstorage/api/network/impl/node/iface/InterfaceExportStateImpl.java @@ -52,10 +52,10 @@ private Collection expandExportCandidates(final RootStorage rootSto final List candidates = new ArrayList<>(); candidates.add(A); // Simulate the behavior from FuzzyRootStorage - if (rootStorage.get(A_ALTERNATIVE).isPresent()) { + if (rootStorage.contains(A_ALTERNATIVE)) { candidates.add(A_ALTERNATIVE); } - if (rootStorage.get(A_ALTERNATIVE2).isPresent()) { + if (rootStorage.contains(A_ALTERNATIVE2)) { candidates.add(A_ALTERNATIVE2); } return candidates; @@ -83,7 +83,7 @@ public ResourceKey getRequestedResource(final int slotIndex) { if (resourceAmount == null) { return null; } - return resourceAmount.getResource(); + return resourceAmount.resource(); } @Override @@ -93,7 +93,7 @@ public long getRequestedAmount(final int slotIndex) { if (resourceAmount == null) { return 0L; } - return resourceAmount.getAmount(); + return resourceAmount.amount(); } @Nullable @@ -104,7 +104,7 @@ public ResourceKey getExportedResource(final int slotIndex) { if (resourceAmount == null) { return null; } - return resourceAmount.getResource(); + return resourceAmount.resource(); } @Override @@ -114,7 +114,7 @@ public long getExportedAmount(final int slotIndex) { if (resourceAmount == null) { return 0L; } - return resourceAmount.getAmount(); + return resourceAmount.amount(); } @Override @@ -131,10 +131,13 @@ public void setCurrentlyExported(final int index, final ResourceKey resource, fi public void shrinkExportedAmount(final int slotIndex, final long amount) { validateIndex(slotIndex); final ResourceAmount resourceAmount = this.current.get(slotIndex); - if (resourceAmount.getAmount() - amount <= 0) { + if (resourceAmount.amount() - amount <= 0) { this.current.remove(slotIndex); } else { - resourceAmount.decrement(amount); + this.current.put( + slotIndex, + new ResourceAmount(resourceAmount.resource(), resourceAmount.amount() - amount) + ); } } @@ -142,7 +145,10 @@ public void shrinkExportedAmount(final int slotIndex, final long amount) { public void growExportedAmount(final int slotIndex, final long amount) { validateIndex(slotIndex); final ResourceAmount resourceAmount = this.current.get(slotIndex); - resourceAmount.increment(amount); + this.current.put( + slotIndex, + new ResourceAmount(resourceAmount.resource(), resourceAmount.amount() + amount) + ); } @Override diff --git a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/ResourceAmount.java b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/ResourceAmount.java index b9f697637..bcf027bba 100644 --- a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/ResourceAmount.java +++ b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/ResourceAmount.java @@ -6,66 +6,15 @@ /** * A class representing a resource and a corresponding amount. - * The resource cannot be mutated but the amount can be modified. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") -public final class ResourceAmount { - private final ResourceKey resource; - private long amount; - +public record ResourceAmount(ResourceKey resource, long amount) { /** * @param resource the resource, must be non-null * @param amount the amount, must be larger than 0 */ - public ResourceAmount(final ResourceKey resource, final long amount) { + public ResourceAmount { validate(resource, amount); - this.resource = resource; - this.amount = amount; - } - - public ResourceKey getResource() { - return resource; - } - - public long getAmount() { - return amount; - } - - public ResourceAmount copy() { - return new ResourceAmount(resource, amount); - } - - /** - * Increments with the given amount. - * - * @param amountToIncrement the amount to increment, must be larger than 0 - */ - public void increment(final long amountToIncrement) { - CoreValidations.validateLargerThanZero(amountToIncrement, "Amount to increment must be larger than 0"); - this.amount += amountToIncrement; - } - - /** - * Decrements with the given amount. - * The amount, after performing this decrement, may not be 0 or less than 0. - * - * @param amountToDecrement the amount to decrement, a positive number - */ - public void decrement(final long amountToDecrement) { - CoreValidations.validateLargerThanZero(amountToDecrement, "Amount to decrement must be larger than 0"); - CoreValidations.validateLargerThanZero( - amount - amountToDecrement, - "Cannot decrement, amount will be zero or negative" - ); - this.amount -= amountToDecrement; - } - - @Override - public String toString() { - return "ResourceAmount{" - + "resource=" + resource - + ", amount=" + amount - + '}'; } public static void validate(final ResourceKey resource, final long amount) { diff --git a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/AbstractProxyResourceList.java b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/AbstractProxyResourceList.java index c7c6cd581..a4df54f02 100644 --- a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/AbstractProxyResourceList.java +++ b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/AbstractProxyResourceList.java @@ -5,6 +5,7 @@ import java.util.Collection; import java.util.Optional; +import java.util.Set; import org.apiguardian.api.API; @@ -30,15 +31,30 @@ public Optional remove(final ResourceKey resource, final long a } @Override - public Optional get(final ResourceKey resource) { + public Collection copyState() { + return delegate.copyState(); + } + + @Override + public long get(final ResourceKey resource) { return delegate.get(resource); } @Override - public Collection getAll() { + public boolean contains(final ResourceKey resource) { + return delegate.contains(resource); + } + + @Override + public Set getAll() { return delegate.getAll(); } + @Override + public ResourceList copy() { + return delegate.copy(); + } + @Override public void clear() { delegate.clear(); diff --git a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceList.java b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceList.java index 7249e2a40..44f86eaf3 100644 --- a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceList.java +++ b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceList.java @@ -5,6 +5,7 @@ import java.util.Collection; import java.util.Optional; +import java.util.Set; import org.apiguardian.api.API; @@ -31,7 +32,7 @@ public interface ResourceList { * @return the result of the operation */ default OperationResult add(ResourceAmount resourceAmount) { - return add(resourceAmount.getResource(), resourceAmount.getAmount()); + return add(resourceAmount.resource(), resourceAmount.amount()); } /** @@ -53,37 +54,52 @@ default OperationResult add(ResourceAmount resourceAmount) { * @return a result if the removal operation was successful, otherwise an empty {@link Optional} */ default Optional remove(ResourceAmount resourceAmount) { - return remove(resourceAmount.getResource(), resourceAmount.getAmount()); + return remove(resourceAmount.resource(), resourceAmount.amount()); } /** - * Retrieves the resource and its amount from the list, identified by resource. + * Retrieves all resources and their amounts from the list. * + * @return a list of resource amounts + */ + Collection copyState(); + + /** + * @return set of resources contained in this list + */ + Set getAll(); + + /** * @param resource the resource - * @return the resource amount if it's present in the list, otherwise an empty {@link Optional} + * @return the amount stored, or zero if not stored */ - Optional get(ResourceKey resource); + long get(ResourceKey resource); /** - * Retrieves all resources and their amounts from the list. - * - * @return a list of resource amounts + * @param resource the resource + * @return whether the list contains this resource */ - Collection getAll(); + boolean contains(ResourceKey resource); /** * Clears the list. */ void clear(); + /** + * Copies the list. + */ + ResourceList copy(); + /** * Represents the result of an operation in a {@link ResourceList}. * - * @param resourceAmount the current resource amount in the list - * @param change the delta caused by the operation - * @param available whether this resource is still available in the list, or if it was removed + * @param resource the resource affected by the operation + * @param amount teh current amount in the list + * @param change the delta caused by the operation + * @param available whether this resource is still available in the list, or if it was removed */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") - record OperationResult(ResourceAmount resourceAmount, long change, boolean available) { + record OperationResult(ResourceKey resource, long amount, long change, boolean available) { } } diff --git a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceListImpl.java b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceListImpl.java index 42aaae19a..c47cc8be0 100644 --- a/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceListImpl.java +++ b/refinedstorage-resource-api/src/main/java/com/refinedmods/refinedstorage/api/resource/list/ResourceListImpl.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage.api.resource.list; +import com.refinedmods.refinedstorage.api.core.CoreValidations; import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; @@ -8,6 +9,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; +import java.util.Set; import org.apiguardian.api.API; @@ -16,9 +18,9 @@ */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.2") public class ResourceListImpl implements ResourceList { - private final Map entries; + private final Map entries; - private ResourceListImpl(final Map entries) { + private ResourceListImpl(final Map entries) { this.entries = entries; } @@ -32,7 +34,8 @@ public static ResourceListImpl orderPreserving() { @Override public OperationResult add(final ResourceKey resource, final long amount) { - final ResourceAmount existing = entries.get(resource); + ResourceAmount.validate(resource, amount); + final Entry existing = entries.get(resource); if (existing != null) { return addToExisting(existing, amount); } else { @@ -40,63 +43,104 @@ public OperationResult add(final ResourceKey resource, final long amount) { } } - private OperationResult addToExisting(final ResourceAmount resourceAmount, final long amount) { - resourceAmount.increment(amount); - - return new OperationResult(resourceAmount, amount, true); + private OperationResult addToExisting(final Entry entry, final long amount) { + entry.increment(amount); + return new OperationResult(entry.resource, entry.amount, amount, true); } private OperationResult addNew(final ResourceKey resource, final long amount) { - final ResourceAmount resourceAmount = new ResourceAmount(resource, amount); - entries.put(resource, resourceAmount); - return new OperationResult(resourceAmount, amount, true); + final Entry entry = new Entry(resource, amount); + entries.put(resource, entry); + return new OperationResult(resource, amount, amount, true); } @Override public Optional remove(final ResourceKey resource, final long amount) { ResourceAmount.validate(resource, amount); - - final ResourceAmount existing = entries.get(resource); + final Entry existing = entries.get(resource); if (existing != null) { - if (existing.getAmount() - amount <= 0) { + if (existing.amount - amount <= 0) { return removeCompletely(existing); } else { return removePartly(amount, existing); } } - return Optional.empty(); } - private Optional removePartly(final long amount, - final ResourceAmount resourceAmount) { - resourceAmount.decrement(amount); - - return Optional.of(new OperationResult(resourceAmount, -amount, true)); + private Optional removePartly(final long amount, final Entry entry) { + entry.decrement(amount); + return Optional.of(new OperationResult(entry.resource, entry.amount, -amount, true)); } - private Optional removeCompletely(final ResourceAmount resourceAmount) { - entries.remove(resourceAmount.getResource()); - + private Optional removeCompletely(final Entry entry) { + entries.remove(entry.resource); return Optional.of(new OperationResult( - resourceAmount, - -resourceAmount.getAmount(), + entry.resource, + 0, + -entry.amount, false )); } @Override - public Optional get(final ResourceKey resource) { - return Optional.ofNullable(entries.get(resource)); + public Collection copyState() { + return entries.values().stream().map(Entry::toResourceAmount).toList(); } @Override - public Collection getAll() { - return entries.values(); + public Set getAll() { + return entries.keySet(); + } + + @Override + public long get(final ResourceKey resource) { + final Entry entry = entries.get(resource); + return entry != null ? entry.amount : 0; + } + + @Override + public boolean contains(final ResourceKey resource) { + return entries.containsKey(resource); } @Override public void clear() { entries.clear(); } + + @Override + public ResourceList copy() { + final ResourceList copy = ResourceListImpl.create(); + entries.forEach((key, entry) -> copy.add(key, entry.amount)); + return copy; + } + + private static class Entry { + private final ResourceKey resource; + private long amount; + + private Entry(final ResourceKey resource, final long amount) { + this.resource = resource; + this.amount = amount; + } + + private void increment(final long amountToIncrement) { + CoreValidations.validateLargerThanZero(amountToIncrement, "Amount to increment must be larger than 0"); + this.amount += amountToIncrement; + } + + private void decrement(final long amountToDecrement) { + CoreValidations.validateLargerThanZero(amountToDecrement, "Amount to decrement must be larger than 0"); + CoreValidations.validateLargerThanZero( + amount - amountToDecrement, + "Cannot decrement, amount will be zero or negative" + ); + this.amount -= amountToDecrement; + } + + private ResourceAmount toResourceAmount() { + return new ResourceAmount(resource, amount); + } + } } diff --git a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/ResourceAmountTest.java b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/ResourceAmountTest.java deleted file mode 100644 index b692225de..000000000 --- a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/ResourceAmountTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.refinedmods.refinedstorage.api.resource; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class ResourceAmountTest { - @Test - void testValidResource() { - // Act - final ResourceAmount resourceAmount = new ResourceAmount(TestResource.A, 1); - - // Assert - assertThat(resourceAmount.getAmount()).isEqualTo(1); - assertThat(resourceAmount.getResource()).isEqualTo(TestResource.A); - } - - @Test - @SuppressWarnings("ConstantConditions") - void testInvalidResource() { - // Act & assert - assertThrows(NullPointerException.class, () -> new ResourceAmount(null, 1)); - } - - @Test - void testInvalidAmount() { - // Act & assert - assertThrows(IllegalArgumentException.class, () -> new ResourceAmount(TestResource.A, 0)); - assertThrows(IllegalArgumentException.class, () -> new ResourceAmount(TestResource.A, -1)); - } - - @Test - void shouldNotIncrementZeroOrNegativeAmount() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 1); - - // Act & assert - assertThrows(IllegalArgumentException.class, () -> sut.increment(0)); - assertThrows(IllegalArgumentException.class, () -> sut.increment(-1)); - } - - @Test - void shouldNotDecrementZeroOrNegativeAmount() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); - - // Act & assert - assertThrows(IllegalArgumentException.class, () -> sut.decrement(0)); - assertThrows(IllegalArgumentException.class, () -> sut.decrement(-1)); - } - - @Test - void shouldNotDecrementLeadingToZeroAmount() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); - - // Act & assert - assertThrows(IllegalArgumentException.class, () -> sut.decrement(3)); - } - - @Test - void shouldIncrement() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); - - // Act - sut.increment(2); - - // Assert - assertThat(sut.getAmount()).isEqualTo(5); - } - - @Test - void shouldDecrement() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); - - // Act - sut.decrement(2); - - // Assert - assertThat(sut.getAmount()).isEqualTo(1); - } - - @Test - void testToString() { - // Arrange - final ResourceAmount sut = new ResourceAmount(TestResource.A, 3); - - // Act & assert - assertThat(sut).hasToString( - "ResourceAmount{" - + "resource=A" - + ", amount=3" - + '}' - ); - } -} diff --git a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/TestResource.java b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/TestResource.java index 996358103..b677a0a2a 100644 --- a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/TestResource.java +++ b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/TestResource.java @@ -3,5 +3,6 @@ public enum TestResource implements ResourceKey { A, B, - C + C, + D } diff --git a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/AbstractResourceListTest.java b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/AbstractResourceListTest.java index 78e10ca3e..2ed6f703c 100644 --- a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/AbstractResourceListTest.java +++ b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/AbstractResourceListTest.java @@ -31,13 +31,17 @@ void shouldAddNewResource() { // Assert assertThat(result.change()).isEqualTo(10); - assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.amount()).isEqualTo(10); + assertThat(result.resource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount(TestResource.A, 10) ); + assertThat(list.get(TestResource.A)).isEqualTo(10); + assertThat(list.contains(TestResource.A)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.A); } @Test @@ -47,13 +51,17 @@ void shouldAddNewResourceWithResourceAmountDirectly() { // Assert assertThat(result.change()).isEqualTo(10); - assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.amount()).isEqualTo(10); + assertThat(result.resource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount(TestResource.A, 10) ); + assertThat(list.get(TestResource.A)).isEqualTo(10); + assertThat(list.contains(TestResource.A)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.A); } @Test @@ -64,18 +72,22 @@ void shouldAddMultipleOfSameResource() { // Assert assertThat(result1.change()).isEqualTo(10); - assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result1.amount()).isEqualTo(10); + assertThat(result1.resource()).isEqualTo(TestResource.A); assertThat(result1.available()).isTrue(); assertThat(result2.change()).isEqualTo(5); - assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result2.amount()).isEqualTo(15); + assertThat(result2.resource()).isEqualTo(TestResource.A); assertThat(result2.available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount(TestResource.A, 15) ); + assertThat(list.get(TestResource.A)).isEqualTo(15); + assertThat(list.contains(TestResource.A)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.A); } @Test @@ -87,24 +99,30 @@ void shouldAddMultipleOfDifferentResources() { // Assert assertThat(result1.change()).isEqualTo(10); - assertThat(result1.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result1.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result1.amount()).isEqualTo(10); + assertThat(result1.resource()).isEqualTo(TestResource.A); assertThat(result1.available()).isTrue(); assertThat(result2.change()).isEqualTo(5); - assertThat(result2.resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result2.amount()).isEqualTo(15); + assertThat(result2.resource()).isEqualTo(TestResource.A); assertThat(result2.available()).isTrue(); assertThat(result3.change()).isEqualTo(3); - assertThat(result3.resourceAmount().getAmount()).isEqualTo(3); - assertThat(result3.resourceAmount().getResource()).isEqualTo(TestResource.B); + assertThat(result3.amount()).isEqualTo(3); + assertThat(result3.resource()).isEqualTo(TestResource.B); assertThat(result3.available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.A, 15), new ResourceAmount(TestResource.B, 3) ); + assertThat(list.get(TestResource.A)).isEqualTo(15); + assertThat(list.contains(TestResource.A)).isTrue(); + assertThat(list.get(TestResource.B)).isEqualTo(3); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactlyInAnyOrder(TestResource.A, TestResource.B); } @Test @@ -142,14 +160,21 @@ void shouldRemoveResourcePartly() { // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-5); - assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result2.get().amount()).isEqualTo(15); + assertThat(result2.get().resource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.A, 15), new ResourceAmount(TestResource.B, 6) ); + + assertThat(list.get(TestResource.A)).isEqualTo(15); + assertThat(list.contains(TestResource.A)).isTrue(); + assertThat(list.get(TestResource.B)).isEqualTo(6); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactlyInAnyOrder(TestResource.A, TestResource.B); } @Test @@ -167,14 +192,21 @@ void shouldRemoveResourcePartlyWithResourceAmountDirectly() { // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-5); - assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(15); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result2.get().amount()).isEqualTo(15); + assertThat(result2.get().resource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isTrue(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.A, 15), new ResourceAmount(TestResource.B, 6) ); + + assertThat(list.get(TestResource.A)).isEqualTo(15); + assertThat(list.contains(TestResource.A)).isTrue(); + assertThat(list.get(TestResource.B)).isEqualTo(6); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactlyInAnyOrder(TestResource.A, TestResource.B); } @Test @@ -184,18 +216,25 @@ void shouldRemoveResourceCompletely() { list.add(TestResource.B, 6); // Act - final Optional result2 = list.remove(TestResource.A, 20); + final Optional result = list.remove(TestResource.A, 20); // Assert - assertThat(result2).isPresent(); - assertThat(result2.get().change()).isEqualTo(-20); - assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); - assertThat(result2.get().available()).isFalse(); + assertThat(result).isPresent(); + assertThat(result.get().change()).isEqualTo(-20); + assertThat(result.get().amount()).isZero(); + assertThat(result.get().resource()).isEqualTo(TestResource.A); + assertThat(result.get().available()).isFalse(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.B, 6) ); + + assertThat(list.get(TestResource.A)).isZero(); + assertThat(list.contains(TestResource.A)).isFalse(); + assertThat(list.get(TestResource.B)).isEqualTo(6); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.B); } @Test @@ -213,13 +252,20 @@ void shouldRemoveResourceCompletelyWithResourceAmountDirectly() { // Assert assertThat(result2).isPresent(); assertThat(result2.get().change()).isEqualTo(-20); - assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result2.get().amount()).isZero(); + assertThat(result2.get().resource()).isEqualTo(TestResource.A); assertThat(result2.get().available()).isFalse(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.B, 6) ); + + assertThat(list.get(TestResource.A)).isZero(); + assertThat(list.contains(TestResource.A)).isFalse(); + assertThat(list.get(TestResource.B)).isEqualTo(6); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.B); } @Test @@ -229,18 +275,25 @@ void shouldNotRemoveResourceWithMoreThanIsAvailable() { list.add(TestResource.B, 6); // Act - final Optional result2 = list.remove(TestResource.A, 21); + final Optional result = list.remove(TestResource.A, 21); // Assert - assertThat(result2).isPresent(); - assertThat(result2.get().change()).isEqualTo(-20); - assertThat(result2.get().resourceAmount().getAmount()).isEqualTo(20); - assertThat(result2.get().resourceAmount().getResource()).isEqualTo(TestResource.A); - assertThat(result2.get().available()).isFalse(); + assertThat(result).isPresent(); + assertThat(result.get().change()).isEqualTo(-20); + assertThat(result.get().amount()).isZero(); + assertThat(result.get().resource()).isEqualTo(TestResource.A); + assertThat(result.get().available()).isFalse(); - assertThat(list.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( new ResourceAmount(TestResource.B, 6) ); + + assertThat(list.get(TestResource.A)).isZero(); + assertThat(list.contains(TestResource.A)).isFalse(); + assertThat(list.get(TestResource.B)).isEqualTo(6); + assertThat(list.contains(TestResource.B)).isTrue(); + + assertThat(list.getAll()).containsExactly(TestResource.B); } @Test @@ -258,62 +311,53 @@ void shouldNotRemoveInvalidResourceOrAmount() { } @Test - void shouldBeAbleToRetrieveByResourceAfterAdding() { - // Arrange - list.add(TestResource.A, 6); - - // Act - final Optional resourceAmount = list.get(TestResource.A); - - // Assert - assertThat(resourceAmount).isPresent(); - assertThat(resourceAmount.get().getResource()).isEqualTo(TestResource.A); - assertThat(resourceAmount.get().getAmount()).isEqualTo(6); - } - - @Test - void shouldStillBeAbleToRetrieveByResourceWhenRemovingPartly() { + void shouldClearList() { // Arrange list.add(TestResource.A, 10); - list.remove(TestResource.A, 3); + list.add(TestResource.B, 5); + + final Collection contentsBeforeClear = new ArrayList<>(list.copyState()); // Act - final Optional resourceAmount = list.get(TestResource.A); + list.clear(); // Assert - assertThat(resourceAmount).isPresent(); - assertThat(resourceAmount.get().getResource()).isEqualTo(TestResource.A); - assertThat(resourceAmount.get().getAmount()).isEqualTo(7); - } + final Collection contentsAfterClear = list.copyState(); - @Test - void shouldNotBeAbleToRetrieveByResourceWhenRemovingCompletely() { - // Arrange - list.add(TestResource.A, 10); - list.remove(TestResource.A, 10); + assertThat(contentsBeforeClear).hasSize(2); + assertThat(contentsAfterClear).isEmpty(); - // Act - final Optional resourceAmount = list.get(TestResource.A); + assertThat(list.get(TestResource.A)).isZero(); + assertThat(list.get(TestResource.B)).isZero(); - // Assert - assertThat(resourceAmount).isNotPresent(); + assertThat(list.getAll()).isEmpty(); } @Test - void shouldClearList() { + void shouldCopyList() { // Arrange list.add(TestResource.A, 10); list.add(TestResource.B, 5); - final Collection contentsBeforeClear = new ArrayList<>(list.getAll()); - // Act - list.clear(); + final ResourceList copy = list.copy(); - // Assert - final Collection contentsAfterClear = list.getAll(); + list.add(TestResource.A, 1); + list.add(TestResource.C, 3); - assertThat(contentsBeforeClear).hasSize(2); - assertThat(contentsAfterClear).isEmpty(); + copy.add(TestResource.A, 2); + copy.add(TestResource.D, 3); + + // Assert + assertThat(list.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(TestResource.A, 11), + new ResourceAmount(TestResource.B, 5), + new ResourceAmount(TestResource.C, 3) + ); + assertThat(copy.copyState()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( + new ResourceAmount(TestResource.A, 12), + new ResourceAmount(TestResource.B, 5), + new ResourceAmount(TestResource.D, 3) + ); } } diff --git a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/listenable/ListenableResourceListTest.java b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/listenable/ListenableResourceListTest.java index 24aa02530..4cf2d9393 100644 --- a/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/listenable/ListenableResourceListTest.java +++ b/refinedstorage-resource-api/src/test/java/com/refinedmods/refinedstorage/api/resource/list/listenable/ListenableResourceListTest.java @@ -35,8 +35,8 @@ void shouldCallListenerWhenAdding() { // Assert assertThat(result.change()).isEqualTo(10); - assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.amount()).isEqualTo(10); + assertThat(result.resource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(listener.changes).hasSize(1); } @@ -48,8 +48,8 @@ void shouldNotCallListenerWhenAddingWithoutListener() { // Assert assertThat(result.change()).isEqualTo(10); - assertThat(result.resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.amount()).isEqualTo(10); + assertThat(result.resource()).isEqualTo(TestResource.A); assertThat(result.available()).isTrue(); assertThat(listener.changes).isEmpty(); } @@ -66,8 +66,8 @@ void shouldCallListenerWhenRemoving() { // Assert assertThat(result).isPresent(); assertThat(result.get().change()).isEqualTo(-10); - assertThat(result.get().resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.get().resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.get().amount()).isZero(); + assertThat(result.get().resource()).isEqualTo(TestResource.A); assertThat(result.get().available()).isFalse(); assertThat(listener.changes).hasSize(2); } @@ -83,8 +83,8 @@ void shouldNotCallListenerWhenRemovingWithoutListener() { // Assert assertThat(result).isPresent(); assertThat(result.get().change()).isEqualTo(-10); - assertThat(result.get().resourceAmount().getAmount()).isEqualTo(10); - assertThat(result.get().resourceAmount().getResource()).isEqualTo(TestResource.A); + assertThat(result.get().amount()).isZero(); + assertThat(result.get().resource()).isEqualTo(TestResource.A); assertThat(result.get().available()).isFalse(); assertThat(listener.changes).isEmpty(); } diff --git a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/InMemoryStorageImpl.java b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/InMemoryStorageImpl.java index 0d7a9ad77..e21e42836 100644 --- a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/InMemoryStorageImpl.java +++ b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/InMemoryStorageImpl.java @@ -29,14 +29,12 @@ public InMemoryStorageImpl() { @Override public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { ResourceAmount.validate(resource, amount); - - return list.get(resource).map(resourceAmount -> { - final long maxExtract = Math.min( - resourceAmount.getAmount(), - amount - ); - return doExtract(resource, maxExtract, action); - }).orElse(0L); + final long availableAmount = list.get(resource); + if (availableAmount == 0) { + return 0; + } + final long maxExtract = Math.min(availableAmount, amount); + return doExtract(resource, maxExtract, action); } private long doExtract(final ResourceKey resource, final long amount, final Action action) { @@ -59,7 +57,7 @@ public long insert(final ResourceKey resource, final long amount, final Action a @Override public Collection getAll() { - return list.getAll(); + return list.copyState(); } @Override diff --git a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/composite/CompositeStorageImpl.java b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/composite/CompositeStorageImpl.java index 167538ab4..829ba79bd 100644 --- a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/composite/CompositeStorageImpl.java +++ b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/composite/CompositeStorageImpl.java @@ -140,7 +140,7 @@ public long insert(final ResourceKey resource, final long amount, final Action a @Override public Collection getAll() { - return list.getAll(); + return list.copyState(); } @Override @@ -211,8 +211,8 @@ private void addContentOfSourceToList(final Storage source) { private void removeContentOfSourceFromList(final Storage source) { source.getAll().forEach(resourceAmount -> list.remove( - resourceAmount.getResource(), - resourceAmount.getAmount() + resourceAmount.resource(), + resourceAmount.amount() )); } } diff --git a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/external/ExternalStorage.java b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/external/ExternalStorage.java index 96694ff2f..5e063794a 100644 --- a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/external/ExternalStorage.java +++ b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/external/ExternalStorage.java @@ -11,7 +11,6 @@ import java.util.Collection; import java.util.HashSet; -import java.util.Optional; import java.util.Set; import org.apiguardian.api.API; @@ -60,36 +59,38 @@ public boolean detectChanges() { } private boolean detectCompleteRemovals(final ResourceList updatedCache) { - final Set removedInUpdatedCache = new HashSet<>(); - for (final ResourceAmount inOldCache : cache.getAll()) { - final Optional inUpdatedCache = updatedCache.get(inOldCache.getResource()); - if (inUpdatedCache.isEmpty()) { + final Set removedInUpdatedCache = new HashSet<>(); + for (final ResourceKey inOldCache : cache.getAll()) { + if (!updatedCache.contains(inOldCache)) { removedInUpdatedCache.add(inOldCache); } } - removedInUpdatedCache.forEach(removed -> removeFromCache(removed.getResource(), removed.getAmount())); + removedInUpdatedCache.forEach(this::removeFromCache); return !removedInUpdatedCache.isEmpty(); } private boolean detectAdditionsAndPartialRemovals(final ResourceList updatedCache) { boolean hasChanges = false; - for (final ResourceAmount inUpdatedCache : updatedCache.getAll()) { - final Optional inOldCache = cache.get(inUpdatedCache.getResource()); - final boolean doesNotExistInOldCache = inOldCache.isEmpty(); + for (final ResourceKey resource : updatedCache.getAll()) { + final long amountInUpdatedCache = updatedCache.get(resource); + final long amountInOldCache = cache.get(resource); + final boolean doesNotExistInOldCache = amountInOldCache == 0; if (doesNotExistInOldCache) { - addToCache(inUpdatedCache.getResource(), inUpdatedCache.getAmount()); + addToCache(resource, amountInUpdatedCache); hasChanges = true; } else { - hasChanges |= detectPotentialDifference(inUpdatedCache, inOldCache.get()); + hasChanges |= detectPotentialDifference(resource, amountInUpdatedCache, amountInOldCache); } } return hasChanges; } - private boolean detectPotentialDifference(final ResourceAmount inUpdatedCache, - final ResourceAmount inOldCache) { - final ResourceKey resource = inUpdatedCache.getResource(); - final long diff = inUpdatedCache.getAmount() - inOldCache.getAmount(); + private boolean detectPotentialDifference( + final ResourceKey resource, + final long amountInUpdatedCache, + final long amountInOldCache + ) { + final long diff = amountInUpdatedCache - amountInOldCache; if (diff > 0) { addToCache(resource, diff); return true; @@ -105,6 +106,10 @@ private void addToCache(final ResourceKey resource, final long amount) { parents.forEach(parent -> parent.addToCache(resource, amount)); } + private void removeFromCache(final ResourceKey resource) { + removeFromCache(resource, cache.get(resource)); + } + private void removeFromCache(final ResourceKey resource, final long amount) { cache.remove(resource, amount); parents.forEach(parent -> parent.removeFromCache(resource, amount)); @@ -118,12 +123,12 @@ private ResourceList buildCache() { @Override public Collection getAll() { - return cache.getAll(); + return cache.copyState(); } @Override public long getStored() { - return getAll().stream().mapToLong(ResourceAmount::getAmount).sum(); + return getAll().stream().mapToLong(ResourceAmount::amount).sum(); } @Override diff --git a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorage.java b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorage.java index 7a5920523..1fb5f228d 100644 --- a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorage.java +++ b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorage.java @@ -1,12 +1,10 @@ package com.refinedmods.refinedstorage.api.storage.root; -import com.refinedmods.refinedstorage.api.resource.ResourceAmount; import com.refinedmods.refinedstorage.api.resource.ResourceKey; import com.refinedmods.refinedstorage.api.resource.list.listenable.ResourceListListener; import com.refinedmods.refinedstorage.api.storage.Storage; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedStorage; -import java.util.Optional; import java.util.function.Predicate; import org.apiguardian.api.API; @@ -33,10 +31,16 @@ public interface RootStorage extends Storage, TrackedStorage { void removeListener(ResourceListListener listener); /** - * @param resource the resource to retrieve - * @return the resource amount for the given resource, if present + * @param resource the resource + * @return the amount stored, or zero if not stored */ - Optional get(ResourceKey resource); + long get(ResourceKey resource); + + /** + * @param resource the resource + * @return whether the storage contains the resource + */ + boolean contains(ResourceKey resource); /** * Sorts the sources in the backing storage. diff --git a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImpl.java b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImpl.java index c38172f67..b85e38871 100644 --- a/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImpl.java +++ b/refinedstorage-storage-api/src/main/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImpl.java @@ -63,10 +63,15 @@ public void removeListener(final ResourceListListener listener) { } @Override - public Optional get(final ResourceKey resource) { + public long get(final ResourceKey resource) { return list.get(resource); } + @Override + public boolean contains(final ResourceKey resource) { + return list.contains(resource); + } + @Override public long extract(final ResourceKey resource, final long amount, final Action action, final Actor actor) { return storage.extract(resource, amount, action, actor); diff --git a/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/TransferHelperTest.java b/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/TransferHelperTest.java index 633034084..d25d33057 100644 --- a/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/TransferHelperTest.java +++ b/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/TransferHelperTest.java @@ -74,8 +74,8 @@ void shouldTransferCorrectly(final Transfer transfer) { if (transfer.amountInSource != null) { source.insert( - transfer.amountInSource.getResource(), - transfer.amountInSource.getAmount(), + transfer.amountInSource.resource(), + transfer.amountInSource.amount(), Action.EXECUTE, EmptyActor.INSTANCE ); @@ -83,8 +83,8 @@ void shouldTransferCorrectly(final Transfer transfer) { if (transfer.amountInDestination != null) { destination.insert( - transfer.amountInDestination.getResource(), - transfer.amountInDestination.getAmount(), + transfer.amountInDestination.resource(), + transfer.amountInDestination.amount(), Action.EXECUTE, EmptyActor.INSTANCE ); @@ -92,8 +92,8 @@ void shouldTransferCorrectly(final Transfer transfer) { // Act final long transferred = TransferHelper.transfer( - transfer.amountToTransfer.getResource(), - transfer.amountToTransfer.getAmount(), + transfer.amountToTransfer.resource(), + transfer.amountToTransfer.amount(), EmptyActor.INSTANCE, source, destination, diff --git a/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImplTest.java b/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImplTest.java index 67896ab94..da1362897 100644 --- a/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImplTest.java +++ b/refinedstorage-storage-api/src/test/java/com/refinedmods/refinedstorage/api/storage/root/RootStorageImplTest.java @@ -11,8 +11,6 @@ import com.refinedmods.refinedstorage.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage.api.storage.tracked.TrackedStorageImpl; -import java.util.Optional; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -116,9 +114,8 @@ void shouldCallListenerOnInsertion(final Action action) { verify(listener, atMost(1)).onChanged(changedResource.capture()); assertThat(changedResource.getValue().change()).isEqualTo(8); - assertThat(changedResource.getValue().resourceAmount()).usingRecursiveComparison().isEqualTo( - new ResourceAmount(A, 10) - ); + assertThat(changedResource.getValue().resource()).isEqualTo(A); + assertThat(changedResource.getValue().amount()).isEqualTo(10); } else { verify(listener, never()).onChanged(any()); } @@ -147,9 +144,8 @@ void shouldCallListenerOnExtraction(final Action action) { verify(listener, atMost(1)).onChanged(changedResource.capture()); assertThat(changedResource.getValue().change()).isEqualTo(-5); - assertThat(changedResource.getValue().resourceAmount()).usingRecursiveComparison().isEqualTo( - new ResourceAmount(A, 3) - ); + assertThat(changedResource.getValue().resource()).isEqualTo(A); + assertThat(changedResource.getValue().amount()).isEqualTo(3); } else { verify(listener, never()).onChanged(any()); } @@ -211,25 +207,35 @@ void shouldExtract() { } @Test - void shouldBeAbleToRetrieveResource() { + void shouldRetrieveIfResourceIsContained() { // Arrange final Storage storage = new LimitedStorageImpl(100); storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); sut.addSource(storage); - // Act - final Optional resource = sut.get(A); + // Act & assert + assertThat(sut.contains(A)).isTrue(); + assertThat(sut.contains(B)).isFalse(); + } - // Assert - assertThat(resource).isPresent(); - assertThat(resource.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount(A, 50)); - assertThat(sut.findTrackedResourceByActorType(A, EmptyActor.class)).isEmpty(); + @Test + void shouldRetrieveResourceAmount() { + // Arrange + final Storage storage = new LimitedStorageImpl(100); + storage.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); + storage.extract(A, 25, Action.EXECUTE, EmptyActor.INSTANCE); + + sut.addSource(storage); + + // Act & assert + assertThat(sut.get(A)).isEqualTo(25); + assertThat(sut.get(B)).isZero(); } @Test @SuppressWarnings("AssertBetweenInconvertibleTypes") - void shouldBeAbleToRetrieveTrackedResource() { + void shouldRetrieveTrackedResource() { // Arrange final Storage storage = new TrackedStorageImpl( new LimitedStorageImpl(100), @@ -242,28 +248,13 @@ void shouldBeAbleToRetrieveTrackedResource() { sut.insert(A, 50, Action.EXECUTE, EmptyActor.INSTANCE); // Assert - final Optional value = sut.get(A); - assertThat(value).isPresent(); - assertThat(value.get()).usingRecursiveComparison().isEqualTo(new ResourceAmount(A, 50)); - + assertThat(sut.contains(A)).isTrue(); assertThat(sut.findTrackedResourceByActorType(A, EmptyActor.class)) .get() .usingRecursiveComparison() .isEqualTo(new TrackedResource("Empty", 0)); } - @Test - void shouldNotBeAbleToRetrieveNonExistentResource() { - // Arrange - sut.addSource(new LimitedStorageImpl(100)); - - // Act - final Optional resource = sut.get(A); - - // Assert - assertThat(resource).isEmpty(); - } - @Test void shouldSortSources() { // Arrange