aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/QPDF_Real.cc
blob: af96c9df5a9acf5aa01fbb1202e020f3b28e376d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <qpdf/QPDF_Real.hh>

#include <qpdf/JSON_writer.hh>
#include <qpdf/QUtil.hh>

QPDF_Real::QPDF_Real(std::string const& val) :
    QPDFValue(::ot_real, "real"),
    val(val)
{
}

QPDF_Real::QPDF_Real(double value, int decimal_places, bool trim_trailing_zeroes) :
    QPDFValue(::ot_real, "real"),
    val(QUtil::double_to_string(value, decimal_places, trim_trailing_zeroes))
{
}

std::shared_ptr<QPDFObject>
QPDF_Real::create(std::string const& val)
{
    return do_create(new QPDF_Real(val));
}

std::shared_ptr<QPDFObject>
QPDF_Real::create(double value, int decimal_places, bool trim_trailing_zeroes)
{
    return do_create(new QPDF_Real(value, decimal_places, trim_trailing_zeroes));
}

std::shared_ptr<QPDFObject>
QPDF_Real::copy(bool shallow)
{
    return create(val);
}

std::string
QPDF_Real::unparse()
{
    return this->val;
}

JSON
QPDF_Real::getJSON(int json_version)
{
    // While PDF allows .x or -.x, JSON does not. Rather than converting from string to double and
    // back, just handle this as a special case for JSON.
    std::string result;
    if (this->val.length() == 0) {
        // Can't really happen...
        result = "0";
    } else if (this->val.at(0) == '.') {
        result = "0" + this->val;
    } else if ((this->val.length() >= 2) && (this->val.at(0) == '-') && (this->val.at(1) == '.')) {
        result = "-0." + this->val.substr(2);
    } else {
        result = this->val;
    }
    return JSON::makeNumber(result);
}

void
QPDF_Real::writeJSON(int json_version, JSON::Writer& p)
{
    if (this->val.length() == 0) {
        // Can't really happen...
        p << "0";
    } else if (this->val.at(0) == '.') {
        p << "0" << this->val;
    } else if (this->val.length() >= 2 && this->val.at(0) == '-' && this->val.at(1) == '.') {
        p << "-0." << this->val.substr(2);
    } else {
        p << this->val;
    }
}