podman
423 строки · 10.0 Кб
1// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6//
7// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer
8// See THIRD-PARTY-NOTICES for original license terms.
9
10package primitive
11
12import (
13"encoding/json"
14"errors"
15"fmt"
16"math/big"
17"regexp"
18"strconv"
19"strings"
20)
21
22// These constants are the maximum and minimum values for the exponent field in a decimal128 value.
23const (
24MaxDecimal128Exp = 6111
25MinDecimal128Exp = -6176
26)
27
28// These errors are returned when an invalid value is parsed as a big.Int.
29var (
30ErrParseNaN = errors.New("cannot parse NaN as a *big.Int")
31ErrParseInf = errors.New("cannot parse Infinity as a *big.Int")
32ErrParseNegInf = errors.New("cannot parse -Infinity as a *big.Int")
33)
34
35// Decimal128 holds decimal128 BSON values.
36type Decimal128 struct {
37h, l uint64
38}
39
40// NewDecimal128 creates a Decimal128 using the provide high and low uint64s.
41func NewDecimal128(h, l uint64) Decimal128 {
42return Decimal128{h: h, l: l}
43}
44
45// GetBytes returns the underlying bytes of the BSON decimal value as two uint64 values. The first
46// contains the most first 8 bytes of the value and the second contains the latter.
47func (d Decimal128) GetBytes() (uint64, uint64) {
48return d.h, d.l
49}
50
51// String returns a string representation of the decimal value.
52func (d Decimal128) String() string {
53var posSign int // positive sign
54var exp int // exponent
55var high, low uint64 // significand high/low
56
57if d.h>>63&1 == 0 {
58posSign = 1
59}
60
61switch d.h >> 58 & (1<<5 - 1) {
62case 0x1F:
63return "NaN"
64case 0x1E:
65return "-Infinity"[posSign:]
66}
67
68low = d.l
69if d.h>>61&3 == 3 {
70// Bits: 1*sign 2*ignored 14*exponent 111*significand.
71// Implicit 0b100 prefix in significand.
72exp = int(d.h >> 47 & (1<<14 - 1))
73//high = 4<<47 | d.h&(1<<47-1)
74// Spec says all of these values are out of range.
75high, low = 0, 0
76} else {
77// Bits: 1*sign 14*exponent 113*significand
78exp = int(d.h >> 49 & (1<<14 - 1))
79high = d.h & (1<<49 - 1)
80}
81exp += MinDecimal128Exp
82
83// Would be handled by the logic below, but that's trivial and common.
84if high == 0 && low == 0 && exp == 0 {
85return "-0"[posSign:]
86}
87
88var repr [48]byte // Loop 5 times over 9 digits plus dot, negative sign, and leading zero.
89var last = len(repr)
90var i = len(repr)
91var dot = len(repr) + exp
92var rem uint32
93Loop:
94for d9 := 0; d9 < 5; d9++ {
95high, low, rem = divmod(high, low, 1e9)
96for d1 := 0; d1 < 9; d1++ {
97// Handle "-0.0", "0.00123400", "-1.00E-6", "1.050E+3", etc.
98if i < len(repr) && (dot == i || low == 0 && high == 0 && rem > 0 && rem < 10 && (dot < i-6 || exp > 0)) {
99exp += len(repr) - i
100i--
101repr[i] = '.'
102last = i - 1
103dot = len(repr) // Unmark.
104}
105c := '0' + byte(rem%10)
106rem /= 10
107i--
108repr[i] = c
109// Handle "0E+3", "1E+3", etc.
110if low == 0 && high == 0 && rem == 0 && i == len(repr)-1 && (dot < i-5 || exp > 0) {
111last = i
112break Loop
113}
114if c != '0' {
115last = i
116}
117// Break early. Works without it, but why.
118if dot > i && low == 0 && high == 0 && rem == 0 {
119break Loop
120}
121}
122}
123repr[last-1] = '-'
124last--
125
126if exp > 0 {
127return string(repr[last+posSign:]) + "E+" + strconv.Itoa(exp)
128}
129if exp < 0 {
130return string(repr[last+posSign:]) + "E" + strconv.Itoa(exp)
131}
132return string(repr[last+posSign:])
133}
134
135// BigInt returns significand as big.Int and exponent, bi * 10 ^ exp.
136func (d Decimal128) BigInt() (*big.Int, int, error) {
137high, low := d.GetBytes()
138posSign := high>>63&1 == 0 // positive sign
139
140switch high >> 58 & (1<<5 - 1) {
141case 0x1F:
142return nil, 0, ErrParseNaN
143case 0x1E:
144if posSign {
145return nil, 0, ErrParseInf
146}
147return nil, 0, ErrParseNegInf
148}
149
150var exp int
151if high>>61&3 == 3 {
152// Bits: 1*sign 2*ignored 14*exponent 111*significand.
153// Implicit 0b100 prefix in significand.
154exp = int(high >> 47 & (1<<14 - 1))
155//high = 4<<47 | d.h&(1<<47-1)
156// Spec says all of these values are out of range.
157high, low = 0, 0
158} else {
159// Bits: 1*sign 14*exponent 113*significand
160exp = int(high >> 49 & (1<<14 - 1))
161high = high & (1<<49 - 1)
162}
163exp += MinDecimal128Exp
164
165// Would be handled by the logic below, but that's trivial and common.
166if high == 0 && low == 0 && exp == 0 {
167if posSign {
168return new(big.Int), 0, nil
169}
170return new(big.Int), 0, nil
171}
172
173bi := big.NewInt(0)
174const host32bit = ^uint(0)>>32 == 0
175if host32bit {
176bi.SetBits([]big.Word{big.Word(low), big.Word(low >> 32), big.Word(high), big.Word(high >> 32)})
177} else {
178bi.SetBits([]big.Word{big.Word(low), big.Word(high)})
179}
180
181if !posSign {
182return bi.Neg(bi), exp, nil
183}
184return bi, exp, nil
185}
186
187// IsNaN returns whether d is NaN.
188func (d Decimal128) IsNaN() bool {
189return d.h>>58&(1<<5-1) == 0x1F
190}
191
192// IsInf returns:
193//
194// +1 d == Infinity
195// 0 other case
196// -1 d == -Infinity
197func (d Decimal128) IsInf() int {
198if d.h>>58&(1<<5-1) != 0x1E {
199return 0
200}
201
202if d.h>>63&1 == 0 {
203return 1
204}
205return -1
206}
207
208// IsZero returns true if d is the empty Decimal128.
209func (d Decimal128) IsZero() bool {
210return d.h == 0 && d.l == 0
211}
212
213// MarshalJSON returns Decimal128 as a string.
214func (d Decimal128) MarshalJSON() ([]byte, error) {
215return json.Marshal(d.String())
216}
217
218// UnmarshalJSON creates a primitive.Decimal128 from a JSON string, an extended JSON $numberDecimal value, or the string
219// "null". If b is a JSON string or extended JSON value, d will have the value of that string, and if b is "null", d will
220// be unchanged.
221func (d *Decimal128) UnmarshalJSON(b []byte) error {
222// Ignore "null" to keep parity with the standard library. Decoding a JSON null into a non-pointer Decimal128 field
223// will leave the field unchanged. For pointer values, encoding/json will set the pointer to nil and will not
224// enter the UnmarshalJSON hook.
225if string(b) == "null" {
226return nil
227}
228
229var res interface{}
230err := json.Unmarshal(b, &res)
231if err != nil {
232return err
233}
234str, ok := res.(string)
235
236// Extended JSON
237if !ok {
238m, ok := res.(map[string]interface{})
239if !ok {
240return errors.New("not an extended JSON Decimal128: expected document")
241}
242d128, ok := m["$numberDecimal"]
243if !ok {
244return errors.New("not an extended JSON Decimal128: expected key $numberDecimal")
245}
246str, ok = d128.(string)
247if !ok {
248return errors.New("not an extended JSON Decimal128: expected decimal to be string")
249}
250}
251
252*d, err = ParseDecimal128(str)
253return err
254}
255
256func divmod(h, l uint64, div uint32) (qh, ql uint64, rem uint32) {
257div64 := uint64(div)
258a := h >> 32
259aq := a / div64
260ar := a % div64
261b := ar<<32 + h&(1<<32-1)
262bq := b / div64
263br := b % div64
264c := br<<32 + l>>32
265cq := c / div64
266cr := c % div64
267d := cr<<32 + l&(1<<32-1)
268dq := d / div64
269dr := d % div64
270return (aq<<32 | bq), (cq<<32 | dq), uint32(dr)
271}
272
273var dNaN = Decimal128{0x1F << 58, 0}
274var dPosInf = Decimal128{0x1E << 58, 0}
275var dNegInf = Decimal128{0x3E << 58, 0}
276
277func dErr(s string) (Decimal128, error) {
278return dNaN, fmt.Errorf("cannot parse %q as a decimal128", s)
279}
280
281// match scientific notation number, example -10.15e-18
282var normalNumber = regexp.MustCompile(`^(?P<int>[-+]?\d*)?(?:\.(?P<dec>\d*))?(?:[Ee](?P<exp>[-+]?\d+))?$`)
283
284// ParseDecimal128 takes the given string and attempts to parse it into a valid
285// Decimal128 value.
286func ParseDecimal128(s string) (Decimal128, error) {
287if s == "" {
288return dErr(s)
289}
290
291matches := normalNumber.FindStringSubmatch(s)
292if len(matches) == 0 {
293orig := s
294neg := s[0] == '-'
295if neg || s[0] == '+' {
296s = s[1:]
297}
298
299if s == "NaN" || s == "nan" || strings.EqualFold(s, "nan") {
300return dNaN, nil
301}
302if s == "Inf" || s == "inf" || strings.EqualFold(s, "inf") || strings.EqualFold(s, "infinity") {
303if neg {
304return dNegInf, nil
305}
306return dPosInf, nil
307}
308return dErr(orig)
309}
310
311intPart := matches[1]
312decPart := matches[2]
313expPart := matches[3]
314
315var err error
316exp := 0
317if expPart != "" {
318exp, err = strconv.Atoi(expPart)
319if err != nil {
320return dErr(s)
321}
322}
323if decPart != "" {
324exp -= len(decPart)
325}
326
327if len(strings.Trim(intPart+decPart, "-0")) > 35 {
328return dErr(s)
329}
330
331bi, ok := new(big.Int).SetString(intPart+decPart, 10)
332if !ok {
333return dErr(s)
334}
335
336d, ok := ParseDecimal128FromBigInt(bi, exp)
337if !ok {
338return dErr(s)
339}
340
341if bi.Sign() == 0 && s[0] == '-' {
342d.h |= 1 << 63
343}
344
345return d, nil
346}
347
348var (
349ten = big.NewInt(10)
350zero = new(big.Int)
351
352maxS, _ = new(big.Int).SetString("9999999999999999999999999999999999", 10)
353)
354
355// ParseDecimal128FromBigInt attempts to parse the given significand and exponent into a valid Decimal128 value.
356func ParseDecimal128FromBigInt(bi *big.Int, exp int) (Decimal128, bool) {
357//copy
358bi = new(big.Int).Set(bi)
359
360q := new(big.Int)
361r := new(big.Int)
362
363for bigIntCmpAbs(bi, maxS) == 1 {
364bi, _ = q.QuoRem(bi, ten, r)
365if r.Cmp(zero) != 0 {
366return Decimal128{}, false
367}
368exp++
369if exp > MaxDecimal128Exp {
370return Decimal128{}, false
371}
372}
373
374for exp < MinDecimal128Exp {
375// Subnormal.
376bi, _ = q.QuoRem(bi, ten, r)
377if r.Cmp(zero) != 0 {
378return Decimal128{}, false
379}
380exp++
381}
382for exp > MaxDecimal128Exp {
383// Clamped.
384bi.Mul(bi, ten)
385if bigIntCmpAbs(bi, maxS) == 1 {
386return Decimal128{}, false
387}
388exp--
389}
390
391b := bi.Bytes()
392var h, l uint64
393for i := 0; i < len(b); i++ {
394if i < len(b)-8 {
395h = h<<8 | uint64(b[i])
396continue
397}
398l = l<<8 | uint64(b[i])
399}
400
401h |= uint64(exp-MinDecimal128Exp) & uint64(1<<14-1) << 49
402if bi.Sign() == -1 {
403h |= 1 << 63
404}
405
406return Decimal128{h: h, l: l}, true
407}
408
409// bigIntCmpAbs computes big.Int.Cmp(absoluteValue(x), absoluteValue(y)).
410func bigIntCmpAbs(x, y *big.Int) int {
411xAbs := bigIntAbsValue(x)
412yAbs := bigIntAbsValue(y)
413return xAbs.Cmp(yAbs)
414}
415
416// bigIntAbsValue returns a big.Int containing the absolute value of b.
417// If b is already a non-negative number, it is returned without any changes or copies.
418func bigIntAbsValue(b *big.Int) *big.Int {
419if b.Sign() >= 0 {
420return b // already positive
421}
422return new(big.Int).Abs(b)
423}
424