Skip to content
This repository has been archived by the owner on Aug 19, 2019. It is now read-only.

Serialize JSON numbers that are essentially ints without a fractional part. #133

Merged
merged 3 commits into from
Apr 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions src/json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@

#include "json.h"

#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <sstream>
#include <utility>

Expand Down Expand Up @@ -120,8 +122,22 @@ std::unique_ptr<Value> Boolean::Clone() const {
return std::unique_ptr<Value>(new Boolean(value_));
}

namespace {
template<class IntType>
constexpr bool IsEffectivelyInteger(long double value) {
return (value == std::floor(value) &&
value >= std::numeric_limits<IntType>::min() &&
value <= std::numeric_limits<IntType>::max() &&
!(value == 0.0 && std::signbit(value)));
}
}

void Number::Serialize(internal::JSONSerializer* serializer) const {
yajl_gen_double(serializer->gen(), value_);
if (IsEffectivelyInteger<long long>(value_)) {
yajl_gen_integer(serializer->gen(), static_cast<long long>(value_));
} else {
yajl_gen_double(serializer->gen(), static_cast<double>(value_));
}
}

std::unique_ptr<Value> Number::Clone() const {
Expand Down Expand Up @@ -339,10 +355,8 @@ int handle_string(void* arg, const unsigned char* val, size_t length) {

int handle_integer(void* arg, long long value) {
JSONBuilder* builder = reinterpret_cast<JSONBuilder*>(arg);
// Careful: converting a long long into a double is lossy.
// I doubt it'll matter in practice, though.
builder->AddValue(
std::unique_ptr<Value>(new Number(static_cast<double>(value))));
std::unique_ptr<Value>(new Number(value)));
return 1;
}

Expand Down
6 changes: 3 additions & 3 deletions src/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -172,20 +172,20 @@ class Boolean : public Value {

class Number : public Value {
public:
Number(double value) : value_(value) {}
Number(long double value) : value_(value) {}
Number(const Number&) = default;

Type type() const override { return NumberType; }

std::unique_ptr<Value> Clone() const override;

double value() const { return value_; }
long double value() const { return value_; }

protected:
void Serialize(internal::JSONSerializer*) const override;

private:
double value_;
long double value_;
};

class String : public Value {
Expand Down
Loading