format_string.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * format_string.cpp - string format node
  3. * Copyright (C) 2017 caryoscelus
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <fmt/format.h>
  19. #include <core/node_info.h>
  20. #include <core/node/node.h>
  21. #include <core/node/property.h>
  22. namespace rainynite::core {
  23. namespace nodes {
  24. static const size_t FORMAT_ARGS = 16;
  25. template <size_t... i>
  26. string format_vector(string format, vector<string> args, std::index_sequence<i...>) {
  27. return fmt::format(format, args[i]...);
  28. }
  29. class FormatString : public Node<string> {
  30. public:
  31. FormatString() {
  32. init(format, string());
  33. init_list<string>(arguments);
  34. }
  35. public:
  36. string get(shared_ptr<Context> ctx) const override {
  37. try {
  38. auto str = get_format()->get(ctx);
  39. auto args = get_arguments()->get(ctx);
  40. if (args.size() > FORMAT_ARGS)
  41. throw std::runtime_error("FormatString: too much arguments");
  42. while (args.size() < FORMAT_ARGS) {
  43. args.emplace_back();
  44. }
  45. return format_vector(str, args, std::make_index_sequence<FORMAT_ARGS>());
  46. } catch (...) {
  47. // TODO: DEBUG
  48. return string();
  49. }
  50. }
  51. private:
  52. NODE_PROPERTY(format, string);
  53. NODE_LIST_PROPERTY(arguments, string);
  54. };
  55. REGISTER_NODE(FormatString);
  56. } // namespace nodes
  57. } // namespace rainynite::core