Upgrade PaesslerAG/gval dep
This commit is contained in:
@@ -10,7 +10,7 @@ require (
|
||||
github.com/766b/chi-prometheus v0.0.0-20211217152057-87afa9aa2ca8
|
||||
github.com/99designs/basicauth-go v0.0.0-20160802081356-2a93ba0f464d
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible
|
||||
github.com/PaesslerAG/gval v1.1.2
|
||||
github.com/PaesslerAG/gval v1.2.1
|
||||
github.com/SentimensRG/ctx v0.0.0-20180729130232-0bfd988c655d
|
||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
|
||||
github.com/brianvoe/gofakeit/v6 v6.16.0
|
||||
@@ -119,6 +119,7 @@ require (
|
||||
github.com/prometheus/procfs v0.7.3 // indirect
|
||||
github.com/russellhaering/goxmldsig v1.1.1 // indirect
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect
|
||||
github.com/shopspring/decimal v1.3.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stretchr/objx v0.2.0 // indirect
|
||||
github.com/tidwall/btree v1.3.1 // indirect
|
||||
|
||||
@@ -67,6 +67,8 @@ github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAE
|
||||
github.com/PaesslerAG/gval v1.0.0/go.mod h1:y/nm5yEyTeX6av0OfKJNp9rBNj2XrGhAf5+v24IBN1I=
|
||||
github.com/PaesslerAG/gval v1.1.2 h1:EROKxV4/fAKWb0Qoj7NOxmHZA7gcpjOV9XgiRZMRCUU=
|
||||
github.com/PaesslerAG/gval v1.1.2/go.mod h1:Fa8gfkCmUsELXgayr8sfL/sw+VzCVoa03dcOcR/if2w=
|
||||
github.com/PaesslerAG/gval v1.2.1 h1:Ggwtej1xCyt1994VuDCSjycybIDo3duDCDghK/xc/A0=
|
||||
github.com/PaesslerAG/gval v1.2.1/go.mod h1:XRFLwvmkTEdYziLdaCeCa5ImcGVrfQbeNUbVR+C6xac=
|
||||
github.com/PaesslerAG/jsonpath v0.1.0/go.mod h1:4BzmtoM/PI8fPO4aQGIusjGxGir2BzcV0grWtFzq1Y8=
|
||||
github.com/PaesslerAG/jsonpath v0.1.1 h1:c1/AToHQMVsduPAa4Vh6xp2U0evy4t8SWp8imEsylIk=
|
||||
github.com/PaesslerAG/jsonpath v0.1.1/go.mod h1:lVboNxFGal/VwW6d9JzIy56bUsYAP6tH/x80vjnCseY=
|
||||
@@ -498,6 +500,8 @@ github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZ
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
|
||||
github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo=
|
||||
|
||||
+13
-1
@@ -14,6 +14,11 @@ func toFunc(f interface{}) function {
|
||||
var v interface{}
|
||||
errCh := make(chan error)
|
||||
go func() {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
errCh <- fmt.Errorf("%v", recovered)
|
||||
}
|
||||
}()
|
||||
result, err := f(arguments...)
|
||||
v = result
|
||||
errCh <- err
|
||||
@@ -37,6 +42,11 @@ func toFunc(f interface{}) function {
|
||||
var v interface{}
|
||||
errCh := make(chan error)
|
||||
go func() {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
errCh <- fmt.Errorf("%v", recovered)
|
||||
}
|
||||
}()
|
||||
in, err := createCallArguments(ctx, t, args)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
@@ -104,7 +114,9 @@ func createCallArguments(ctx context.Context, t reflect.Type, args []interface{}
|
||||
inType = t.In(numIn - 1).Elem()
|
||||
}
|
||||
argVal := reflect.ValueOf(arg)
|
||||
if arg == nil || !argVal.Type().AssignableTo(inType) {
|
||||
if arg == nil {
|
||||
argVal = reflect.ValueOf(reflect.Interface)
|
||||
} else if !argVal.Type().AssignableTo(inType) {
|
||||
return nil, fmt.Errorf("expected type %s for parameter %d but got %T",
|
||||
inType.String(), i, arg)
|
||||
}
|
||||
|
||||
+42
-1
@@ -1,7 +1,7 @@
|
||||
// Package gval provides a generic expression language.
|
||||
// All functions, infix and prefix operators can be replaced by composing languages into a new one.
|
||||
//
|
||||
// The package contains concrete expression languages for common application in text, arithmetic, propositional logic and so on.
|
||||
// The package contains concrete expression languages for common application in text, arithmetic, decimal arithmetic, propositional logic and so on.
|
||||
// They can be used as basis for a custom expression language or to evaluate expressions directly.
|
||||
package gval
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"reflect"
|
||||
"text/scanner"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
//Evaluate given parameter with given expression in gval full language
|
||||
@@ -51,6 +53,17 @@ func Arithmetic() Language {
|
||||
return arithmetic
|
||||
}
|
||||
|
||||
// DecimalArithmetic contains base, plus(+), minus(-), divide(/), power(**), negative(-)
|
||||
// and numerical order (<=,<,>,>=)
|
||||
//
|
||||
// DecimalArithmetic operators expect decimal.Decimal operands (github.com/shopspring/decimal)
|
||||
// and are used to calculate money/decimal rather than floating point calculations.
|
||||
// Called with unfitting input, they try to convert the input to decimal.Decimal.
|
||||
// They can parse strings and convert any type of int or float.
|
||||
func DecimalArithmetic() Language {
|
||||
return decimalArithmetic
|
||||
}
|
||||
|
||||
// Bitmask contains base, bitwise and(&), bitwise or(|) and bitwise not(^).
|
||||
//
|
||||
// Bitmask operators expect float64 operands.
|
||||
@@ -172,6 +185,34 @@ var arithmetic = NewLanguage(
|
||||
base,
|
||||
)
|
||||
|
||||
var decimalArithmetic = NewLanguage(
|
||||
InfixDecimalOperator("+", func(a, b decimal.Decimal) (interface{}, error) { return a.Add(b), nil }),
|
||||
InfixDecimalOperator("-", func(a, b decimal.Decimal) (interface{}, error) { return a.Sub(b), nil }),
|
||||
InfixDecimalOperator("*", func(a, b decimal.Decimal) (interface{}, error) { return a.Mul(b), nil }),
|
||||
InfixDecimalOperator("/", func(a, b decimal.Decimal) (interface{}, error) { return a.Div(b), nil }),
|
||||
InfixDecimalOperator("%", func(a, b decimal.Decimal) (interface{}, error) { return a.Mod(b), nil }),
|
||||
InfixDecimalOperator("**", func(a, b decimal.Decimal) (interface{}, error) { return a.Pow(b), nil }),
|
||||
|
||||
InfixDecimalOperator(">", func(a, b decimal.Decimal) (interface{}, error) { return a.GreaterThan(b), nil }),
|
||||
InfixDecimalOperator(">=", func(a, b decimal.Decimal) (interface{}, error) { return a.GreaterThanOrEqual(b), nil }),
|
||||
InfixDecimalOperator("<", func(a, b decimal.Decimal) (interface{}, error) { return a.LessThan(b), nil }),
|
||||
InfixDecimalOperator("<=", func(a, b decimal.Decimal) (interface{}, error) { return a.LessThanOrEqual(b), nil }),
|
||||
|
||||
InfixDecimalOperator("==", func(a, b decimal.Decimal) (interface{}, error) { return a.Equal(b), nil }),
|
||||
InfixDecimalOperator("!=", func(a, b decimal.Decimal) (interface{}, error) { return !a.Equal(b), nil }),
|
||||
base,
|
||||
//Base is before these overrides so that the Base options are overridden
|
||||
PrefixExtension(scanner.Int, parseDecimal),
|
||||
PrefixExtension(scanner.Float, parseDecimal),
|
||||
PrefixOperator("-", func(c context.Context, v interface{}) (interface{}, error) {
|
||||
i, ok := convertToFloat(v)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected %v(%T) expected number", v, v)
|
||||
}
|
||||
return decimal.NewFromFloat(i).Neg(), nil
|
||||
}),
|
||||
)
|
||||
|
||||
var bitmask = NewLanguage(
|
||||
InfixNumberOperator("^", func(a, b float64) (interface{}, error) { return float64(int64(a) ^ int64(b)), nil }),
|
||||
InfixNumberOperator("&", func(a, b float64) (interface{}, error) { return float64(int64(a) & int64(b)), nil }),
|
||||
|
||||
+15
-3
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"text/scanner"
|
||||
"unicode"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
// Language is an expression language
|
||||
@@ -54,9 +56,14 @@ func newLanguage() Language {
|
||||
|
||||
// NewEvaluable returns an Evaluable for given expression in the specified language
|
||||
func (l Language) NewEvaluable(expression string) (Evaluable, error) {
|
||||
return l.NewEvaluableWithContext(context.Background(), expression)
|
||||
}
|
||||
|
||||
// NewEvaluableWithContext returns an Evaluable for given expression in the specified language using context
|
||||
func (l Language) NewEvaluableWithContext(c context.Context, expression string) (Evaluable, error) {
|
||||
p := newParser(expression, l)
|
||||
|
||||
eval, err := p.parse(context.Background())
|
||||
eval, err := p.parse(c)
|
||||
if err == nil && p.isCamouflaged() && p.lastScan != scanner.EOF {
|
||||
err = p.camouflage
|
||||
}
|
||||
@@ -75,7 +82,7 @@ func (l Language) Evaluate(expression string, parameter interface{}) (interface{
|
||||
|
||||
// Evaluate given parameter with given expression using context
|
||||
func (l Language) EvaluateWithContext(c context.Context, expression string, parameter interface{}) (interface{}, error) {
|
||||
eval, err := l.NewEvaluable(expression)
|
||||
eval, err := l.NewEvaluableWithContext(c, expression)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -180,7 +187,7 @@ func PrefixOperator(name string, e Evaluable) Language {
|
||||
return e(c, a)
|
||||
}
|
||||
if eval.IsConst() {
|
||||
v, err := prefix(context.Background(), nil)
|
||||
v, err := prefix(c, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -222,6 +229,11 @@ func InfixNumberOperator(name string, f func(a, b float64) (interface{}, error))
|
||||
return newLanguageOperator(name, &infix{number: f})
|
||||
}
|
||||
|
||||
// InfixDecimalOperator for two decimal values.
|
||||
func InfixDecimalOperator(name string, f func(a, b decimal.Decimal) (interface{}, error)) Language {
|
||||
return newLanguageOperator(name, &infix{decimal: f})
|
||||
}
|
||||
|
||||
// InfixBoolOperator for two bool values.
|
||||
func InfixBoolOperator(name string, f func(a, b bool) (interface{}, error)) Language {
|
||||
return newLanguageOperator(name, &infix{boolean: f})
|
||||
|
||||
+62
@@ -6,6 +6,8 @@ import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type stage struct {
|
||||
@@ -80,6 +82,9 @@ func (op *infix) initiate(name string) {
|
||||
if op.number != nil {
|
||||
f = getFloatOpFunc(op.number, f, typeConvertion)
|
||||
}
|
||||
if op.decimal != nil {
|
||||
f = getDecimalOpFunc(op.decimal, f, typeConvertion)
|
||||
}
|
||||
}
|
||||
if op.shortCircuit == nil {
|
||||
op.builder = func(a, b Evaluable) (Evaluable, error) {
|
||||
@@ -229,6 +234,59 @@ func getFloatOpFunc(o func(a, b float64) (interface{}, error), f opFunc, typeCon
|
||||
return f(a, b)
|
||||
}
|
||||
}
|
||||
func convertToDecimal(o interface{}) (decimal.Decimal, bool) {
|
||||
if i, ok := o.(decimal.Decimal); ok {
|
||||
return i, true
|
||||
}
|
||||
if i, ok := o.(float64); ok {
|
||||
return decimal.NewFromFloat(i), true
|
||||
}
|
||||
v := reflect.ValueOf(o)
|
||||
for o != nil && v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
if !v.IsValid() {
|
||||
return decimal.Zero, false
|
||||
}
|
||||
o = v.Interface()
|
||||
}
|
||||
switch v.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return decimal.NewFromInt(v.Int()), true
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return decimal.NewFromFloat(float64(v.Uint())), true
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return decimal.NewFromFloat(v.Float()), true
|
||||
}
|
||||
if s, ok := o.(string); ok {
|
||||
f, err := strconv.ParseFloat(s, 64)
|
||||
if err == nil {
|
||||
return decimal.NewFromFloat(f), true
|
||||
}
|
||||
}
|
||||
return decimal.Zero, false
|
||||
}
|
||||
func getDecimalOpFunc(o func(a, b decimal.Decimal) (interface{}, error), f opFunc, typeConversion bool) opFunc {
|
||||
if typeConversion {
|
||||
return func(a, b interface{}) (interface{}, error) {
|
||||
x, k := convertToDecimal(a)
|
||||
y, l := convertToDecimal(b)
|
||||
if k && l {
|
||||
return o(x, y)
|
||||
}
|
||||
|
||||
return f(a, b)
|
||||
}
|
||||
}
|
||||
return func(a, b interface{}) (interface{}, error) {
|
||||
x, k := a.(decimal.Decimal)
|
||||
y, l := b.(decimal.Decimal)
|
||||
if k && l {
|
||||
return o(x, y)
|
||||
}
|
||||
|
||||
return f(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
type operator interface {
|
||||
merge(operator) operator
|
||||
@@ -260,6 +318,7 @@ func (pre operatorPrecedence) initiate(name string) {}
|
||||
type infix struct {
|
||||
operatorPrecedence
|
||||
number func(a, b float64) (interface{}, error)
|
||||
decimal func(a, b decimal.Decimal) (interface{}, error)
|
||||
boolean func(a, b bool) (interface{}, error)
|
||||
text func(a, b string) (interface{}, error)
|
||||
arbitrary func(a, b interface{}) (interface{}, error)
|
||||
@@ -273,6 +332,9 @@ func (op infix) merge(op2 operator) operator {
|
||||
if op.number == nil {
|
||||
op.number = op2.number
|
||||
}
|
||||
if op.decimal == nil {
|
||||
op.decimal = op2.decimal
|
||||
}
|
||||
if op.boolean == nil {
|
||||
op.boolean = op2.boolean
|
||||
}
|
||||
|
||||
+10
@@ -6,6 +6,8 @@ import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"text/scanner"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
//ParseExpression scans an expression into an Evaluable.
|
||||
@@ -90,6 +92,14 @@ func parseNumber(c context.Context, p *Parser) (Evaluable, error) {
|
||||
return p.Const(n), nil
|
||||
}
|
||||
|
||||
func parseDecimal(c context.Context, p *Parser) (Evaluable, error) {
|
||||
n, err := strconv.ParseFloat(p.TokenText(), 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.Const(decimal.NewFromFloat(n)), nil
|
||||
}
|
||||
|
||||
func parseParentheses(c context.Context, p *Parser) (Evaluable, error) {
|
||||
eval, err := p.ParseExpression(c)
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -197,7 +197,7 @@ search with the same path more than once.
|
||||
|
||||
These are just a few examples of the things the etree package can do. See the
|
||||
[documentation](http://godoc.org/github.com/beevik/etree) for a complete
|
||||
description of its dal.
|
||||
description of its capabilities.
|
||||
|
||||
### Contributing
|
||||
|
||||
|
||||
+2
-2
@@ -7129,7 +7129,7 @@ SQLITE_API int sqlite3_table_column_metadata(
|
||||
** interface. The use of the [sqlite3_enable_load_extension()] interface
|
||||
** should be avoided. This will keep the SQL function [load_extension()]
|
||||
** disabled and prevent SQL injections from giving attackers
|
||||
** access to extension loading dal.
|
||||
** access to extension loading capabilities.
|
||||
**
|
||||
** See also the [load_extension() SQL function].
|
||||
*/
|
||||
@@ -7163,7 +7163,7 @@ SQLITE_API int sqlite3_load_extension(
|
||||
** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
|
||||
** rather than this interface, so the [load_extension()] SQL function
|
||||
** remains disabled. This will prevent SQL injections from giving attackers
|
||||
** access to extension loading dal.
|
||||
** access to extension loading capabilities.
|
||||
*/
|
||||
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
|
||||
|
||||
|
||||
+2
-2
@@ -6823,7 +6823,7 @@ SQLITE_API int sqlite3_table_column_metadata(
|
||||
** interface. The use of the [sqlite3_enable_load_extension()] interface
|
||||
** should be avoided. This will keep the SQL function [load_extension()]
|
||||
** disabled and prevent SQL injections from giving attackers
|
||||
** access to extension loading dal.
|
||||
** access to extension loading capabilities.
|
||||
**
|
||||
** See also the [load_extension() SQL function].
|
||||
*/
|
||||
@@ -6857,7 +6857,7 @@ SQLITE_API int sqlite3_load_extension(
|
||||
** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
|
||||
** rather than this interface, so the [load_extension()] SQL function
|
||||
** remains disabled. This will prevent SQL injections from giving attackers
|
||||
** access to extension loading dal.
|
||||
** access to extension loading capabilities.
|
||||
*/
|
||||
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
|
||||
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
//go:build arm64 && linux
|
||||
// +build arm64,linux
|
||||
|
||||
// Minio Cloud Storage, (C) 2016 Minio, Inc.
|
||||
@@ -35,7 +34,7 @@ func xgetbv(index uint32) (eax, edx uint32) {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
// File to check for cpu dal.
|
||||
// File to check for cpu capabilities.
|
||||
const procCPUInfo = "/proc/cpuinfo"
|
||||
|
||||
// Feature to check for.
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
.git
|
||||
*.swp
|
||||
|
||||
# IntelliJ
|
||||
.idea/
|
||||
*.iml
|
||||
|
||||
# VS code
|
||||
*.code-workspace
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
language: go
|
||||
|
||||
arch:
|
||||
- amd64
|
||||
- ppc64le
|
||||
|
||||
go:
|
||||
- 1.7.x
|
||||
- 1.14.x
|
||||
- 1.15.x
|
||||
- 1.16.x
|
||||
- 1.17.x
|
||||
- tip
|
||||
|
||||
install:
|
||||
- go build .
|
||||
|
||||
script:
|
||||
- go test -v
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
## Decimal v1.3.1
|
||||
|
||||
#### ENHANCEMENTS
|
||||
- Reduce memory allocation in case of initialization from big.Int [#252](https://github.com/shopspring/decimal/pull/252)
|
||||
|
||||
#### BUGFIXES
|
||||
- Fix binary marshalling of decimal zero value [#253](https://github.com/shopspring/decimal/pull/253)
|
||||
|
||||
## Decimal v1.3.0
|
||||
|
||||
#### FEATURES
|
||||
- Add NewFromFormattedString initializer [#184](https://github.com/shopspring/decimal/pull/184)
|
||||
- Add NewNullDecimal initializer [#234](https://github.com/shopspring/decimal/pull/234)
|
||||
- Add implementation of natural exponent function (Taylor, Hull-Abraham) [#229](https://github.com/shopspring/decimal/pull/229)
|
||||
- Add RoundUp, RoundDown, RoundCeil, RoundFloor methods [#196](https://github.com/shopspring/decimal/pull/196) [#202](https://github.com/shopspring/decimal/pull/202) [#220](https://github.com/shopspring/decimal/pull/220)
|
||||
- Add XML support for NullDecimal [#192](https://github.com/shopspring/decimal/pull/192)
|
||||
- Add IsInteger method [#179](https://github.com/shopspring/decimal/pull/179)
|
||||
- Add Copy helper method [#123](https://github.com/shopspring/decimal/pull/123)
|
||||
- Add InexactFloat64 helper method [#205](https://github.com/shopspring/decimal/pull/205)
|
||||
- Add CoefficientInt64 helper method [#244](https://github.com/shopspring/decimal/pull/244)
|
||||
|
||||
#### ENHANCEMENTS
|
||||
- Performance optimization of NewFromString init method [#198](https://github.com/shopspring/decimal/pull/198)
|
||||
- Performance optimization of Abs and Round methods [#240](https://github.com/shopspring/decimal/pull/240)
|
||||
- Additional tests (CI) for ppc64le architecture [#188](https://github.com/shopspring/decimal/pull/188)
|
||||
|
||||
#### BUGFIXES
|
||||
- Fix rounding in FormatFloat fallback path (roundShortest method, fix taken from Go main repository) [#161](https://github.com/shopspring/decimal/pull/161)
|
||||
- Add slice range checks to UnmarshalBinary method [#232](https://github.com/shopspring/decimal/pull/232)
|
||||
|
||||
## Decimal v1.2.0
|
||||
|
||||
#### BREAKING
|
||||
- Drop support for Go version older than 1.7 [#172](https://github.com/shopspring/decimal/pull/172)
|
||||
|
||||
#### FEATURES
|
||||
- Add NewFromInt and NewFromInt32 initializers [#72](https://github.com/shopspring/decimal/pull/72)
|
||||
- Add support for Go modules [#157](https://github.com/shopspring/decimal/pull/157)
|
||||
- Add BigInt, BigFloat helper methods [#171](https://github.com/shopspring/decimal/pull/171)
|
||||
|
||||
#### ENHANCEMENTS
|
||||
- Memory usage optimization [#160](https://github.com/shopspring/decimal/pull/160)
|
||||
- Updated travis CI golang versions [#156](https://github.com/shopspring/decimal/pull/156)
|
||||
- Update documentation [#173](https://github.com/shopspring/decimal/pull/173)
|
||||
- Improve code quality [#174](https://github.com/shopspring/decimal/pull/174)
|
||||
|
||||
#### BUGFIXES
|
||||
- Revert remove insignificant digits [#159](https://github.com/shopspring/decimal/pull/159)
|
||||
- Remove 15 interval for RoundCash [#166](https://github.com/shopspring/decimal/pull/166)
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Spring, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
- Based on https://github.com/oguzbilgic/fpd, which has the following license:
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Oguz Bilgic
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
"""
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
# decimal
|
||||
|
||||
[](https://app.travis-ci.com/shopspring/decimal) [](https://godoc.org/github.com/shopspring/decimal) [](https://goreportcard.com/report/github.com/shopspring/decimal)
|
||||
|
||||
Arbitrary-precision fixed-point decimal numbers in go.
|
||||
|
||||
_Note:_ Decimal library can "only" represent numbers with a maximum of 2^31 digits after the decimal point.
|
||||
|
||||
## Features
|
||||
|
||||
* The zero-value is 0, and is safe to use without initialization
|
||||
* Addition, subtraction, multiplication with no loss of precision
|
||||
* Division with specified precision
|
||||
* Database/sql serialization/deserialization
|
||||
* JSON and XML serialization/deserialization
|
||||
|
||||
## Install
|
||||
|
||||
Run `go get github.com/shopspring/decimal`
|
||||
|
||||
## Requirements
|
||||
|
||||
Decimal library requires Go version `>=1.7`
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
price, err := decimal.NewFromString("136.02")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
quantity := decimal.NewFromInt(3)
|
||||
|
||||
fee, _ := decimal.NewFromString(".035")
|
||||
taxRate, _ := decimal.NewFromString(".08875")
|
||||
|
||||
subtotal := price.Mul(quantity)
|
||||
|
||||
preTax := subtotal.Mul(fee.Add(decimal.NewFromFloat(1)))
|
||||
|
||||
total := preTax.Mul(taxRate.Add(decimal.NewFromFloat(1)))
|
||||
|
||||
fmt.Println("Subtotal:", subtotal) // Subtotal: 408.06
|
||||
fmt.Println("Pre-tax:", preTax) // Pre-tax: 422.3421
|
||||
fmt.Println("Taxes:", total.Sub(preTax)) // Taxes: 37.482861375
|
||||
fmt.Println("Total:", total) // Total: 459.824961375
|
||||
fmt.Println("Tax rate:", total.Sub(preTax).Div(preTax)) // Tax rate: 0.08875
|
||||
}
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
http://godoc.org/github.com/shopspring/decimal
|
||||
|
||||
## Production Usage
|
||||
|
||||
* [Spring](https://shopspring.com/), since August 14, 2014.
|
||||
* If you are using this in production, please let us know!
|
||||
|
||||
## FAQ
|
||||
|
||||
#### Why don't you just use float64?
|
||||
|
||||
Because float64 (or any binary floating point type, actually) can't represent
|
||||
numbers such as `0.1` exactly.
|
||||
|
||||
Consider this code: http://play.golang.org/p/TQBd4yJe6B You might expect that
|
||||
it prints out `10`, but it actually prints `9.999999999999831`. Over time,
|
||||
these small errors can really add up!
|
||||
|
||||
#### Why don't you just use big.Rat?
|
||||
|
||||
big.Rat is fine for representing rational numbers, but Decimal is better for
|
||||
representing money. Why? Here's a (contrived) example:
|
||||
|
||||
Let's say you use big.Rat, and you have two numbers, x and y, both
|
||||
representing 1/3, and you have `z = 1 - x - y = 1/3`. If you print each one
|
||||
out, the string output has to stop somewhere (let's say it stops at 3 decimal
|
||||
digits, for simplicity), so you'll get 0.333, 0.333, and 0.333. But where did
|
||||
the other 0.001 go?
|
||||
|
||||
Here's the above example as code: http://play.golang.org/p/lCZZs0w9KE
|
||||
|
||||
With Decimal, the strings being printed out represent the number exactly. So,
|
||||
if you have `x = y = 1/3` (with precision 3), they will actually be equal to
|
||||
0.333, and when you do `z = 1 - x - y`, `z` will be equal to .334. No money is
|
||||
unaccounted for!
|
||||
|
||||
You still have to be careful. If you want to split a number `N` 3 ways, you
|
||||
can't just send `N/3` to three different people. You have to pick one to send
|
||||
`N - (2/3*N)` to. That person will receive the fraction of a penny remainder.
|
||||
|
||||
But, it is much easier to be careful with Decimal than with big.Rat.
|
||||
|
||||
#### Why isn't the API similar to big.Int's?
|
||||
|
||||
big.Int's API is built to reduce the number of memory allocations for maximal
|
||||
performance. This makes sense for its use-case, but the trade-off is that the
|
||||
API is awkward and easy to misuse.
|
||||
|
||||
For example, to add two big.Ints, you do: `z := new(big.Int).Add(x, y)`. A
|
||||
developer unfamiliar with this API might try to do `z := a.Add(a, b)`. This
|
||||
modifies `a` and sets `z` as an alias for `a`, which they might not expect. It
|
||||
also modifies any other aliases to `a`.
|
||||
|
||||
Here's an example of the subtle bugs you can introduce with big.Int's API:
|
||||
https://play.golang.org/p/x2R_78pa8r
|
||||
|
||||
In contrast, it's difficult to make such mistakes with decimal. Decimals
|
||||
behave like other go numbers types: even though `a = b` will not deep copy
|
||||
`b` into `a`, it is impossible to modify a Decimal, since all Decimal methods
|
||||
return new Decimals and do not modify the originals. The downside is that
|
||||
this causes extra allocations, so Decimal is less performant. My assumption
|
||||
is that if you're using Decimals, you probably care more about correctness
|
||||
than performance.
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
This is a heavily modified fork of [fpd.Decimal](https://github.com/oguzbilgic/fpd), which was also released under the MIT License.
|
||||
+415
@@ -0,0 +1,415 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Multiprecision decimal numbers.
|
||||
// For floating-point formatting only; not general purpose.
|
||||
// Only operations are assign and (binary) left/right shift.
|
||||
// Can do binary floating point in multiprecision decimal precisely
|
||||
// because 2 divides 10; cannot do decimal floating point
|
||||
// in multiprecision binary precisely.
|
||||
|
||||
package decimal
|
||||
|
||||
type decimal struct {
|
||||
d [800]byte // digits, big-endian representation
|
||||
nd int // number of digits used
|
||||
dp int // decimal point
|
||||
neg bool // negative flag
|
||||
trunc bool // discarded nonzero digits beyond d[:nd]
|
||||
}
|
||||
|
||||
func (a *decimal) String() string {
|
||||
n := 10 + a.nd
|
||||
if a.dp > 0 {
|
||||
n += a.dp
|
||||
}
|
||||
if a.dp < 0 {
|
||||
n += -a.dp
|
||||
}
|
||||
|
||||
buf := make([]byte, n)
|
||||
w := 0
|
||||
switch {
|
||||
case a.nd == 0:
|
||||
return "0"
|
||||
|
||||
case a.dp <= 0:
|
||||
// zeros fill space between decimal point and digits
|
||||
buf[w] = '0'
|
||||
w++
|
||||
buf[w] = '.'
|
||||
w++
|
||||
w += digitZero(buf[w : w+-a.dp])
|
||||
w += copy(buf[w:], a.d[0:a.nd])
|
||||
|
||||
case a.dp < a.nd:
|
||||
// decimal point in middle of digits
|
||||
w += copy(buf[w:], a.d[0:a.dp])
|
||||
buf[w] = '.'
|
||||
w++
|
||||
w += copy(buf[w:], a.d[a.dp:a.nd])
|
||||
|
||||
default:
|
||||
// zeros fill space between digits and decimal point
|
||||
w += copy(buf[w:], a.d[0:a.nd])
|
||||
w += digitZero(buf[w : w+a.dp-a.nd])
|
||||
}
|
||||
return string(buf[0:w])
|
||||
}
|
||||
|
||||
func digitZero(dst []byte) int {
|
||||
for i := range dst {
|
||||
dst[i] = '0'
|
||||
}
|
||||
return len(dst)
|
||||
}
|
||||
|
||||
// trim trailing zeros from number.
|
||||
// (They are meaningless; the decimal point is tracked
|
||||
// independent of the number of digits.)
|
||||
func trim(a *decimal) {
|
||||
for a.nd > 0 && a.d[a.nd-1] == '0' {
|
||||
a.nd--
|
||||
}
|
||||
if a.nd == 0 {
|
||||
a.dp = 0
|
||||
}
|
||||
}
|
||||
|
||||
// Assign v to a.
|
||||
func (a *decimal) Assign(v uint64) {
|
||||
var buf [24]byte
|
||||
|
||||
// Write reversed decimal in buf.
|
||||
n := 0
|
||||
for v > 0 {
|
||||
v1 := v / 10
|
||||
v -= 10 * v1
|
||||
buf[n] = byte(v + '0')
|
||||
n++
|
||||
v = v1
|
||||
}
|
||||
|
||||
// Reverse again to produce forward decimal in a.d.
|
||||
a.nd = 0
|
||||
for n--; n >= 0; n-- {
|
||||
a.d[a.nd] = buf[n]
|
||||
a.nd++
|
||||
}
|
||||
a.dp = a.nd
|
||||
trim(a)
|
||||
}
|
||||
|
||||
// Maximum shift that we can do in one pass without overflow.
|
||||
// A uint has 32 or 64 bits, and we have to be able to accommodate 9<<k.
|
||||
const uintSize = 32 << (^uint(0) >> 63)
|
||||
const maxShift = uintSize - 4
|
||||
|
||||
// Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow.
|
||||
func rightShift(a *decimal, k uint) {
|
||||
r := 0 // read pointer
|
||||
w := 0 // write pointer
|
||||
|
||||
// Pick up enough leading digits to cover first shift.
|
||||
var n uint
|
||||
for ; n>>k == 0; r++ {
|
||||
if r >= a.nd {
|
||||
if n == 0 {
|
||||
// a == 0; shouldn't get here, but handle anyway.
|
||||
a.nd = 0
|
||||
return
|
||||
}
|
||||
for n>>k == 0 {
|
||||
n = n * 10
|
||||
r++
|
||||
}
|
||||
break
|
||||
}
|
||||
c := uint(a.d[r])
|
||||
n = n*10 + c - '0'
|
||||
}
|
||||
a.dp -= r - 1
|
||||
|
||||
var mask uint = (1 << k) - 1
|
||||
|
||||
// Pick up a digit, put down a digit.
|
||||
for ; r < a.nd; r++ {
|
||||
c := uint(a.d[r])
|
||||
dig := n >> k
|
||||
n &= mask
|
||||
a.d[w] = byte(dig + '0')
|
||||
w++
|
||||
n = n*10 + c - '0'
|
||||
}
|
||||
|
||||
// Put down extra digits.
|
||||
for n > 0 {
|
||||
dig := n >> k
|
||||
n &= mask
|
||||
if w < len(a.d) {
|
||||
a.d[w] = byte(dig + '0')
|
||||
w++
|
||||
} else if dig > 0 {
|
||||
a.trunc = true
|
||||
}
|
||||
n = n * 10
|
||||
}
|
||||
|
||||
a.nd = w
|
||||
trim(a)
|
||||
}
|
||||
|
||||
// Cheat sheet for left shift: table indexed by shift count giving
|
||||
// number of new digits that will be introduced by that shift.
|
||||
//
|
||||
// For example, leftcheats[4] = {2, "625"}. That means that
|
||||
// if we are shifting by 4 (multiplying by 16), it will add 2 digits
|
||||
// when the string prefix is "625" through "999", and one fewer digit
|
||||
// if the string prefix is "000" through "624".
|
||||
//
|
||||
// Credit for this trick goes to Ken.
|
||||
|
||||
type leftCheat struct {
|
||||
delta int // number of new digits
|
||||
cutoff string // minus one digit if original < a.
|
||||
}
|
||||
|
||||
var leftcheats = []leftCheat{
|
||||
// Leading digits of 1/2^i = 5^i.
|
||||
// 5^23 is not an exact 64-bit floating point number,
|
||||
// so have to use bc for the math.
|
||||
// Go up to 60 to be large enough for 32bit and 64bit platforms.
|
||||
/*
|
||||
seq 60 | sed 's/^/5^/' | bc |
|
||||
awk 'BEGIN{ print "\t{ 0, \"\" }," }
|
||||
{
|
||||
log2 = log(2)/log(10)
|
||||
printf("\t{ %d, \"%s\" },\t// * %d\n",
|
||||
int(log2*NR+1), $0, 2**NR)
|
||||
}'
|
||||
*/
|
||||
{0, ""},
|
||||
{1, "5"}, // * 2
|
||||
{1, "25"}, // * 4
|
||||
{1, "125"}, // * 8
|
||||
{2, "625"}, // * 16
|
||||
{2, "3125"}, // * 32
|
||||
{2, "15625"}, // * 64
|
||||
{3, "78125"}, // * 128
|
||||
{3, "390625"}, // * 256
|
||||
{3, "1953125"}, // * 512
|
||||
{4, "9765625"}, // * 1024
|
||||
{4, "48828125"}, // * 2048
|
||||
{4, "244140625"}, // * 4096
|
||||
{4, "1220703125"}, // * 8192
|
||||
{5, "6103515625"}, // * 16384
|
||||
{5, "30517578125"}, // * 32768
|
||||
{5, "152587890625"}, // * 65536
|
||||
{6, "762939453125"}, // * 131072
|
||||
{6, "3814697265625"}, // * 262144
|
||||
{6, "19073486328125"}, // * 524288
|
||||
{7, "95367431640625"}, // * 1048576
|
||||
{7, "476837158203125"}, // * 2097152
|
||||
{7, "2384185791015625"}, // * 4194304
|
||||
{7, "11920928955078125"}, // * 8388608
|
||||
{8, "59604644775390625"}, // * 16777216
|
||||
{8, "298023223876953125"}, // * 33554432
|
||||
{8, "1490116119384765625"}, // * 67108864
|
||||
{9, "7450580596923828125"}, // * 134217728
|
||||
{9, "37252902984619140625"}, // * 268435456
|
||||
{9, "186264514923095703125"}, // * 536870912
|
||||
{10, "931322574615478515625"}, // * 1073741824
|
||||
{10, "4656612873077392578125"}, // * 2147483648
|
||||
{10, "23283064365386962890625"}, // * 4294967296
|
||||
{10, "116415321826934814453125"}, // * 8589934592
|
||||
{11, "582076609134674072265625"}, // * 17179869184
|
||||
{11, "2910383045673370361328125"}, // * 34359738368
|
||||
{11, "14551915228366851806640625"}, // * 68719476736
|
||||
{12, "72759576141834259033203125"}, // * 137438953472
|
||||
{12, "363797880709171295166015625"}, // * 274877906944
|
||||
{12, "1818989403545856475830078125"}, // * 549755813888
|
||||
{13, "9094947017729282379150390625"}, // * 1099511627776
|
||||
{13, "45474735088646411895751953125"}, // * 2199023255552
|
||||
{13, "227373675443232059478759765625"}, // * 4398046511104
|
||||
{13, "1136868377216160297393798828125"}, // * 8796093022208
|
||||
{14, "5684341886080801486968994140625"}, // * 17592186044416
|
||||
{14, "28421709430404007434844970703125"}, // * 35184372088832
|
||||
{14, "142108547152020037174224853515625"}, // * 70368744177664
|
||||
{15, "710542735760100185871124267578125"}, // * 140737488355328
|
||||
{15, "3552713678800500929355621337890625"}, // * 281474976710656
|
||||
{15, "17763568394002504646778106689453125"}, // * 562949953421312
|
||||
{16, "88817841970012523233890533447265625"}, // * 1125899906842624
|
||||
{16, "444089209850062616169452667236328125"}, // * 2251799813685248
|
||||
{16, "2220446049250313080847263336181640625"}, // * 4503599627370496
|
||||
{16, "11102230246251565404236316680908203125"}, // * 9007199254740992
|
||||
{17, "55511151231257827021181583404541015625"}, // * 18014398509481984
|
||||
{17, "277555756156289135105907917022705078125"}, // * 36028797018963968
|
||||
{17, "1387778780781445675529539585113525390625"}, // * 72057594037927936
|
||||
{18, "6938893903907228377647697925567626953125"}, // * 144115188075855872
|
||||
{18, "34694469519536141888238489627838134765625"}, // * 288230376151711744
|
||||
{18, "173472347597680709441192448139190673828125"}, // * 576460752303423488
|
||||
{19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976
|
||||
}
|
||||
|
||||
// Is the leading prefix of b lexicographically less than s?
|
||||
func prefixIsLessThan(b []byte, s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if i >= len(b) {
|
||||
return true
|
||||
}
|
||||
if b[i] != s[i] {
|
||||
return b[i] < s[i]
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow.
|
||||
func leftShift(a *decimal, k uint) {
|
||||
delta := leftcheats[k].delta
|
||||
if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
|
||||
delta--
|
||||
}
|
||||
|
||||
r := a.nd // read index
|
||||
w := a.nd + delta // write index
|
||||
|
||||
// Pick up a digit, put down a digit.
|
||||
var n uint
|
||||
for r--; r >= 0; r-- {
|
||||
n += (uint(a.d[r]) - '0') << k
|
||||
quo := n / 10
|
||||
rem := n - 10*quo
|
||||
w--
|
||||
if w < len(a.d) {
|
||||
a.d[w] = byte(rem + '0')
|
||||
} else if rem != 0 {
|
||||
a.trunc = true
|
||||
}
|
||||
n = quo
|
||||
}
|
||||
|
||||
// Put down extra digits.
|
||||
for n > 0 {
|
||||
quo := n / 10
|
||||
rem := n - 10*quo
|
||||
w--
|
||||
if w < len(a.d) {
|
||||
a.d[w] = byte(rem + '0')
|
||||
} else if rem != 0 {
|
||||
a.trunc = true
|
||||
}
|
||||
n = quo
|
||||
}
|
||||
|
||||
a.nd += delta
|
||||
if a.nd >= len(a.d) {
|
||||
a.nd = len(a.d)
|
||||
}
|
||||
a.dp += delta
|
||||
trim(a)
|
||||
}
|
||||
|
||||
// Binary shift left (k > 0) or right (k < 0).
|
||||
func (a *decimal) Shift(k int) {
|
||||
switch {
|
||||
case a.nd == 0:
|
||||
// nothing to do: a == 0
|
||||
case k > 0:
|
||||
for k > maxShift {
|
||||
leftShift(a, maxShift)
|
||||
k -= maxShift
|
||||
}
|
||||
leftShift(a, uint(k))
|
||||
case k < 0:
|
||||
for k < -maxShift {
|
||||
rightShift(a, maxShift)
|
||||
k += maxShift
|
||||
}
|
||||
rightShift(a, uint(-k))
|
||||
}
|
||||
}
|
||||
|
||||
// If we chop a at nd digits, should we round up?
|
||||
func shouldRoundUp(a *decimal, nd int) bool {
|
||||
if nd < 0 || nd >= a.nd {
|
||||
return false
|
||||
}
|
||||
if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
|
||||
// if we truncated, a little higher than what's recorded - always round up
|
||||
if a.trunc {
|
||||
return true
|
||||
}
|
||||
return nd > 0 && (a.d[nd-1]-'0')%2 != 0
|
||||
}
|
||||
// not halfway - digit tells all
|
||||
return a.d[nd] >= '5'
|
||||
}
|
||||
|
||||
// Round a to nd digits (or fewer).
|
||||
// If nd is zero, it means we're rounding
|
||||
// just to the left of the digits, as in
|
||||
// 0.09 -> 0.1.
|
||||
func (a *decimal) Round(nd int) {
|
||||
if nd < 0 || nd >= a.nd {
|
||||
return
|
||||
}
|
||||
if shouldRoundUp(a, nd) {
|
||||
a.RoundUp(nd)
|
||||
} else {
|
||||
a.RoundDown(nd)
|
||||
}
|
||||
}
|
||||
|
||||
// Round a down to nd digits (or fewer).
|
||||
func (a *decimal) RoundDown(nd int) {
|
||||
if nd < 0 || nd >= a.nd {
|
||||
return
|
||||
}
|
||||
a.nd = nd
|
||||
trim(a)
|
||||
}
|
||||
|
||||
// Round a up to nd digits (or fewer).
|
||||
func (a *decimal) RoundUp(nd int) {
|
||||
if nd < 0 || nd >= a.nd {
|
||||
return
|
||||
}
|
||||
|
||||
// round up
|
||||
for i := nd - 1; i >= 0; i-- {
|
||||
c := a.d[i]
|
||||
if c < '9' { // can stop after this digit
|
||||
a.d[i]++
|
||||
a.nd = i + 1
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Number is all 9s.
|
||||
// Change to single 1 with adjusted decimal point.
|
||||
a.d[0] = '1'
|
||||
a.nd = 1
|
||||
a.dp++
|
||||
}
|
||||
|
||||
// Extract integer part, rounded appropriately.
|
||||
// No guarantees about overflow.
|
||||
func (a *decimal) RoundedInteger() uint64 {
|
||||
if a.dp > 20 {
|
||||
return 0xFFFFFFFFFFFFFFFF
|
||||
}
|
||||
var i int
|
||||
n := uint64(0)
|
||||
for i = 0; i < a.dp && i < a.nd; i++ {
|
||||
n = n*10 + uint64(a.d[i]-'0')
|
||||
}
|
||||
for ; i < a.dp; i++ {
|
||||
n *= 10
|
||||
}
|
||||
if shouldRoundUp(a, a.dp) {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
+1904
File diff suppressed because it is too large
Load Diff
+160
@@ -0,0 +1,160 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Multiprecision decimal numbers.
|
||||
// For floating-point formatting only; not general purpose.
|
||||
// Only operations are assign and (binary) left/right shift.
|
||||
// Can do binary floating point in multiprecision decimal precisely
|
||||
// because 2 divides 10; cannot do decimal floating point
|
||||
// in multiprecision binary precisely.
|
||||
|
||||
package decimal
|
||||
|
||||
type floatInfo struct {
|
||||
mantbits uint
|
||||
expbits uint
|
||||
bias int
|
||||
}
|
||||
|
||||
var float32info = floatInfo{23, 8, -127}
|
||||
var float64info = floatInfo{52, 11, -1023}
|
||||
|
||||
// roundShortest rounds d (= mant * 2^exp) to the shortest number of digits
|
||||
// that will let the original floating point value be precisely reconstructed.
|
||||
func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) {
|
||||
// If mantissa is zero, the number is zero; stop now.
|
||||
if mant == 0 {
|
||||
d.nd = 0
|
||||
return
|
||||
}
|
||||
|
||||
// Compute upper and lower such that any decimal number
|
||||
// between upper and lower (possibly inclusive)
|
||||
// will round to the original floating point number.
|
||||
|
||||
// We may see at once that the number is already shortest.
|
||||
//
|
||||
// Suppose d is not denormal, so that 2^exp <= d < 10^dp.
|
||||
// The closest shorter number is at least 10^(dp-nd) away.
|
||||
// The lower/upper bounds computed below are at distance
|
||||
// at most 2^(exp-mantbits).
|
||||
//
|
||||
// So the number is already shortest if 10^(dp-nd) > 2^(exp-mantbits),
|
||||
// or equivalently log2(10)*(dp-nd) > exp-mantbits.
|
||||
// It is true if 332/100*(dp-nd) >= exp-mantbits (log2(10) > 3.32).
|
||||
minexp := flt.bias + 1 // minimum possible exponent
|
||||
if exp > minexp && 332*(d.dp-d.nd) >= 100*(exp-int(flt.mantbits)) {
|
||||
// The number is already shortest.
|
||||
return
|
||||
}
|
||||
|
||||
// d = mant << (exp - mantbits)
|
||||
// Next highest floating point number is mant+1 << exp-mantbits.
|
||||
// Our upper bound is halfway between, mant*2+1 << exp-mantbits-1.
|
||||
upper := new(decimal)
|
||||
upper.Assign(mant*2 + 1)
|
||||
upper.Shift(exp - int(flt.mantbits) - 1)
|
||||
|
||||
// d = mant << (exp - mantbits)
|
||||
// Next lowest floating point number is mant-1 << exp-mantbits,
|
||||
// unless mant-1 drops the significant bit and exp is not the minimum exp,
|
||||
// in which case the next lowest is mant*2-1 << exp-mantbits-1.
|
||||
// Either way, call it mantlo << explo-mantbits.
|
||||
// Our lower bound is halfway between, mantlo*2+1 << explo-mantbits-1.
|
||||
var mantlo uint64
|
||||
var explo int
|
||||
if mant > 1<<flt.mantbits || exp == minexp {
|
||||
mantlo = mant - 1
|
||||
explo = exp
|
||||
} else {
|
||||
mantlo = mant*2 - 1
|
||||
explo = exp - 1
|
||||
}
|
||||
lower := new(decimal)
|
||||
lower.Assign(mantlo*2 + 1)
|
||||
lower.Shift(explo - int(flt.mantbits) - 1)
|
||||
|
||||
// The upper and lower bounds are possible outputs only if
|
||||
// the original mantissa is even, so that IEEE round-to-even
|
||||
// would round to the original mantissa and not the neighbors.
|
||||
inclusive := mant%2 == 0
|
||||
|
||||
// As we walk the digits we want to know whether rounding up would fall
|
||||
// within the upper bound. This is tracked by upperdelta:
|
||||
//
|
||||
// If upperdelta == 0, the digits of d and upper are the same so far.
|
||||
//
|
||||
// If upperdelta == 1, we saw a difference of 1 between d and upper on a
|
||||
// previous digit and subsequently only 9s for d and 0s for upper.
|
||||
// (Thus rounding up may fall outside the bound, if it is exclusive.)
|
||||
//
|
||||
// If upperdelta == 2, then the difference is greater than 1
|
||||
// and we know that rounding up falls within the bound.
|
||||
var upperdelta uint8
|
||||
|
||||
// Now we can figure out the minimum number of digits required.
|
||||
// Walk along until d has distinguished itself from upper and lower.
|
||||
for ui := 0; ; ui++ {
|
||||
// lower, d, and upper may have the decimal points at different
|
||||
// places. In this case upper is the longest, so we iterate from
|
||||
// ui==0 and start li and mi at (possibly) -1.
|
||||
mi := ui - upper.dp + d.dp
|
||||
if mi >= d.nd {
|
||||
break
|
||||
}
|
||||
li := ui - upper.dp + lower.dp
|
||||
l := byte('0') // lower digit
|
||||
if li >= 0 && li < lower.nd {
|
||||
l = lower.d[li]
|
||||
}
|
||||
m := byte('0') // middle digit
|
||||
if mi >= 0 {
|
||||
m = d.d[mi]
|
||||
}
|
||||
u := byte('0') // upper digit
|
||||
if ui < upper.nd {
|
||||
u = upper.d[ui]
|
||||
}
|
||||
|
||||
// Okay to round down (truncate) if lower has a different digit
|
||||
// or if lower is inclusive and is exactly the result of rounding
|
||||
// down (i.e., and we have reached the final digit of lower).
|
||||
okdown := l != m || inclusive && li+1 == lower.nd
|
||||
|
||||
switch {
|
||||
case upperdelta == 0 && m+1 < u:
|
||||
// Example:
|
||||
// m = 12345xxx
|
||||
// u = 12347xxx
|
||||
upperdelta = 2
|
||||
case upperdelta == 0 && m != u:
|
||||
// Example:
|
||||
// m = 12345xxx
|
||||
// u = 12346xxx
|
||||
upperdelta = 1
|
||||
case upperdelta == 1 && (m != '9' || u != '0'):
|
||||
// Example:
|
||||
// m = 1234598x
|
||||
// u = 1234600x
|
||||
upperdelta = 2
|
||||
}
|
||||
// Okay to round up if upper has a different digit and either upper
|
||||
// is inclusive or upper is bigger than the result of rounding up.
|
||||
okup := upperdelta > 0 && (inclusive || upperdelta > 1 || ui+1 < upper.nd)
|
||||
|
||||
// If it's okay to do either, then round to the nearest one.
|
||||
// If it's okay to do only one, do it.
|
||||
switch {
|
||||
case okdown && okup:
|
||||
d.Round(mi + 1)
|
||||
return
|
||||
case okdown:
|
||||
d.RoundDown(mi + 1)
|
||||
return
|
||||
case okup:
|
||||
d.RoundUp(mi + 1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -20,5 +20,5 @@
|
||||
|
||||
// Package zapcore defines and implements the low-level interfaces upon which
|
||||
// zap is built. By providing alternate implementations of these interfaces,
|
||||
// external packages can extend zap's dal.
|
||||
// external packages can extend zap's capabilities.
|
||||
package zapcore // import "go.uber.org/zap/zapcore"
|
||||
|
||||
Vendored
+4
-1
@@ -16,7 +16,7 @@ github.com/Masterminds/semver
|
||||
# github.com/Masterminds/sprig v2.22.0+incompatible
|
||||
## explicit
|
||||
github.com/Masterminds/sprig
|
||||
# github.com/PaesslerAG/gval v1.1.2
|
||||
# github.com/PaesslerAG/gval v1.2.1
|
||||
## explicit; go 1.15
|
||||
github.com/PaesslerAG/gval
|
||||
# github.com/PaesslerAG/jsonpath v0.1.1
|
||||
@@ -395,6 +395,9 @@ github.com/russellhaering/goxmldsig/types
|
||||
## explicit
|
||||
github.com/rwcarlsen/goexif/exif
|
||||
github.com/rwcarlsen/goexif/tiff
|
||||
# github.com/shopspring/decimal v1.3.1
|
||||
## explicit; go 1.13
|
||||
github.com/shopspring/decimal
|
||||
# github.com/sony/sonyflake v1.0.0
|
||||
## explicit; go 1.12
|
||||
github.com/sony/sonyflake
|
||||
|
||||
Reference in New Issue
Block a user