hermez-node/common/float16.go
common/float16.goRaw
1// Package common Float16 provides methods to work with Hermez custom half float
2// precision, 16 bits, codification internally called Float16 has been adopted
3// to encode large integers. This is done in order to save bits when L2
4// transactions are published.
5//nolint:gomnd
6package common
7
8import (
9 "encoding/binary"
10 "errors"
11 "math/big"
12)
13
14var (
15 // ErrRoundingLoss is used when converted big.Int to Float16 causes rounding loss
16 ErrRoundingLoss = errors.New("input value causes rounding loss")
17)
18
19// Float16 represents a float in a 16 bit format
20type Float16 uint16
21
22// Bytes return a byte array of length 2 with the Float16 value encoded in BigEndian
23func (f16 Float16) Bytes() []byte {
24 var b [2]byte
25 binary.BigEndian.PutUint16(b[:], uint16(f16))
26 return b[:]
27}
28
29// Float16FromBytes returns a Float16 from a byte array of 2 bytes.
30func Float16FromBytes(b []byte) *Float16 {
31 f16 := Float16(binary.BigEndian.Uint16(b[:2]))
32 return &f16
33}
34
35// BigInt converts the Float16 to a *big.Int integer
36func (f16 *Float16) BigInt() *big.Int {
37 fl := int64(*f16)
38
39 m := big.NewInt(fl & 0x3FF)
40 e := big.NewInt(fl >> 11)
41 e5 := (fl >> 10) & 0x01
42
43 exp := big.NewInt(0).Exp(big.NewInt(10), e, nil)
44 res := m.Mul(m, exp)
45
46 if e5 != 0 && e.Cmp(big.NewInt(0)) != 0 {
47 res.Add(res, exp.Div(exp, big.NewInt(2)))
48 }
49 return res
50}
51
52// floorFix2Float converts a fix to a float, always rounding down
53func floorFix2Float(_f *big.Int) Float16 {
54 zero := big.NewInt(0)
55 ten := big.NewInt(10)
56 e := int64(0)
57
58 m := big.NewInt(0)
59 m.Set(_f)
60
61 if m.Cmp(zero) == 0 {
62 return 0
63 }
64
65 s := big.NewInt(0).Rsh(m, 10)
66
67 for s.Cmp(zero) != 0 {
68 m.Div(m, ten)
69 s.Rsh(m, 10)
70 e++
71 }
72
73 return Float16(m.Int64() | e<<11)
74}
75
76// NewFloat16 encodes a *big.Int integer as a Float16, returning error in
77// case of loss during the encoding.
78func NewFloat16(f *big.Int) (Float16, error) {
79 fl1 := floorFix2Float(f)
80 fi1 := fl1.BigInt()
81 fl2 := fl1 | 0x400
82 fi2 := fl2.BigInt()
83
84 m3 := (fl1 & 0x3FF) + 1
85 e3 := fl1 >> 11
86
87 if m3&0x400 == 0 {
88 m3 = 0x66
89 e3++
90 }
91
92 fl3 := m3 + e3<<11
93 fi3 := fl3.BigInt()
94
95 res := fl1
96
97 d := big.NewInt(0).Abs(fi1.Sub(fi1, f))
98 d2 := big.NewInt(0).Abs(fi2.Sub(fi2, f))
99
100 if d.Cmp(d2) == 1 {
101 res = fl2
102 d = d2
103 }
104
105 d3 := big.NewInt(0).Abs(fi3.Sub(fi3, f))
106
107 if d.Cmp(d3) == 1 {
108 res = fl3
109 }
110
111 // Do rounding check
112 if res.BigInt().Cmp(f) == 0 {
113 return res, nil
114 }
115 return res, ErrRoundingLoss
116}
117
118// NewFloat16Floor encodes a big.Int integer as a Float16, rounding down in
119// case of loss during the encoding.
120func NewFloat16Floor(f *big.Int) Float16 {
121 fl1 := floorFix2Float(f)
122 fl2 := fl1 | 0x400
123 fi2 := fl2.BigInt()
124
125 if fi2.Cmp(f) < 1 {
126 return fl2
127 }
128 return fl1
129}