/
decimal256.go
364 lines (314 loc) · 8.87 KB
/
decimal256.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package array
import (
"bytes"
"fmt"
"math"
"math/big"
"reflect"
"strings"
"sync/atomic"
"github.com/apache/arrow/go/v15/arrow"
"github.com/apache/arrow/go/v15/arrow/bitutil"
"github.com/apache/arrow/go/v15/arrow/decimal256"
"github.com/apache/arrow/go/v15/arrow/internal/debug"
"github.com/apache/arrow/go/v15/arrow/memory"
"github.com/apache/arrow/go/v15/internal/json"
)
// Decimal256 is a type that represents an immutable sequence of 256-bit decimal values.
type Decimal256 struct {
array
values []decimal256.Num
}
func NewDecimal256Data(data arrow.ArrayData) *Decimal256 {
a := &Decimal256{}
a.refCount = 1
a.setData(data.(*Data))
return a
}
func (a *Decimal256) Value(i int) decimal256.Num { return a.values[i] }
func (a *Decimal256) ValueStr(i int) string {
if a.IsNull(i) {
return NullValueStr
}
return a.GetOneForMarshal(i).(string)
}
func (a *Decimal256) Values() []decimal256.Num { return a.values }
func (a *Decimal256) String() string {
o := new(strings.Builder)
o.WriteString("[")
for i := 0; i < a.Len(); i++ {
if i > 0 {
fmt.Fprintf(o, " ")
}
switch {
case a.IsNull(i):
o.WriteString(NullValueStr)
default:
fmt.Fprintf(o, "%v", a.Value(i))
}
}
o.WriteString("]")
return o.String()
}
func (a *Decimal256) setData(data *Data) {
a.array.setData(data)
vals := data.buffers[1]
if vals != nil {
a.values = arrow.Decimal256Traits.CastFromBytes(vals.Bytes())
beg := a.array.data.offset
end := beg + a.array.data.length
a.values = a.values[beg:end]
}
}
func (a *Decimal256) GetOneForMarshal(i int) interface{} {
if a.IsNull(i) {
return nil
}
typ := a.DataType().(*arrow.Decimal256Type)
f := (&big.Float{}).SetInt(a.Value(i).BigInt())
f.Quo(f, big.NewFloat(math.Pow10(int(typ.Scale))))
return f.Text('g', int(typ.Precision))
}
func (a *Decimal256) MarshalJSON() ([]byte, error) {
vals := make([]interface{}, a.Len())
for i := 0; i < a.Len(); i++ {
vals[i] = a.GetOneForMarshal(i)
}
return json.Marshal(vals)
}
func arrayEqualDecimal256(left, right *Decimal256) bool {
for i := 0; i < left.Len(); i++ {
if left.IsNull(i) {
continue
}
if left.Value(i) != right.Value(i) {
return false
}
}
return true
}
type Decimal256Builder struct {
builder
dtype *arrow.Decimal256Type
data *memory.Buffer
rawData []decimal256.Num
}
func NewDecimal256Builder(mem memory.Allocator, dtype *arrow.Decimal256Type) *Decimal256Builder {
return &Decimal256Builder{
builder: builder{refCount: 1, mem: mem},
dtype: dtype,
}
}
// Release decreases the reference count by 1.
// When the reference count goes to zero, the memory is freed.
func (b *Decimal256Builder) Release() {
debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")
if atomic.AddInt64(&b.refCount, -1) == 0 {
if b.nullBitmap != nil {
b.nullBitmap.Release()
b.nullBitmap = nil
}
if b.data != nil {
b.data.Release()
b.data = nil
b.rawData = nil
}
}
}
func (b *Decimal256Builder) Append(v decimal256.Num) {
b.Reserve(1)
b.UnsafeAppend(v)
}
func (b *Decimal256Builder) UnsafeAppend(v decimal256.Num) {
bitutil.SetBit(b.nullBitmap.Bytes(), b.length)
b.rawData[b.length] = v
b.length++
}
func (b *Decimal256Builder) AppendNull() {
b.Reserve(1)
b.UnsafeAppendBoolToBitmap(false)
}
func (b *Decimal256Builder) AppendNulls(n int) {
for i := 0; i < n; i++ {
b.AppendNull()
}
}
func (b *Decimal256Builder) AppendEmptyValue() {
b.Append(decimal256.Num{})
}
func (b *Decimal256Builder) AppendEmptyValues(n int) {
for i := 0; i < n; i++ {
b.AppendEmptyValue()
}
}
func (b *Decimal256Builder) Type() arrow.DataType { return b.dtype }
func (b *Decimal256Builder) UnsafeAppendBoolToBitmap(isValid bool) {
if isValid {
bitutil.SetBit(b.nullBitmap.Bytes(), b.length)
} else {
b.nulls++
}
b.length++
}
// AppendValues will append the values in the v slice. The valid slice determines which values
// in v are valid (not null). The valid slice must either be empty or be equal in length to v. If empty,
// all values in v are appended and considered valid.
func (b *Decimal256Builder) AppendValues(v []decimal256.Num, valid []bool) {
if len(v) != len(valid) && len(valid) != 0 {
panic("arrow/array: len(v) != len(valid) && len(valid) != 0")
}
if len(v) == 0 {
return
}
b.Reserve(len(v))
if len(v) > 0 {
arrow.Decimal256Traits.Copy(b.rawData[b.length:], v)
}
b.builder.unsafeAppendBoolsToBitmap(valid, len(v))
}
func (b *Decimal256Builder) init(capacity int) {
b.builder.init(capacity)
b.data = memory.NewResizableBuffer(b.mem)
bytesN := arrow.Decimal256Traits.BytesRequired(capacity)
b.data.Resize(bytesN)
b.rawData = arrow.Decimal256Traits.CastFromBytes(b.data.Bytes())
}
// Reserve ensures there is enough space for appending n elements
// by checking the capacity and calling Resize if necessary.
func (b *Decimal256Builder) Reserve(n int) {
b.builder.reserve(n, b.Resize)
}
// Resize adjusts the space allocated by b to n elements. If n is greater than b.Cap(),
// additional memory will be allocated. If n is smaller, the allocated memory may reduced.
func (b *Decimal256Builder) Resize(n int) {
nBuilder := n
if n < minBuilderCapacity {
n = minBuilderCapacity
}
if b.capacity == 0 {
b.init(n)
} else {
b.builder.resize(nBuilder, b.init)
b.data.Resize(arrow.Decimal256Traits.BytesRequired(n))
b.rawData = arrow.Decimal256Traits.CastFromBytes(b.data.Bytes())
}
}
// NewArray creates a Decimal256 array from the memory buffers used by the builder and resets the Decimal256Builder
// so it can be used to build a new array.
func (b *Decimal256Builder) NewArray() arrow.Array {
return b.NewDecimal256Array()
}
// NewDecimal256Array creates a Decimal256 array from the memory buffers used by the builder and resets the Decimal256Builder
// so it can be used to build a new array.
func (b *Decimal256Builder) NewDecimal256Array() (a *Decimal256) {
data := b.newData()
a = NewDecimal256Data(data)
data.Release()
return
}
func (b *Decimal256Builder) newData() (data *Data) {
bytesRequired := arrow.Decimal256Traits.BytesRequired(b.length)
if bytesRequired > 0 && bytesRequired < b.data.Len() {
// trim buffers
b.data.Resize(bytesRequired)
}
data = NewData(b.dtype, b.length, []*memory.Buffer{b.nullBitmap, b.data}, nil, b.nulls, 0)
b.reset()
if b.data != nil {
b.data.Release()
b.data = nil
b.rawData = nil
}
return
}
func (b *Decimal256Builder) AppendValueFromString(s string) error {
if s == NullValueStr {
b.AppendNull()
return nil
}
val, err := decimal256.FromString(s, b.dtype.Precision, b.dtype.Scale)
if err != nil {
b.AppendNull()
return err
}
b.Append(val)
return nil
}
func (b *Decimal256Builder) UnmarshalOne(dec *json.Decoder) error {
t, err := dec.Token()
if err != nil {
return err
}
switch v := t.(type) {
case float64:
val, err := decimal256.FromFloat64(v, b.dtype.Precision, b.dtype.Scale)
if err != nil {
return err
}
b.Append(val)
case string:
out, err := decimal256.FromString(v, b.dtype.Precision, b.dtype.Scale)
if err != nil {
return err
}
b.Append(out)
case json.Number:
out, err := decimal256.FromString(v.String(), b.dtype.Precision, b.dtype.Scale)
if err != nil {
return err
}
b.Append(out)
case nil:
b.AppendNull()
return nil
default:
return &json.UnmarshalTypeError{
Value: fmt.Sprint(t),
Type: reflect.TypeOf(decimal256.Num{}),
Offset: dec.InputOffset(),
}
}
return nil
}
func (b *Decimal256Builder) Unmarshal(dec *json.Decoder) error {
for dec.More() {
if err := b.UnmarshalOne(dec); err != nil {
return err
}
}
return nil
}
// UnmarshalJSON will add the unmarshalled values to this builder.
//
// If the values are strings, they will get parsed with big.ParseFloat using
// a rounding mode of big.ToNearestAway currently.
func (b *Decimal256Builder) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
t, err := dec.Token()
if err != nil {
return err
}
if delim, ok := t.(json.Delim); !ok || delim != '[' {
return fmt.Errorf("arrow/array: decimal256 builder must unpack from json array, found %s", delim)
}
return b.Unmarshal(dec)
}
var (
_ arrow.Array = (*Decimal256)(nil)
_ Builder = (*Decimal256Builder)(nil)
)