json_binder.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. //
  2. // json_binder.h
  3. // json
  4. //
  5. // Created by Sam Jaffe on 1/31/16.
  6. // Copyright © 2016 Sam Jaffe. All rights reserved.
  7. //
  8. #ifndef json_binder_h
  9. #define json_binder_h
  10. #pragma once
  11. #include "json_common.h"
  12. #include <map>
  13. #include <string>
  14. #include <vector>
  15. namespace json {
  16. namespace binder {
  17. template <typename T>
  18. class binder_impl {
  19. public:
  20. virtual binder_impl<T>* clone() const = 0;
  21. virtual ~binder_impl() {}
  22. virtual void parse(T&, char const*&) const = 0;
  23. virtual void write(T const&, std::string &) const = 0;
  24. };
  25. template <typename T>
  26. class binder {
  27. public:
  28. binder() :
  29. impl(nullptr) {
  30. }
  31. binder(binder const& other) :
  32. impl(other.impl->clone()) {
  33. }
  34. binder(binder_impl<T> const* p) :
  35. impl(p) {
  36. }
  37. binder(binder_impl<T> const& r) :
  38. impl(r.clone()) {
  39. }
  40. ~binder() {
  41. if (impl) {
  42. delete impl;
  43. impl = nullptr;
  44. }
  45. }
  46. void parse(T& object, char const*& data) const {
  47. if (!impl) return;
  48. impl->parse(object, data);
  49. }
  50. void write(T const& object, std::string & data) const {
  51. if (!impl) return;
  52. impl->write(object, data);
  53. }
  54. private:
  55. binder_impl<T> const* impl;
  56. };
  57. template <typename T, typename S = T>
  58. class visitor {
  59. public:
  60. visitor(S& o, binder_impl<T>& b) : obj(o), b(b) {}
  61. void parse(char const* data) {
  62. b.parse(obj, data);
  63. }
  64. void write(std::string & data) const {
  65. b.write(obj, data);
  66. }
  67. private:
  68. S& obj;
  69. binder_impl<T>& b;
  70. };
  71. template <typename T>
  72. visitor<T> bind(T& object, binder_impl<T>& b) {
  73. return visitor<T>{object, b};
  74. }
  75. }
  76. namespace parser {
  77. template <typename T>
  78. void parse(binder::visitor<T>& visitor, char const* data) {
  79. visitor.parse(data);
  80. }
  81. template <typename T, typename S>
  82. void write(binder::visitor<T, S> const & visitor, std::string & data) {
  83. visitor.write(data);
  84. }
  85. }
  86. }
  87. #include "json/json_direct_binder.hpp"
  88. #include "json/json_tuple_binder.hpp"
  89. #include "json/json_object_binder.hpp"
  90. #include "json/json_direct_map_binder.hpp"
  91. #include "json/json_direct_scalar_binder.hpp"
  92. #include "json/json_direct_vector_binder.hpp"
  93. #endif /* json_binder_h */