2
0

Registry.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. VCMI_LIB_NAMESPACE_BEGIN
  13. namespace scripting
  14. {
  15. namespace api
  16. {
  17. Registry::Registry() = default;
  18. Registry * Registry::get()
  19. {
  20. static auto Instance = std::unique_ptr<Registry>(new Registry());
  21. return Instance.get();
  22. }
  23. void Registry::add(const std::string & name, std::shared_ptr<Registar> item)
  24. {
  25. data[name] = std::move(item);
  26. }
  27. void Registry::addCore(const std::string & name, std::shared_ptr<Registar> item)
  28. {
  29. coreData[name] = std::move(item);
  30. }
  31. const Registar * Registry::find(const std::string & name) const
  32. {
  33. auto iter = data.find(name);
  34. if(iter == data.end())
  35. return nullptr;
  36. else
  37. return iter->second.get();
  38. }
  39. TypeRegistry::TypeRegistry()
  40. : nextIndex(0)
  41. {
  42. }
  43. TypeRegistry * TypeRegistry::get()
  44. {
  45. static auto Instance = std::unique_ptr<TypeRegistry>(new TypeRegistry());
  46. return Instance.get();
  47. }
  48. const char * TypeRegistry::getKeyForType(const std::type_info & type)
  49. {
  50. //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
  51. //there is no guarantee that name is unique, but it is at least somewhat human readable, so we append unique number to name
  52. //TODO: name demangle
  53. std::type_index typeIndex(type);
  54. std::unique_lock<std::mutex> lock(mutex);
  55. auto iter = keys.find(typeIndex);
  56. if(iter == std::end(keys))
  57. {
  58. std::string newKey = type.name();
  59. newKey += "_";
  60. newKey += std::to_string(nextIndex++);
  61. keys[typeIndex] = std::move(newKey);
  62. return keys[typeIndex].c_str();
  63. }
  64. else
  65. {
  66. return iter->second.c_str();
  67. }
  68. }
  69. }
  70. }
  71. VCMI_LIB_NAMESPACE_END