forked from woodsbury/decimal128
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
104 lines (89 loc) · 1.89 KB
/
json.go
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
104
package decimal128
import (
"encoding/json"
"reflect"
)
// MarshalJSON implements the [encoding/json.Marshaler] interface.
func (d Decimal) MarshalJSON() ([]byte, error) {
if d.isSpecial() {
return nil, &json.UnsupportedValueError{
Value: reflect.ValueOf(d),
Str: d.String(),
}
}
var digs digits
d.digits(&digs)
prec := 0
if digs.ndig != 0 {
prec = digs.ndig - 1
}
exp := digs.exp + prec
if exp < -6 || exp >= 20 {
return digs.fmtE(nil, prec, 0, false, false, false, false, false, false, 'e'), nil
}
prec = 0
if digs.exp < 0 {
prec = -digs.exp
}
return digs.fmtF(nil, prec, 0, false, false, false, false, false), nil
}
// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface.
func (d *Decimal) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
l := len(data)
if l == 0 {
return nil
}
neg := false
i := 0
if data[0] == '+' {
i = 1
} else if data[0] == '-' {
neg = true
i = 1
}
tmp, err := parseNumber(data[i:], neg, false)
if err != nil {
switch err := err.(type) {
case parseNumberRangeError:
return &json.UnmarshalTypeError{
Value: "number " + string(data),
Type: reflect.TypeOf(Decimal{}),
}
case parseNumberSyntaxError:
switch data[0] {
case '[':
return &json.UnmarshalTypeError{
Value: "array",
Type: reflect.TypeOf(Decimal{}),
}
case '{':
return &json.UnmarshalTypeError{
Value: "object",
Type: reflect.TypeOf(Decimal{}),
}
case 'f', 't':
return &json.UnmarshalTypeError{
Value: "bool",
Type: reflect.TypeOf(Decimal{}),
}
case '"':
return &json.UnmarshalTypeError{
Value: "string",
Type: reflect.TypeOf(Decimal{}),
}
default:
return &json.UnmarshalTypeError{
Value: "number " + string(data),
Type: reflect.TypeOf(Decimal{}),
}
}
default:
return err
}
}
*d = tmp
return nil
}