forked from kaptinlin/jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrat.go
94 lines (78 loc) · 2.1 KB
/
rat.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
package jsonschema
import (
"fmt"
"math/big"
"strings"
"github.com/goccy/go-json"
)
// Rat wraps a big.Rat to enable custom JSON marshaling and unmarshaling.
type Rat struct {
*big.Rat
}
// UnmarshalJSON implements the json.Unmarshaler interface for Rat.
func (r *Rat) UnmarshalJSON(data []byte) error {
var tmp interface{}
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
converted, err := convertToBigRat(tmp)
if err != nil {
return err
}
r.Rat = converted
return nil
}
// MarshalJSON implements the json.Marshaler interface for Rat.
func (r *Rat) MarshalJSON() ([]byte, error) {
formattedValue := FormatRat(r)
if strings.Contains(formattedValue, "/") {
// Output as a JSON string if it still contains a fraction
return json.Marshal(formattedValue)
}
// Output as a JSON number
return []byte(formattedValue), nil
}
// convertToBigRat converts various types to big.Rat.
func convertToBigRat(data interface{}) (*big.Rat, error) {
var str string
switch v := data.(type) {
case float64, float32, int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
str = fmt.Sprint(v)
case string:
str = v
default:
return nil, ErrUnsupportedTypeForRat
}
numRat := new(big.Rat)
if _, ok := numRat.SetString(str); !ok {
return nil, ErrFailedToConvertToRat
}
return numRat, nil
}
// NewRat creates a new Rat instance from a given value.
func NewRat(value interface{}) *Rat {
converted, err := convertToBigRat(value)
if err != nil {
return nil
}
return &Rat{converted}
}
// FormatRat formats a Rat as a string.
func FormatRat(r *Rat) string {
if r == nil {
return "null"
}
// Check if the Rat is an integer
if r.IsInt() {
return r.Num().String() // Output as a plain integer string
}
// Format as a decimal maintaining precision
dec := r.FloatString(10) // You might adjust precision as needed
// Trim unnecessary trailing zeros and decimal point if no fractional part
trimmedDec := strings.TrimRight(dec, "0")
trimmedDec = strings.TrimRight(trimmedDec, ".")
if trimmedDec == "" {
return "0" // correct trimming edge case of "0.0000"
}
return trimmedDec
}