|
|
@@ -0,0 +1,71 @@
|
|
|
+//
|
|
|
+// json_binder_custom.t.h
|
|
|
+// json
|
|
|
+//
|
|
|
+// Created by Sam Jaffe on 9/12/17.
|
|
|
+//
|
|
|
+
|
|
|
+#pragma once
|
|
|
+
|
|
|
+#include <cxxtest/TestSuite.h>
|
|
|
+#include "json_binder.hpp"
|
|
|
+
|
|
|
+#include <iomanip>
|
|
|
+
|
|
|
+using namespace json::binder;
|
|
|
+using namespace json::parser;
|
|
|
+
|
|
|
+class precision_binder : public binder_impl<double> {
|
|
|
+public:
|
|
|
+ precision_binder(int d) : digits(d), trunc(std::pow(10, d)) {}
|
|
|
+ virtual ~precision_binder() = default;
|
|
|
+
|
|
|
+ binder_impl<double> * clone() const override {
|
|
|
+ return new precision_binder{*this};
|
|
|
+ }
|
|
|
+
|
|
|
+ void parse(double & value, char const * & str, options) const override {
|
|
|
+ std::sscanf(str, "%lf", &value);
|
|
|
+ value = static_cast<long long>(value * trunc) / trunc;
|
|
|
+ json::parse_discard_token(str); // Advance to the boundary
|
|
|
+ }
|
|
|
+
|
|
|
+ void write(double const & value, std::ostream & out) const override {
|
|
|
+ out << std::fixed << std::setprecision(digits) << value;
|
|
|
+ }
|
|
|
+private:
|
|
|
+ int digits;
|
|
|
+ double trunc;
|
|
|
+};
|
|
|
+
|
|
|
+class json_binder_custom_TestSuite : public CxxTest::TestSuite {
|
|
|
+public:
|
|
|
+ struct TestObject {
|
|
|
+ double A; // four_digits
|
|
|
+ double B; // two_digits
|
|
|
+ double C;
|
|
|
+ bool operator==(TestObject const & other) const {
|
|
|
+ return A == other.A && B == other.B && C == other.C;
|
|
|
+ }
|
|
|
+ };
|
|
|
+
|
|
|
+ static object_binder<TestObject> GetImpl() {
|
|
|
+ return object_binder<TestObject>()
|
|
|
+ ("A", &TestObject::A, precision_binder(4))
|
|
|
+ ("B", &TestObject::B, precision_binder(2))
|
|
|
+ ("C", &TestObject::C);
|
|
|
+ }
|
|
|
+
|
|
|
+ static object_binder<TestObject> & Get() {
|
|
|
+ static object_binder<TestObject> val = GetImpl();
|
|
|
+ return val;
|
|
|
+ }
|
|
|
+
|
|
|
+ void test_() {
|
|
|
+ char data[] = "{\"A\":1.00008, \"B\":1.0, \"C\":1.523211102}";
|
|
|
+ TestObject out{0.0, 0.0, 0.0};
|
|
|
+ TestObject const expected{1.0, 1.0, 1.523211102};
|
|
|
+ TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data));
|
|
|
+ TS_ASSERT_EQUALS(out, expected);
|
|
|
+ }
|
|
|
+};
|