💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

  1. /*
  2. * Copyright (C) 2023 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef ANTKEEPER_GAME_SETTINGS_HPP
  20. #define ANTKEEPER_GAME_SETTINGS_HPP
  21. #include "game/context.hpp"
  22. #include "debug/log.hpp"
  23. namespace game {
  24. /**
  25. * Reads a setting if found, inserts a setting if not found, and overwrites a setting if a type mismatch occurs.
  26. *
  27. * @tparam T Setting value type.
  28. *
  29. * @param[in] ctx Game context.
  30. * @param[in] key Setting key.
  31. * @param[in,out] Setting value.
  32. *
  33. * @return `true` if the setting was read, `false` if the setting was written.
  34. */
  35. template <class T>
  36. bool read_or_write_setting(game::context& ctx, std::uint32_t key, T& value)
  37. {
  38. if (auto i = ctx.settings->find(key); i != ctx.settings->end())
  39. {
  40. try
  41. {
  42. value = std::any_cast<T>(i->second);
  43. }
  44. catch (const std::bad_any_cast& e)
  45. {
  46. debug::log::error("Setting type mismatch ({:x}={})", key, value);
  47. i->second = value;
  48. return false;
  49. }
  50. }
  51. else
  52. {
  53. debug::log::trace("Setting key not found ({:x}={})", key, value);
  54. (*ctx.settings)[key] = value;
  55. return false;
  56. }
  57. return true;
  58. }
  59. } // namespace game
  60. #endif // ANTKEEPER_GAME_SETTINGS_HPP