aboutsummaryrefslogtreecommitdiff
path: root/libxsde/xsde/cxx/serializer/non-validating/double.cxx
blob: 43d32ac674ba67e48e00bb3d0b95414b5cccb61b (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// file      : xsde/cxx/serializer/non-validating/double.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#include <stdio.h> // sprintf/snprintf

#include <xsde/cxx/serializer/non-validating/double.hxx>

namespace xsde
{
  namespace cxx
  {
    namespace serializer
    {
      namespace non_validating
      {
        void double_simpl::
        pre (double value)
        {
          value_ = value;
        }

        void double_simpl::
        _serialize_content ()
        {
          // Assume double values cannot be longer than 127 characters.
          //
          char str[128];

          const char* fmt = 0;

          switch (notation_)
          {
          case notation_auto:
            {
              fmt = "%.*g";
              break;
            }
          case notation_fixed:
            {
              fmt = "%.*f";
              break;
            }
          case notation_scientific:
            {
              fmt = "%.*e";
              break;
            }
          }

#ifdef XSDE_SNPRINTF
          int n = snprintf (str, 128, fmt, precision_, value_);
#else
          int n = sprintf (str, fmt, precision_, value_);
#endif
          if (n > 0 && n < 128)
          {
            if (str[0] == '-')
            {
              if (str[1] == 'n' && str[2] == 'a' && str[3] == 'n')
              {
                _characters ("NaN", 3);
                return;
              }
              else if (str[1] == 'i' && str[2] == 'n' && str[3] == 'f')
              {
                _characters ("-INF", 4);
                return;
              }
            }
            else
            {
              if (str[0] == 'n' && str[1] == 'a' && str[2] == 'n')
              {
                _characters ("NaN", 3);
                return;
              }
              else if (str[0] == 'i' && str[1] == 'n' && str[2] == 'f')
              {
                _characters ("INF", 3);
                return;
              }
            }

            if (notation_ == notation_fixed)
            {
              // Remove trailing '0' and '.' if necessary.
              //
              while (str[n - 1] == '0')
                n--;

              if (str[n - 1] == '.')
                n--;
            }

            _characters (str, static_cast<size_t> (n));
          }
        }
      }
    }
  }
}