Skip to content

Commit

Permalink
item/stack.go: Fixed panic when copying empty enchantments/data map.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sandertv committed Dec 24, 2024
1 parent 055377b commit 69cca3a
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions server/item/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ func (s Stack) Lore() []string {
// WithValue stores Values by encoding them using the encoding/gob package. Users of WithValue must ensure
// that their value is valid for encoding with this package.
func (s Stack) WithValue(key string, val any) Stack {
s.data = maps.Clone(s.data)
s.data = cloneMap(s.data)
if val != nil {
s.data[key] = val
} else {
Expand All @@ -233,7 +233,7 @@ func (s Stack) WithEnchantments(enchants ...Enchantment) Stack {
if _, ok := s.item.(Book); ok {
s.item = EnchantedBook{}
}
s.enchantments = maps.Clone(s.enchantments)
s.enchantments = cloneMap(s.enchantments)
for _, enchant := range enchants {
if _, ok := s.Item().(EnchantedBook); !ok && !enchant.t.CompatibleWithItem(s.item) {
// Enchantment is not compatible with the item.
Expand All @@ -246,7 +246,7 @@ func (s Stack) WithEnchantments(enchants ...Enchantment) Stack {

// WithoutEnchantments returns the current stack but with the passed enchantments removed.
func (s Stack) WithoutEnchantments(enchants ...EnchantmentType) Stack {
s.enchantments = maps.Clone(s.enchantments)
s.enchantments = cloneMap(s.enchantments)
for _, enchant := range enchants {
delete(s.enchantments, enchant)
}
Expand Down Expand Up @@ -386,6 +386,14 @@ func (s Stack) Values() map[string]any {
return maps.Clone(s.data)
}

// cloneMap calls maps.Clone, but initialises m if it does not yet exist.
func cloneMap[M ~map[K]V, K comparable, V any](m M) M {
if m == nil {
m = make(M)
}
return maps.Clone(m)
}

// stackID is a counter for unique stack IDs.
var stackID = new(int32)

Expand Down

0 comments on commit 69cca3a

Please sign in to comment.