json_direct_vector_binder.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // json_direct_vector_binder.hpp
  3. // json
  4. //
  5. // Created by Sam Jaffe on 4/23/16.
  6. //
  7. #pragma once
  8. namespace json { namespace binder {
  9. template <typename T, typename V>
  10. class direct_binder<T, std::vector<V> > : public binder_impl<T> {
  11. public:
  12. direct_binder(std::vector<V> T::*p, binder<V> const&i);
  13. virtual binder_impl<T>* clone() const override { return new direct_binder(*this); }
  14. virtual void parse(T& val, char const*& data, parser::options opts) const override {
  15. const char ch = json::helper::get_next_element(data);
  16. if (ch != '[') {
  17. throw json::malformed_json_exception("Expected an array type");
  18. }
  19. ++data;
  20. V to_make;
  21. std::vector<V>& vec = val.*ptr;
  22. while (*data && *data != ']') {
  23. impl.parse(to_make, data, opts);
  24. vec.emplace_back(to_make);
  25. json::helper::advance_to_boundary(']', data);
  26. }
  27. if (*data) ++data;
  28. else throw json::unterminated_json_exception("Reached end of parse string without finding array end");
  29. }
  30. virtual void write(T const& val, std::ostream & data) const override {
  31. data << '[';
  32. std::vector<V> const & vec = val.*ptr;
  33. typename std::vector<V>::const_iterator it = vec.begin(), end = vec.end();
  34. if (it != end) {
  35. impl.write(*it, data);
  36. for (++it; it != end; ++it) {
  37. data << ",";
  38. impl.write(*it, data);
  39. }
  40. }
  41. data << ']';
  42. }
  43. private:
  44. std::vector<V> T::*ptr;
  45. binder<V> impl;
  46. };
  47. } }