nameidmapping.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include <string>
  18. #include <iostream>
  19. #include <unordered_map>
  20. #include <cassert>
  21. #include "irrlichttypes_bloated.h"
  22. typedef std::unordered_map<u16, std::string> IdToNameMap;
  23. typedef std::unordered_map<std::string, u16> NameToIdMap;
  24. class NameIdMapping
  25. {
  26. public:
  27. void serialize(std::ostream &os) const;
  28. void deSerialize(std::istream &is);
  29. void clear()
  30. {
  31. m_id_to_name.clear();
  32. m_name_to_id.clear();
  33. }
  34. void set(u16 id, const std::string &name)
  35. {
  36. assert(!name.empty());
  37. m_id_to_name[id] = name;
  38. m_name_to_id[name] = id;
  39. }
  40. void removeId(u16 id)
  41. {
  42. std::string name;
  43. bool found = getName(id, name);
  44. if (!found)
  45. return;
  46. m_id_to_name.erase(id);
  47. m_name_to_id.erase(name);
  48. }
  49. void eraseName(const std::string &name)
  50. {
  51. u16 id;
  52. bool found = getId(name, id);
  53. if (!found)
  54. return;
  55. m_id_to_name.erase(id);
  56. m_name_to_id.erase(name);
  57. }
  58. bool getName(u16 id, std::string &result) const
  59. {
  60. auto i = m_id_to_name.find(id);
  61. if (i == m_id_to_name.end())
  62. return false;
  63. result = i->second;
  64. return true;
  65. }
  66. bool getId(const std::string &name, u16 &result) const
  67. {
  68. auto i = m_name_to_id.find(name);
  69. if (i == m_name_to_id.end())
  70. return false;
  71. result = i->second;
  72. return true;
  73. }
  74. u16 size() const { return m_id_to_name.size(); }
  75. private:
  76. IdToNameMap m_id_to_name;
  77. NameToIdMap m_name_to_id;
  78. };