forked from Concordium/concordium-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amount.go
84 lines (70 loc) · 1.64 KB
/
amount.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
package concordium
import (
"encoding/binary"
"encoding/json"
"fmt"
"strconv"
)
const amountSize = 8
type Amount struct {
microCCD uint64
}
func NewAmountZero() *Amount {
return &Amount{}
}
func NewAmountFromMicroCCD(v int) *Amount {
return &Amount{microCCD: uint64(v)}
}
func NewAmountFromCCD(v float64) *Amount {
return &Amount{microCCD: uint64(v * 1e6)}
}
func (a *Amount) MicroCCD() int {
return int(a.microCCD)
}
func (a *Amount) CCD() float64 {
return float64(a.microCCD) / 1e6
}
func (a *Amount) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(strconv.Itoa(int(a.microCCD)))
if err != nil {
return nil, fmt.Errorf("%T: %w", *a, err)
}
return b, nil
}
func (a *Amount) UnmarshalJSON(b []byte) error {
var str json.Number
err := json.Unmarshal(b, &str)
if err != nil {
return fmt.Errorf("%T: %w", *a, err)
}
num, err := str.Int64()
if err != nil {
return fmt.Errorf("%T: %w", *a, err)
}
a.microCCD = uint64(num)
return nil
}
func (a *Amount) Serialize() ([]byte, error) {
b := make([]byte, amountSize)
binary.BigEndian.PutUint64(b, a.microCCD)
return b, nil
}
func (a *Amount) Deserialize(b []byte) error {
if len(b) < amountSize {
return fmt.Errorf("%T requires %d bytes", *a, amountSize)
}
a.microCCD = binary.BigEndian.Uint64(b)
return nil
}
func (a *Amount) SerializeModel() ([]byte, error) {
b := make([]byte, amountSize)
binary.LittleEndian.PutUint64(b, a.microCCD)
return b, nil
}
func (a *Amount) DeserializeModel(b []byte) (int, error) {
if len(b) < amountSize {
return 0, fmt.Errorf("%T requires %d bytes", *a, amountSize)
}
a.microCCD = binary.LittleEndian.Uint64(b)
return amountSize, nil
}