| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- //
- // json_binder.h
- // json
- //
- // Created by Sam Jaffe on 1/31/16.
- // Copyright © 2016 Sam Jaffe. All rights reserved.
- //
- #ifndef json_binder_h
- #define json_binder_h
- #pragma once
- #include "json_common.hpp"
- #include <map>
- #include <string>
- #include <sstream>
- #include <vector>
- namespace json {
- namespace binder {
- template <typename T>
- class binder_impl {
- public:
- virtual binder_impl<T>* clone() const = 0;
- virtual ~binder_impl() {}
- virtual void parse(T&, char const*&) const = 0;
- virtual void write(T const&, std::ostream &) const = 0;
- };
-
- template <typename T>
- class binder {
- public:
- binder() :
- impl(nullptr) {
- }
-
- binder(binder const& other) :
- impl(other.impl->clone()) {
- }
-
- explicit binder(binder_impl<T> const* p) :
- impl(p) {
- }
-
- explicit binder(binder_impl<T> const& r) :
- impl(r.clone()) {
- }
-
- ~binder() {
- if (impl) {
- delete impl;
- impl = nullptr;
- }
- }
-
- void parse(T& object, char const*& data) const {
- if (!impl) return;
- impl->parse(object, data);
- }
-
- void write(T const& object, std::ostream & data) const {
- if (!impl) return;
- impl->write(object, data);
- }
- private:
- binder_impl<T> const* impl;
- };
-
- template <typename T, typename S = T>
- class visitor {
- public:
- visitor(S& o, binder_impl<T>& b) : obj(o), b(b) {}
-
- void parse(char const* data) {
- b.parse(obj, data);
- }
-
- void write(std::ostream & data) const {
- b.write(obj, data);
- }
-
- private:
- S& obj;
- binder_impl<T>& b;
- };
-
- template <typename T>
- visitor<T> bind(T& object, binder_impl<T>& b) {
- return visitor<T>{object, b};
- }
- }
-
- namespace parser {
- template <typename T>
- void parse(binder::visitor<T>& visitor, char const* data) {
- visitor.parse(data);
- }
-
- template <typename T, typename S>
- void write(binder::visitor<T, S> const & visitor, std::ostream & out) {
- visitor.write(out);
- }
-
- template <typename T, typename S>
- void write(binder::visitor<T, S> const & visitor, std::string & data) {
- std::stringstream ss;
- visitor.write(ss);
- data = ss.str();
- }
- }
- }
- #include "json/json_binder_parser.hpp"
- #include "json/json_direct_binder.hpp"
- #include "json/json_tuple_binder.hpp"
- #include "json/json_object_binder.hpp"
- #include "json/json_direct_map_binder.hpp"
- #include "json/json_direct_scalar_binder.hpp"
- #include "json/json_direct_vector_binder.hpp"
- #endif /* json_binder_h */
|