Skip to content

Commit f1eec50

Browse files
committed
Add additional helper methods for working with inventories.
1 parent 10c78bc commit f1eec50

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

Common/src/main/java/net/darkhax/bookshelf/api/util/IInventoryHelper.java

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
import javax.annotation.Nullable;
1818
import java.util.Random;
19+
import java.util.function.BiConsumer;
20+
import java.util.function.Consumer;
1921

2022
public interface IInventoryHelper {
2123

@@ -124,4 +126,64 @@ default NonNullList<ItemStack> keepDamageableItems(CraftingContainer inv, NonNul
124126

125127
return keptItems;
126128
}
127-
}
129+
130+
/**
131+
* Creates a list view of a Container's inventory contents.
132+
*
133+
* @param inventory The container to view.
134+
* @return A list view of the provided containers inventory contents.
135+
*/
136+
default NonNullList<ItemStack> toList(Container inventory) {
137+
138+
final NonNullList<ItemStack> items = NonNullList.withSize(inventory.getContainerSize(), ItemStack.EMPTY);
139+
applyForEach(inventory, items::set);
140+
return items;
141+
}
142+
143+
/**
144+
* Fills an inventory with a list of ItemStack. The inventory size and container size must be identical.
145+
*
146+
* @param inventory The inventory to fill.
147+
* @param fillWith The items to fill the inventory with.
148+
*/
149+
default void fill(Container inventory, NonNullList<ItemStack> fillWith) {
150+
151+
if (inventory.getContainerSize() != fillWith.size()) {
152+
153+
throw new IllegalStateException("Inventory size did not match! inv_size=" + inventory.getContainerSize() + " fill_size=" + fillWith.size());
154+
}
155+
156+
for (int slotId = 0; slotId < fillWith.size(); slotId++) {
157+
158+
inventory.setItem(slotId, fillWith.get(slotId));
159+
}
160+
}
161+
162+
/**
163+
* Applies an action to every item within the inventory.
164+
*
165+
* @param inventory The inventory container.
166+
* @param action The action to apply.
167+
*/
168+
default void applyForEach(Container inventory, Consumer<ItemStack> action) {
169+
170+
for (int slotId = 0; slotId < inventory.getContainerSize(); slotId++) {
171+
172+
action.accept(inventory.getItem(slotId));
173+
}
174+
}
175+
176+
/**
177+
* Applies an action to every item within the inventory.
178+
*
179+
* @param inventory The inventory container.
180+
* @param action The action to apply.
181+
*/
182+
default void applyForEach(Container inventory, BiConsumer<Integer, ItemStack> action) {
183+
184+
for (int slotId = 0; slotId < inventory.getContainerSize(); slotId++) {
185+
186+
action.accept(slotId, inventory.getItem(slotId));
187+
}
188+
}
189+
}

0 commit comments

Comments
 (0)