remove_detached_inventory: Fix segfault during mod load
[oweals/minetest.git] / src / inventory.cpp
index ff2c15b651b431a5a3f333f31bfeee489e9ba54c..40dc602d0e855883a1d0a42549bdedb117c1fcda 100644 (file)
@@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include <sstream>
 #include "log.h"
 #include "itemdef.h"
-#include "strfnd.h"
+#include "util/strfnd.h"
 #include "content_mapnode.h" // For loading legacy MaterialItems
 #include "nameidmapping.h" // For loading legacy MaterialItems
 #include "util/serialize.h"
@@ -35,100 +35,29 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 
 static content_t content_translate_from_19_to_internal(content_t c_from)
 {
-       for(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
-       {
-               if(trans_table_19[i][1] == c_from)
-               {
-                       return trans_table_19[i][0];
+       for (const auto &tt : trans_table_19) {
+               if(tt[1] == c_from) {
+                       return tt[0];
                }
        }
        return c_from;
 }
 
-// If the string contains spaces, quotes or control characters, encodes as JSON.
-// Else returns the string unmodified.
-static std::string serializeJsonStringIfNeeded(const std::string &s)
-{
-       for(size_t i = 0; i < s.size(); ++i)
-       {
-               if(s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
-                       return serializeJsonString(s);
-       }
-       return s;
-}
-
-// Parses a string serialized by serializeJsonStringIfNeeded.
-static std::string deSerializeJsonStringIfNeeded(std::istream &is)
-{
-       std::ostringstream tmp_os;
-       bool expect_initial_quote = true;
-       bool is_json = false;
-       bool was_backslash = false;
-       for(;;)
-       {
-               char c = is.get();
-               if(is.eof())
-                       break;
-               if(expect_initial_quote && c == '"')
-               {
-                       tmp_os << c;
-                       is_json = true;
-               }
-               else if(is_json)
-               {
-                       tmp_os << c;
-                       if(was_backslash)
-                               was_backslash = false;
-                       else if(c == '\\')
-                               was_backslash = true;
-                       else if(c == '"')
-                               break; // Found end of string
-               }
-               else
-               {
-                       if(c == ' ')
-                       {
-                               // Found end of word
-                               is.unget();
-                               break;
-                       }
-                       else
-                       {
-                               tmp_os << c;
-                       }
-               }
-               expect_initial_quote = false;
-       }
-       if(is_json)
-       {
-               std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
-               return deSerializeJsonString(tmp_is);
-       }
-       else
-               return tmp_os.str();
-}
-
-
-ItemStack::ItemStack(std::string name_, u16 count_,
-               u16 wear_, std::string metadata_,
-               IItemDefManager *itemdef)
+ItemStack::ItemStack(const std::string &name_, u16 count_,
+               u16 wear_, IItemDefManager *itemdef) :
+       name(itemdef->getAlias(name_)),
+       count(count_),
+       wear(wear_)
 {
-       name = itemdef->getAlias(name_);
-       count = count_;
-       wear = wear_;
-       metadata = metadata_;
-
-       if(name.empty() || count == 0)
+       if (name.empty() || count == 0)
                clear();
-       else if(itemdef->get(name).type == ITEM_TOOL)
+       else if (itemdef->get(name).type == ITEM_TOOL)
                count = 1;
 }
 
 void ItemStack::serialize(std::ostream &os) const
 {
-       DSTACK(__FUNCTION_NAME);
-
-       if(empty())
+       if (empty())
                return;
 
        // Check how many parts of the itemstring are needed
@@ -137,7 +66,7 @@ void ItemStack::serialize(std::ostream &os) const
                parts = 2;
        if(wear != 0)
                parts = 3;
-       if(metadata != "")
+       if (!metadata.empty())
                parts = 4;
 
        os<<serializeJsonStringIfNeeded(name);
@@ -145,14 +74,14 @@ void ItemStack::serialize(std::ostream &os) const
                os<<" "<<count;
        if(parts >= 3)
                os<<" "<<wear;
-       if(parts >= 4)
-               os<<" "<<serializeJsonStringIfNeeded(metadata);
+       if (parts >= 4) {
+               os << " ";
+               metadata.serialize(os);
+       }
 }
 
 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
 {
-       DSTACK(__FUNCTION_NAME);
-
        clear();
 
        // Read name
@@ -163,7 +92,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
        std::getline(is, tmp, ' ');
        if(!tmp.empty())
                throw SerializationError("Unexpected text after item name");
-       
+
        if(name == "MaterialItem")
        {
                // Obsoleted on 2011-07-30
@@ -181,7 +110,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
                NameIdMapping legacy_nimap;
                content_mapnode_get_name_id_mapping(&legacy_nimap);
                legacy_nimap.getName(material, name);
-               if(name == "")
+               if(name.empty())
                        name = "unknown_block";
                if (itemdef)
                        name = itemdef->getAlias(name);
@@ -201,7 +130,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
                NameIdMapping legacy_nimap;
                content_mapnode_get_name_id_mapping(&legacy_nimap);
                legacy_nimap.getName(material, name);
-               if(name == "")
+               if(name.empty())
                        name = "unknown_block";
                if (itemdef)
                        name = itemdef->getAlias(name);
@@ -218,7 +147,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
                Strfnd fnd(all);
                fnd.next("\"");
                // If didn't skip to end, we have ""s
-               if(!fnd.atend()){
+               if(!fnd.at_end()){
                        name = fnd.next("\"");
                } else { // No luck, just read a word then
                        fnd.start(all);
@@ -246,7 +175,7 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
                Strfnd fnd(all);
                fnd.next("\"");
                // If didn't skip to end, we have ""s
-               if(!fnd.atend()){
+               if(!fnd.at_end()){
                        name = fnd.next("\"");
                } else { // No luck, just read a word then
                        fnd.start(all);
@@ -272,24 +201,23 @@ void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
                        // Read the count
                        std::string count_str;
                        std::getline(is, count_str, ' ');
-                       if(count_str.empty())
-                       {
+                       if (count_str.empty()) {
                                count = 1;
                                break;
                        }
-                       else
-                               count = stoi(count_str);
+
+                       count = stoi(count_str);
 
                        // Read the wear
                        std::string wear_str;
                        std::getline(is, wear_str, ' ');
                        if(wear_str.empty())
                                break;
-                       else
-                               wear = stoi(wear_str);
+
+                       wear = stoi(wear_str);
 
                        // Read metadata
-                       metadata = deSerializeJsonStringIfNeeded(is);
+                       metadata.deSerialize(is);
 
                        // In case fields are added after metadata, skip space here:
                        //std::getline(is, tmp, ' ');
@@ -319,11 +247,8 @@ std::string ItemStack::getItemString() const
 }
 
 
-ItemStack ItemStack::addItem(const ItemStack &newitem_,
-               IItemDefManager *itemdef)
+ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
 {
-       ItemStack newitem = newitem_;
-
        // If the item is empty or the position invalid, bail out
        if(newitem.empty())
        {
@@ -335,8 +260,9 @@ ItemStack ItemStack::addItem(const ItemStack &newitem_,
                *this = newitem;
                newitem.clear();
        }
-       // If item name differs, bail out
-       else if(name != newitem.name)
+       // If item name or metadata differs, bail out
+       else if (name != newitem.name
+               || metadata != newitem.metadata)
        {
                // cannot be added
        }
@@ -358,11 +284,10 @@ ItemStack ItemStack::addItem(const ItemStack &newitem_,
        return newitem;
 }
 
-bool ItemStack::itemFits(const ItemStack &newitem_,
+bool ItemStack::itemFits(ItemStack newitem,
                ItemStack *restitem,
                IItemDefManager *itemdef) const
 {
-       ItemStack newitem = newitem_;
 
        // If the item is empty or the position invalid, bail out
        if(newitem.empty())
@@ -374,8 +299,9 @@ bool ItemStack::itemFits(const ItemStack &newitem_,
        {
                newitem.clear();
        }
-       // If item name differs, bail out
-       else if(name != newitem.name)
+       // If item name or metadata differs, bail out
+       else if (name != newitem.name
+               || metadata != newitem.metadata)
        {
                // cannot be added
        }
@@ -385,7 +311,6 @@ bool ItemStack::itemFits(const ItemStack &newitem_,
                newitem.clear();
        }
        // Else the item does not fit fully. Return the rest.
-       // the rest.
        else
        {
                u16 freespace = freeSpace(itemdef);
@@ -394,6 +319,7 @@ bool ItemStack::itemFits(const ItemStack &newitem_,
 
        if(restitem)
                *restitem = newitem;
+
        return newitem.empty();
 }
 
@@ -432,27 +358,20 @@ ItemStack ItemStack::peekItem(u32 peekcount) const
        Inventory
 */
 
-InventoryList::InventoryList(std::string name, u32 size, IItemDefManager *itemdef)
+InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
+       m_name(name),
+       m_size(size),
+       m_itemdef(itemdef)
 {
-       m_name = name;
-       m_size = size;
-       m_width = 0;
-       m_itemdef = itemdef;
        clearItems();
-       //m_dirty = false;
-}
-
-InventoryList::~InventoryList()
-{
 }
 
 void InventoryList::clearItems()
 {
        m_items.clear();
 
-       for(u32 i=0; i<m_size; i++)
-       {
-               m_items.push_back(ItemStack());
+       for (u32 i=0; i < m_size; i++) {
+               m_items.emplace_back();
        }
 
        //setDirty(true);
@@ -478,18 +397,13 @@ void InventoryList::setName(const std::string &name)
 void InventoryList::serialize(std::ostream &os) const
 {
        //os.imbue(std::locale("C"));
-       
+
        os<<"Width "<<m_width<<"\n";
 
-       for(u32 i=0; i<m_items.size(); i++)
-       {
-               const ItemStack &item = m_items[i];
-               if(item.empty())
-               {
+       for (const auto &item : m_items) {
+               if (item.empty()) {
                        os<<"Empty";
-               }
-               else
-               {
+               } else {
                        os<<"Item ";
                        item.serialize(os);
                }
@@ -507,8 +421,7 @@ void InventoryList::deSerialize(std::istream &is)
        u32 item_i = 0;
        m_width = 0;
 
-       for(;;)
-       {
+       while (is.good()) {
                std::string line;
                std::getline(is, line, '\n');
 
@@ -518,17 +431,14 @@ void InventoryList::deSerialize(std::istream &is)
                std::string name;
                std::getline(iss, name, ' ');
 
-               if(name == "EndInventoryList")
-               {
-                       break;
-               }
+               if (name == "EndInventoryList")
+                       return;
+
                // This is a temporary backwards compatibility fix
-               else if(name == "end")
-               {
-                       break;
-               }
-               else if(name == "Width")
-               {
+               if (name == "end")
+                       return;
+
+               if (name == "Width") {
                        iss >> m_width;
                        if (iss.fail())
                                throw SerializationError("incorrect width property");
@@ -548,6 +458,14 @@ void InventoryList::deSerialize(std::istream &is)
                        m_items[item_i++].clear();
                }
        }
+
+       // Contents given to deSerialize() were not terminated properly: throw error.
+
+       std::ostringstream ss;
+       ss << "Malformatted inventory list. list="
+               << m_name << ", read " << item_i << " of " << getSize()
+               << " ItemStacks." << std::endl;
+       throw SerializationError(ss.str());
 }
 
 InventoryList::InventoryList(const InventoryList &other)
@@ -575,14 +493,9 @@ bool InventoryList::operator == (const InventoryList &other) const
                return false;
        if(m_name != other.m_name)
                return false;
-       for(u32 i=0; i<m_items.size(); i++)
-       {
-               ItemStack s1 = m_items[i];
-               ItemStack s2 = other.m_items[i];
-               if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
-                               s1.metadata != s2.metadata)
+       for (u32 i = 0; i < m_items.size(); i++)
+               if (m_items[i] != other.m_items[i])
                        return false;
-       }
 
        return true;
 }
@@ -605,9 +518,8 @@ u32 InventoryList::getWidth() const
 u32 InventoryList::getUsedSlots() const
 {
        u32 num = 0;
-       for(u32 i=0; i<m_items.size(); i++)
-       {
-               if(!m_items[i].empty())
+       for (const auto &m_item : m_items) {
+               if (!m_item.empty())
                        num++;
        }
        return num;
@@ -653,7 +565,7 @@ ItemStack InventoryList::addItem(const ItemStack &newitem_)
 
        if(newitem.empty())
                return newitem;
-       
+
        /*
                First try to find if it could be added to some existing items
        */
@@ -723,23 +635,20 @@ bool InventoryList::roomForItem(const ItemStack &item_) const
        return false;
 }
 
-bool InventoryList::containsItem(const ItemStack &item) const
+bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
 {
        u32 count = item.count;
-       if(count == 0)
+       if (count == 0)
                return true;
-       for(std::vector<ItemStack>::const_reverse_iterator
-                       i = m_items.rbegin();
-                       i != m_items.rend(); i++)
-       {
-               if(count == 0)
+
+       for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
+               if (count == 0)
                        break;
-               if(i->name == item.name)
-               {
-                       if(i->count >= count)
+               if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
+                       if (i->count >= count)
                                return true;
-                       else
-                               count -= i->count;
+
+                       count -= i->count;
                }
        }
        return false;
@@ -748,15 +657,11 @@ bool InventoryList::containsItem(const ItemStack &item) const
 ItemStack InventoryList::removeItem(const ItemStack &item)
 {
        ItemStack removed;
-       for(std::vector<ItemStack>::reverse_iterator
-                       i = m_items.rbegin();
-                       i != m_items.rend(); i++)
-       {
-               if(i->name == item.name)
-               {
+       for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
+               if (i->name == item.name) {
                        u32 still_to_remove = item.count - removed.count;
                        removed.addItem(i->takeItem(still_to_remove), m_itemdef);
-                       if(removed.count == item.count)
+                       if (removed.count == item.count)
                                break;
                }
        }
@@ -774,14 +679,6 @@ ItemStack InventoryList::takeItem(u32 i, u32 takecount)
        return taken;
 }
 
-ItemStack InventoryList::peekItem(u32 i, u32 peekcount) const
-{
-       if(i >= m_items.size())
-               return ItemStack();
-
-       return m_items[i].peekItem(peekcount);
-}
-
 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
 {
        // Take item from source list
@@ -795,7 +692,6 @@ void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
                return;
 
        // Try to add the item to destination list
-       u32 oldcount = item1.count;
        u32 dest_size = dest->getSize();
        // First try all the non-empty slots
        for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
@@ -819,7 +715,7 @@ void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
 }
 
 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
-               u32 count, bool swap_if_needed)
+               u32 count, bool swap_if_needed, bool *did_swap)
 {
        if(this == dest && i == dest_i)
                return count;
@@ -851,6 +747,10 @@ u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
                // If olditem is returned, nothing was added.
                // Swap the items
                if (nothing_added && swap_if_needed) {
+                       // Tell that we swapped
+                       if (did_swap != NULL) {
+                               *did_swap = true;
+                       }
                        // Take item from source list
                        item1 = changeItem(i, ItemStack());
                        // Adding was not possible, swap the items.
@@ -874,9 +774,8 @@ Inventory::~Inventory()
 void Inventory::clear()
 {
        m_dirty = true;
-       for(u32 i=0; i<m_lists.size(); i++)
-       {
-               delete m_lists[i];
+       for (auto &m_list : m_lists) {
+               delete m_list;
        }
        m_lists.clear();
 }
@@ -884,11 +783,8 @@ void Inventory::clear()
 void Inventory::clearContents()
 {
        m_dirty = true;
-       for(u32 i=0; i<m_lists.size(); i++)
-       {
-               InventoryList *list = m_lists[i];
-               for(u32 j=0; j<list->getSize(); j++)
-               {
+       for (InventoryList *list : m_lists) {
+               for (u32 j=0; j<list->getSize(); j++) {
                        list->deleteItem(j);
                }
        }
@@ -914,9 +810,8 @@ Inventory & Inventory::operator = (const Inventory &other)
                m_dirty = true;
                clear();
                m_itemdef = other.m_itemdef;
-               for(u32 i=0; i<other.m_lists.size(); i++)
-               {
-                       m_lists.push_back(new InventoryList(*other.m_lists[i]));
+               for (InventoryList *list : other.m_lists) {
+                       m_lists.push_back(new InventoryList(*list));
                }
        }
        return *this;
@@ -937,9 +832,7 @@ bool Inventory::operator == (const Inventory &other) const
 
 void Inventory::serialize(std::ostream &os) const
 {
-       for(u32 i=0; i<m_lists.size(); i++)
-       {
-               InventoryList *list = m_lists[i];
+       for (InventoryList *list : m_lists) {
                os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
                list->serialize(os);
        }
@@ -951,8 +844,7 @@ void Inventory::deSerialize(std::istream &is)
 {
        clear();
 
-       for(;;)
-       {
+       while (is.good()) {
                std::string line;
                std::getline(is, line, '\n');
 
@@ -961,17 +853,14 @@ void Inventory::deSerialize(std::istream &is)
                std::string name;
                std::getline(iss, name, ' ');
 
-               if(name == "EndInventory")
-               {
-                       break;
-               }
+               if (name == "EndInventory")
+                       return;
+
                // This is a temporary backwards compatibility fix
-               else if(name == "end")
-               {
-                       break;
-               }
-               else if(name == "List")
-               {
+               if (name == "end")
+                       return;
+
+               if (name == "List") {
                        std::string listname;
                        u32 listsize;
 
@@ -988,6 +877,13 @@ void Inventory::deSerialize(std::istream &is)
                        throw SerializationError("invalid inventory specifier: " + name);
                }
        }
+
+       // Contents given to deSerialize() were not terminated properly: throw error.
+
+       std::ostringstream ss;
+       ss << "Malformatted inventory (damaged?). "
+               << m_lists.size() << " lists read." << std::endl;
+       throw SerializationError(ss.str());
 }
 
 InventoryList * Inventory::addList(const std::string &name, u32 size)
@@ -1003,15 +899,14 @@ InventoryList * Inventory::addList(const std::string &name, u32 size)
                }
                return m_lists[i];
        }
-       else
-       {
-               //don't create list with invalid name
-               if (name.find(" ") != std::string::npos) return NULL;
 
-               InventoryList *list = new InventoryList(name, size, m_itemdef);
-               m_lists.push_back(list);
-               return list;
-       }
+
+       //don't create list with invalid name
+       if (name.find(' ') != std::string::npos) return NULL;
+
+       InventoryList *list = new InventoryList(name, size, m_itemdef);
+       m_lists.push_back(list);
+       return list;
 }
 
 InventoryList * Inventory::getList(const std::string &name)
@@ -1025,9 +920,7 @@ InventoryList * Inventory::getList(const std::string &name)
 std::vector<const InventoryList*> Inventory::getLists()
 {
        std::vector<const InventoryList*> lists;
-       for(u32 i=0; i<m_lists.size(); i++)
-       {
-               InventoryList *list = m_lists[i];
+       for (auto list : m_lists) {
                lists.push_back(list);
        }
        return lists;