Registry.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Registry.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "api/Registry.h"
  12. namespace scripting
  13. {
  14. namespace api
  15. {
  16. Registry::Registry() = default;
  17. Registry * Registry::get()
  18. {
  19. static std::unique_ptr<Registry> Instance = std::unique_ptr<Registry>(new Registry());
  20. return Instance.get();
  21. }
  22. void Registry::add(const std::string & name, std::shared_ptr<Registar> item)
  23. {
  24. data[name] = item;
  25. }
  26. void Registry::addCore(const std::string & name, std::shared_ptr<Registar> item)
  27. {
  28. coreData[name] = item;
  29. }
  30. const Registar * Registry::find(const std::string & name) const
  31. {
  32. auto iter = data.find(name);
  33. if(iter == data.end())
  34. return nullptr;
  35. else
  36. return iter->second.get();
  37. }
  38. TypeRegistry::TypeRegistry()
  39. : nextIndex(0)
  40. {
  41. }
  42. TypeRegistry * TypeRegistry::get()
  43. {
  44. static std::unique_ptr<TypeRegistry> Instance = std::unique_ptr<TypeRegistry>(new TypeRegistry());
  45. return Instance.get();
  46. }
  47. const char * TypeRegistry::getKeyForType(const std::type_info & type)
  48. {
  49. //std::type_index is unique and stable (because all bindings are in vcmiLua shared lib), but there is no way to convert it to Lua value
  50. //there is no guarantee that name is unique, but it is at least somewhat human readable, so we append unique number to name
  51. //TODO: name demangle
  52. std::type_index typeIndex(type);
  53. boost::unique_lock<boost::mutex> lock(mutex);
  54. auto iter = keys.find(typeIndex);
  55. if(iter == std::end(keys))
  56. {
  57. std::string newKey = type.name();
  58. newKey += "_";
  59. newKey += std::to_string(nextIndex++);
  60. keys[typeIndex] = std::move(newKey);
  61. return keys[typeIndex].c_str();
  62. }
  63. else
  64. {
  65. return iter->second.c_str();
  66. }
  67. }
  68. }
  69. }