From 735e1cacf0ac2e0d5dc0d115adfd4515104144ca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:57:23 +0000 Subject: [PATCH] chore(deps): update dependency: bump github.com/getkin/kin-openapi Bumps [github.com/getkin/kin-openapi](https://github.com/getkin/kin-openapi) from 0.139.0 to 0.140.0. - [Release notes](https://github.com/getkin/kin-openapi/releases) - [Commits](https://github.com/getkin/kin-openapi/compare/v0.139.0...v0.140.0) --- updated-dependencies: - dependency-name: github.com/getkin/kin-openapi dependency-version: 0.140.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 12 +- go.sum | 34 +- .../getkin/kin-openapi/openapi3/helpers.go | 2 +- .../getkin/kin-openapi/openapi3/loader.go | 29 +- .../getkin/kin-openapi/openapi3/refs.go | 46 +- .../getkin/kin-openapi/openapi3/refs.tmpl | 6 +- .../getkin/kin-openapi/openapi3/schema.go | 37 +- .../go-openapi/jsonpointer/.cliff.toml | 181 +++ .../go-openapi/jsonpointer/.gitignore | 7 +- .../go-openapi/jsonpointer/.golangci.yml | 112 +- .../go-openapi/jsonpointer/CODE_OF_CONDUCT.md | 6 +- .../go-openapi/jsonpointer/CONTRIBUTORS.md | 24 + .../github.com/go-openapi/jsonpointer/LICENSE | 1 - .../github.com/go-openapi/jsonpointer/NOTICE | 39 + .../go-openapi/jsonpointer/README.md | 161 ++- .../go-openapi/jsonpointer/SECURITY.md | 37 + .../go-openapi/jsonpointer/errors.go | 35 + .../go-openapi/jsonpointer/pointer.go | 622 +++++---- .../github.com/go-openapi/swag/.editorconfig | 26 - .../github.com/go-openapi/swag/.gitattributes | 2 - vendor/github.com/go-openapi/swag/.gitignore | 5 - .../github.com/go-openapi/swag/.golangci.yml | 60 - .../github.com/go-openapi/swag/BENCHMARK.md | 52 - .../go-openapi/swag/CODE_OF_CONDUCT.md | 74 - vendor/github.com/go-openapi/swag/README.md | 23 - vendor/github.com/go-openapi/swag/convert.go | 208 --- .../go-openapi/swag/convert_types.go | 730 ---------- vendor/github.com/go-openapi/swag/doc.go | 31 - vendor/github.com/go-openapi/swag/file.go | 33 - .../go-openapi/swag/initialism_index.go | 202 --- vendor/github.com/go-openapi/swag/json.go | 312 ----- .../go-openapi/swag/{ => jsonname}/LICENSE | 0 .../go-openapi/swag/jsonname/doc.go | 5 + .../go-openapi/swag/jsonname/name_provider.go | 138 ++ vendor/github.com/go-openapi/swag/loading.go | 176 --- .../github.com/go-openapi/swag/name_lexem.go | 93 -- vendor/github.com/go-openapi/swag/net.go | 38 - vendor/github.com/go-openapi/swag/path.go | 59 - vendor/github.com/go-openapi/swag/split.go | 508 ------- .../go-openapi/swag/string_bytes.go | 8 - vendor/github.com/go-openapi/swag/util.go | 364 ----- vendor/github.com/go-openapi/swag/yaml.go | 481 ------- vendor/github.com/josharian/intern/README.md | 5 - vendor/github.com/josharian/intern/intern.go | 44 - vendor/github.com/josharian/intern/license.md | 21 - vendor/github.com/mailru/easyjson/LICENSE | 7 - .../github.com/mailru/easyjson/buffer/pool.go | 278 ---- .../mailru/easyjson/jlexer/bytestostr.go | 24 - .../easyjson/jlexer/bytestostr_nounsafe.go | 13 - .../mailru/easyjson/jlexer/error.go | 15 - .../mailru/easyjson/jlexer/lexer.go | 1244 ----------------- .../mailru/easyjson/jwriter/writer.go | 405 ------ vendor/github.com/mohae/deepcopy/.gitignore | 26 - vendor/github.com/mohae/deepcopy/.travis.yml | 11 - vendor/github.com/mohae/deepcopy/LICENSE | 21 - vendor/github.com/mohae/deepcopy/README.md | 8 - vendor/github.com/mohae/deepcopy/deepcopy.go | 125 -- .../perimeterx/marshmallow/.gitignore | 4 - .../perimeterx/marshmallow/CHANGELOG.md | 49 - .../perimeterx/marshmallow/CODE_OF_CONDUCT.md | 133 -- .../perimeterx/marshmallow/CONTRIBUTING.md | 47 - .../github.com/perimeterx/marshmallow/LICENSE | 21 - .../perimeterx/marshmallow/README.md | 205 --- .../perimeterx/marshmallow/cache.go | 63 - .../github.com/perimeterx/marshmallow/doc.go | 10 - .../perimeterx/marshmallow/errors.go | 101 -- .../perimeterx/marshmallow/options.go | 96 -- .../perimeterx/marshmallow/reflection.go | 197 --- .../perimeterx/marshmallow/unmarshal.go | 383 ----- .../marshmallow/unmarshal_from_json_map.go | 295 ---- .../github.com/woodsbury/decimal128/LICENCE | 14 - .../github.com/woodsbury/decimal128/arith.go | 1178 ---------------- .../github.com/woodsbury/decimal128/binary.go | 59 - .../woodsbury/decimal128/compare.go | 1054 -------------- .../woodsbury/decimal128/compose.go | 252 ---- .../woodsbury/decimal128/constants.go | 22 - .../woodsbury/decimal128/convert.go | 799 ----------- .../woodsbury/decimal128/decimal.go | 284 ---- .../woodsbury/decimal128/decomposed.go | 1199 ---------------- vendor/github.com/woodsbury/decimal128/exp.go | 783 ----------- .../github.com/woodsbury/decimal128/format.go | 929 ------------ vendor/github.com/woodsbury/decimal128/int.go | 1017 -------------- .../github.com/woodsbury/decimal128/json.go | 104 -- .../woodsbury/decimal128/payload.go | 125 -- .../woodsbury/decimal128/rounding.go | 747 ---------- .../github.com/woodsbury/decimal128/scan.go | 475 ------- vendor/modules.txt | 29 +- 87 files changed, 1127 insertions(+), 16813 deletions(-) create mode 100644 vendor/github.com/go-openapi/jsonpointer/.cliff.toml create mode 100644 vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md create mode 100644 vendor/github.com/go-openapi/jsonpointer/NOTICE create mode 100644 vendor/github.com/go-openapi/jsonpointer/SECURITY.md create mode 100644 vendor/github.com/go-openapi/jsonpointer/errors.go delete mode 100644 vendor/github.com/go-openapi/swag/.editorconfig delete mode 100644 vendor/github.com/go-openapi/swag/.gitattributes delete mode 100644 vendor/github.com/go-openapi/swag/.gitignore delete mode 100644 vendor/github.com/go-openapi/swag/.golangci.yml delete mode 100644 vendor/github.com/go-openapi/swag/BENCHMARK.md delete mode 100644 vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/swag/README.md delete mode 100644 vendor/github.com/go-openapi/swag/convert.go delete mode 100644 vendor/github.com/go-openapi/swag/convert_types.go delete mode 100644 vendor/github.com/go-openapi/swag/doc.go delete mode 100644 vendor/github.com/go-openapi/swag/file.go delete mode 100644 vendor/github.com/go-openapi/swag/initialism_index.go delete mode 100644 vendor/github.com/go-openapi/swag/json.go rename vendor/github.com/go-openapi/swag/{ => jsonname}/LICENSE (100%) create mode 100644 vendor/github.com/go-openapi/swag/jsonname/doc.go create mode 100644 vendor/github.com/go-openapi/swag/jsonname/name_provider.go delete mode 100644 vendor/github.com/go-openapi/swag/loading.go delete mode 100644 vendor/github.com/go-openapi/swag/name_lexem.go delete mode 100644 vendor/github.com/go-openapi/swag/net.go delete mode 100644 vendor/github.com/go-openapi/swag/path.go delete mode 100644 vendor/github.com/go-openapi/swag/split.go delete mode 100644 vendor/github.com/go-openapi/swag/string_bytes.go delete mode 100644 vendor/github.com/go-openapi/swag/util.go delete mode 100644 vendor/github.com/go-openapi/swag/yaml.go delete mode 100644 vendor/github.com/josharian/intern/README.md delete mode 100644 vendor/github.com/josharian/intern/intern.go delete mode 100644 vendor/github.com/josharian/intern/license.md delete mode 100644 vendor/github.com/mailru/easyjson/LICENSE delete mode 100644 vendor/github.com/mailru/easyjson/buffer/pool.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/error.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer.go delete mode 100644 vendor/github.com/mailru/easyjson/jwriter/writer.go delete mode 100644 vendor/github.com/mohae/deepcopy/.gitignore delete mode 100644 vendor/github.com/mohae/deepcopy/.travis.yml delete mode 100644 vendor/github.com/mohae/deepcopy/LICENSE delete mode 100644 vendor/github.com/mohae/deepcopy/README.md delete mode 100644 vendor/github.com/mohae/deepcopy/deepcopy.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/.gitignore delete mode 100644 vendor/github.com/perimeterx/marshmallow/CHANGELOG.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/CONTRIBUTING.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/LICENSE delete mode 100644 vendor/github.com/perimeterx/marshmallow/README.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/cache.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/doc.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/errors.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/options.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/reflection.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/unmarshal.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/unmarshal_from_json_map.go delete mode 100644 vendor/github.com/woodsbury/decimal128/LICENCE delete mode 100644 vendor/github.com/woodsbury/decimal128/arith.go delete mode 100644 vendor/github.com/woodsbury/decimal128/binary.go delete mode 100644 vendor/github.com/woodsbury/decimal128/compare.go delete mode 100644 vendor/github.com/woodsbury/decimal128/compose.go delete mode 100644 vendor/github.com/woodsbury/decimal128/constants.go delete mode 100644 vendor/github.com/woodsbury/decimal128/convert.go delete mode 100644 vendor/github.com/woodsbury/decimal128/decimal.go delete mode 100644 vendor/github.com/woodsbury/decimal128/decomposed.go delete mode 100644 vendor/github.com/woodsbury/decimal128/exp.go delete mode 100644 vendor/github.com/woodsbury/decimal128/format.go delete mode 100644 vendor/github.com/woodsbury/decimal128/int.go delete mode 100644 vendor/github.com/woodsbury/decimal128/json.go delete mode 100644 vendor/github.com/woodsbury/decimal128/payload.go delete mode 100644 vendor/github.com/woodsbury/decimal128/rounding.go delete mode 100644 vendor/github.com/woodsbury/decimal128/scan.go diff --git a/go.mod b/go.mod index 37ade64..d2dc13e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/DistroByte/molecule go 1.26.0 require ( - github.com/getkin/kin-openapi v0.139.0 + github.com/getkin/kin-openapi v0.140.0 github.com/go-chi/chi/v5 v5.3.0 github.com/google/uuid v1.6.0 github.com/hashicorp/nomad/api v0.0.0-20260220212019-daca79db0bd6 @@ -14,16 +14,16 @@ require ( require ( github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/go-openapi/swag/jsonname v0.25.5 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect + github.com/kr/pretty v0.3.1 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect - github.com/woodsbury/decimal128 v1.3.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) require ( github.com/davecgh/go-spew v1.1.1 // indirect - github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-openapi/jsonpointer v0.22.5 // indirect github.com/goccy/go-yaml v1.19.2 github.com/gorilla/websocket v1.5.3 // indirect github.com/hashicorp/cronexpr v1.1.3 // indirect @@ -31,16 +31,12 @@ require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.20 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/oasdiff/yaml v0.1.0 // indirect github.com/oasdiff/yaml3 v0.0.13 // indirect - github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/text v0.34.0 // indirect diff --git a/go.sum b/go.sum index d1d6b02..b458471 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,6 @@ github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= @@ -8,16 +9,16 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4 github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/getkin/kin-openapi v0.139.0 h1:pBFXcZJFwz9J1X64jzxlOoNgFm+TF7kNrs9+HJVN6Ic= -github.com/getkin/kin-openapi v0.139.0/go.mod h1:NGxPfE4PwS/TRXEbyx2RrxDFPZvxcWw31Tw8XXjPZLs= +github.com/getkin/kin-openapi v0.140.0 h1:JFn675aXRFjyiZKa/BFWploGldQlI0gobp4J5k0EZ2g= +github.com/getkin/kin-openapi v0.140.0/go.mod h1:lISrB64F0CPcuDJ3LdtPTMJBY8VENjR9wJBdrcT6J3g= github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM= github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= -github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= -github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= -github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= -github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= -github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA= +github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0= +github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo= +github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= +github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM= +github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= @@ -43,14 +44,10 @@ github.com/hashicorp/nomad/api v0.0.0-20260220212019-daca79db0bd6 h1:QN/GwpGyiW8 github.com/hashicorp/nomad/api v0.0.0-20260220212019-daca79db0bd6/go.mod h1:KkLNLU0Nyfh5jWsFoF/PsmMbKpRIAoIV4lmQoJWgKCk= github.com/jedib0t/go-pretty/v6 v6.7.10 h1:B/2qW2Bkv2L6n14PP8o1kx75kWzHOQ3YTluWzg9icac= github.com/jedib0t/go-pretty/v6 v6.7.10/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -59,18 +56,15 @@ github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjc github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= -github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/oasdiff/yaml v0.1.0 h1:0bqZjfKc/8S9urj4JuwepX41WX9EoA6ifhU3SV06cXg= github.com/oasdiff/yaml v0.1.0/go.mod h1:kOlRmMdL2X3vucLCEQO5u61SU22RysnfXvcttrZA1O0= github.com/oasdiff/yaml3 v0.0.13 h1:06svmvOHOVBqF81+sY2EUScvUI/iS/vl2VIeUUxZQwg= github.com/oasdiff/yaml3 v0.0.13/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o= -github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= -github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI= github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw= github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= @@ -79,10 +73,6 @@ github.com/shoenig/test v1.12.2 h1:ZVT8NeIUwGWpZcKaepPmFMoNQ3sVpxvqUh/MAqwFiJI= github.com/shoenig/test v1.12.2/go.mod h1:UxJ6u/x2v/TNs/LoLxBNJRV9DiwBBKYxXSyczsBHFoI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= -github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= -github.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0= -github.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go b/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go index 24c26a4..62e8457 100644 --- a/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go +++ b/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go @@ -212,7 +212,7 @@ func ReferencesComponentInRootDocument(doc *T, ref ComponentRef) (string, bool) var components map[string]ComponentRef - componentRefType := reflect.TypeOf(new(ComponentRef)).Elem() + componentRefType := reflect.TypeFor[ComponentRef]() if t := reflect.TypeOf(collection); t.Kind() == reflect.Map && t.Key().Kind() == reflect.String && t.Elem().AssignableTo(componentRefType) { diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go b/vendor/github.com/getkin/kin-openapi/openapi3/loader.go index 4f2697d..1974294 100644 --- a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go +++ b/vendor/github.com/getkin/kin-openapi/openapi3/loader.go @@ -26,7 +26,9 @@ func failedToResolveRefFragmentPart(value, what string) error { // Loader helps deserialize an OpenAPIv3 document type Loader struct { - // IsExternalRefsAllowed enables visiting other files + // IsExternalRefsAllowed enables visiting other files. Enforced only when + // ReadFromURIFunc is nil; a custom ReadFromURIFunc bypasses this flag and + // owns the access policy itself — see ReadFromURIFunc. IsExternalRefsAllowed bool // IncludeOrigin enables recording the file/line/column of each OpenAPI element. @@ -34,7 +36,16 @@ type Loader struct { // concurrent use. IncludeOrigin bool - // ReadFromURIFunc allows overriding the any file/URL reading func + // ReadFromURIFunc overrides how the loader reads a referenced file or URL. + // + // SECURITY: when a custom ReadFromURIFunc is set, IsExternalRefsAllowed is + // NOT enforced — this function alone decides which locations may be read. A + // func that reads whatever URI it is handed (e.g. by delegating to + // DefaultReadFromURI) resolves external $refs even when IsExternalRefsAllowed + // is false, which on untrusted documents enables local file reads + // (`$ref: "/etc/passwd"`) and SSRF (`$ref: "http://169.254.169.254/..."`). + // A custom func must apply its own scheme/host allowlist, or re-check + // IsExternalRefsAllowed, before reading. ReadFromURIFunc ReadFromURIFunc // JoinFunc allows overriding how relative $ref paths are resolved against @@ -101,9 +112,9 @@ func (loader *Loader) allowsExternalRefs(ref string) (err error) { } func (loader *Loader) loadSingleElementFromURI(ref string, rootPath *url.URL, element any) (*url.URL, error) { - // When a custom ReadFromURIFunc is installed, defer the external-ref decision to it; - // the function itself is responsible for enforcing any access policy. - // Otherwise enforce IsExternalRefsAllowed here before attempting any I/O. + // IsExternalRefsAllowed is enforced here only when no custom ReadFromURIFunc + // is installed; otherwise the custom func owns the access policy (see the + // SECURITY note on the ReadFromURIFunc field). if loader.ReadFromURIFunc == nil { if err := loader.allowsExternalRefs(ref); err != nil { return nil, err @@ -331,7 +342,9 @@ func (loader *Loader) resolveRefPath(ref string, path *url.URL) (*url.URL, error return path, nil } - // When a custom ReadFromURIFunc is installed, defer the external-ref decision to it. + // IsExternalRefsAllowed is enforced here only when no custom ReadFromURIFunc + // is installed; otherwise the custom func owns the access policy (see the + // SECURITY note on the ReadFromURIFunc field). if loader.ReadFromURIFunc == nil { if err := loader.allowsExternalRefs(ref); err != nil { return nil, err @@ -487,7 +500,7 @@ func (loader *Loader) resolveComponent(doc *T, ref string, path *url.URL, resolv reflect.ValueOf(resolved).Elem().Set(reflect.ValueOf(cursor).Elem()) return componentDoc, componentPath, nil - case reflect.TypeOf(cursor) == reflect.TypeOf(map[string]any{}): + case reflect.TypeOf(cursor) == reflect.TypeFor[map[string]any](): codec := func(got, expect any) error { enc, err := json.Marshal(got) if err != nil { @@ -565,7 +578,7 @@ func drillIntoField(cursor any, fieldName string) (any, error) { for i := range val.NumField() { hasFields = true if yamlTag := val.Type().Field(i).Tag.Get("yaml"); yamlTag != "-" { - if tagName := strings.Split(yamlTag, ",")[0]; tagName != "" { + if tagName, _, _ := strings.Cut(yamlTag, ","); tagName != "" { if fieldName == tagName { return val.Field(i).Interface(), nil } diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go b/vendor/github.com/getkin/kin-openapi/openapi3/refs.go index ace377e..2a4066f 100644 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go +++ b/vendor/github.com/getkin/kin-openapi/openapi3/refs.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/go-openapi/jsonpointer" - "github.com/perimeterx/marshmallow" ) // CallbackRef represents either a Callback or a $ref to a Callback. @@ -69,7 +68,10 @@ func (x CallbackRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets CallbackRef to a copy of data. func (x *CallbackRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -208,7 +210,10 @@ func (x ExampleRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets ExampleRef to a copy of data. func (x *ExampleRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -347,7 +352,10 @@ func (x HeaderRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets HeaderRef to a copy of data. func (x *HeaderRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -486,7 +494,10 @@ func (x LinkRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets LinkRef to a copy of data. func (x *LinkRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -625,7 +636,10 @@ func (x ParameterRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets ParameterRef to a copy of data. func (x *ParameterRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -764,7 +778,10 @@ func (x RequestBodyRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets RequestBodyRef to a copy of data. func (x *RequestBodyRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -903,7 +920,10 @@ func (x ResponseRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets ResponseRef to a copy of data. func (x *ResponseRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -1045,7 +1065,10 @@ func (x SchemaRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets SchemaRef to a copy of data. func (x *SchemaRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { @@ -1202,7 +1225,10 @@ func (x SecuritySchemeRef) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets SecuritySchemeRef to a copy of data. func (x *SecuritySchemeRef) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl b/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl index 99dd94a..fdff1c9 100644 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl +++ b/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl @@ -8,7 +8,6 @@ import ( "strings" "github.com/go-openapi/jsonpointer" - "github.com/perimeterx/marshmallow" ) {{ range $type := .Types }} // {{ $type.Name }}Ref represents either a {{ $type.Name }} or a $ref to a {{ $type.Name }}. @@ -74,7 +73,10 @@ func (x {{ $type.Name }}Ref) MarshalJSON() ([]byte, error) { // UnmarshalJSON sets {{ $type.Name }}Ref to a copy of data. func (x *{{ $type.Name }}Ref) UnmarshalJSON(data []byte) error { var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { + if err := json.Unmarshal(data, &refOnly); err == nil && refOnly.Ref != "" { + extra := map[string]any{} + _ = json.Unmarshal(data, &extra) + delete(extra, "$ref") x.Ref = refOnly.Ref x.Origin = refOnly.Origin if len(extra) != 0 { diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema.go index e44fe81..1f5eebd 100644 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go +++ b/vendor/github.com/getkin/kin-openapi/openapi3/schema.go @@ -17,8 +17,6 @@ import ( "unicode/utf16" "github.com/go-openapi/jsonpointer" - "github.com/mohae/deepcopy" - "github.com/woodsbury/decimal128" ) const ( @@ -2202,7 +2200,7 @@ func (schema *Schema) visitXOFOperations(settings *schemaValidationSettings, val // make a deep copy to protect origin value from being injected default value that defined in mismatched oneOf schema if settings.asreq || settings.asrep { - tempValue = deepcopy.Copy(value) + tempValue = deepCopyJSONValue(value) } if err := v.visitJSON(settings, tempValue); err != nil { @@ -2265,7 +2263,7 @@ func (schema *Schema) visitXOFOperations(settings *schemaValidationSettings, val // make a deep copy to protect origin value from being injected default value that defined in mismatched anyOf schema if settings.asreq || settings.asrep { - tempValue = deepcopy.Copy(value) + tempValue = deepCopyJSONValue(value) } if err := v.visitJSON(settings, tempValue); err == nil { ok = true @@ -2553,10 +2551,10 @@ func (schema *Schema) visitJSONNumber(settings *schemaValidationSettings, value if v := schema.MultipleOf; v != nil { // "A numeric instance is valid only if division by this keyword's // value results in an integer." - numParsed, _ := decimal128.Parse(fmt.Sprintf("%.10f", value)) - denParsed, _ := decimal128.Parse(fmt.Sprintf("%.10f", *v)) - _, remainder := numParsed.QuoRem(denParsed) - if !remainder.IsZero() { + numRat, denRat := &big.Rat{}, &big.Rat{} + numRat.SetString(fmt.Sprintf("%.10f", value)) + denRat.SetString(fmt.Sprintf("%.10f", *v)) + if !(&big.Rat{}).Quo(numRat, denRat).IsInt() { if settings.failfast { return errSchema } @@ -3085,9 +3083,9 @@ func (err *SchemaError) Error() string { if len(err.reversePath) > 0 { buf.WriteString(`Error at "`) reversePath := err.reversePath - for i := len(reversePath) - 1; i >= 0; i-- { + for _, r := range slices.Backward(reversePath) { buf.WriteByte('/') - buf.WriteString(reversePath[i]) + buf.WriteString(r) } buf.WriteString(`": `) } @@ -3158,6 +3156,25 @@ func unsupportedFormat(format string) error { return fmt.Errorf("unsupported 'format' value %q", format) } +func deepCopyJSONValue(v any) any { + switch v := v.(type) { + case map[string]any: + cp := make(map[string]any, len(v)) + for k, val := range v { + cp[k] = deepCopyJSONValue(val) + } + return cp + case []any: + cp := make([]any, len(v)) + for i, val := range v { + cp[i] = deepCopyJSONValue(val) + } + return cp + default: + return v // string, float64, bool, nil — all immutable + } +} + // UnmarshalJSON sets Schemas to a copy of data. func (schemas *Schemas) UnmarshalJSON(data []byte) (err error) { *schemas, err = unmarshalStringMapP[SchemaRef](data) diff --git a/vendor/github.com/go-openapi/jsonpointer/.cliff.toml b/vendor/github.com/go-openapi/jsonpointer/.cliff.toml new file mode 100644 index 0000000..702629f --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.cliff.toml @@ -0,0 +1,181 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +header = """ +""" + +footer = """ + +----- + +**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** + +[![License][license-badge]][license-url] + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" + +body = """ +{%- if version %} +## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} +{%- else %} +## [unreleased] +{%- endif %} +{%- if message %} + {%- raw %}\n{% endraw %} +{{ message }} + {%- raw %}\n{% endraw %} +{%- endif %} +{%- if version %} + {%- if previous.version %} + +**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> + {%- endif %} +{%- else %} + {%- raw %}\n{% endraw %} +{%- endif %} + +{%- if statistics %}{% if statistics.commit_count %} + {%- raw %}\n{% endraw %} +{{ statistics.commit_count }} commits in this release. + {%- raw %}\n{% endraw %} +{%- endif %}{% endif %} +----- + +{%- for group, commits in commits | group_by(attribute="group") %} + {%- raw %}\n{% endraw %} +### {{ group | upper_first }} + {%- raw %}\n{% endraw %} + {%- for commit in commits %} + {%- if commit.remote.pr_title %} + {%- set commit_message = commit.remote.pr_title %} + {%- else %} + {%- set commit_message = commit.message %} + {%- endif %} +* {{ commit_message | split(pat="\n") | first | trim }} + {%- if commit.remote.username %} +{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) + {%- endif %} + {%- if commit.remote.pr_number %} +{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) + {%- endif %} +{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) + {%- endfor %} +{%- endfor %} + +{%- if github %} +{%- raw %}\n{% endraw -%} + {%- set all_contributors = github.contributors | length %} + {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} +----- + +### People who contributed to this release + {% endif %} + {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) + {%- endif %} + {%- endfor %} + + {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} +----- + {%- raw %}\n{% endraw %} + +### New Contributors + {%- endif %} + + {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} + in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endif %} + +{%- raw %}\n{% endraw %} + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true +# Render body even when there are no releases to process. +render_always = true +# An array of regex based postprocessors to modify the changelog. +postprocessors = [ + # Replace the placeholder with a URL. + #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, +] +# output file path +# output = "test.md" + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = false +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# Require all commits to be conventional. +# Takes precedence over filter_unconventional. +require_conventional = false +# Split commits on newlines, treating each line as an individual commit. +split_commits = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit message using https://github.com/crate-ci/typos. + # If the spelling is incorrect, it will be fixed automatically. + #{ pattern = '.*', replace_command = 'typos --write-changes -' } +] +# Prevent commits that are breaking from being excluded by commit parsers. +protect_breaking_commits = false +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, + { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, + { field = "author.name", pattern = "dependabot*", group = "Updates" }, + { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, + { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, + { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, + { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, + { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, + { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, + { message = "^test", group = "Testing" }, + { message = "(^fix)|(panic)", group = "Fixed bugs" }, + { message = "(^refact)|(rework)", group = "Refactor" }, + { message = "(^[Pp]erf)|(performance)", group = "Performance" }, + { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, + { message = "^[Rr]evert", group = "Reverted changes" }, + { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, + { message = ".*", group = "Other" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# An array of link parsers for extracting external references, and turning them into URLs, using regex. +link_parsers = [] +# Include only the tags that belong to the current branch. +use_branch_tags = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order releases topologically instead of chronologically. +topo_order_commits = true +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" +# Process submodules commits +recurse_submodules = false + +#[remote.github] +#owner = "go-openapi" diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore index 769c244..885dc27 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ b/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -1 +1,6 @@ -secrets.yml +*.out +*.cov +.idea +.env +.mcp.json +.claude/ diff --git a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index 22f8d21..dc7c960 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -1,61 +1,67 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - maligned - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - depguard - funlen - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - exhaustruct - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest - - tparallel + - recvcheck + - testpackage - thelper - - ifshort - - exhaustruct + - tparallel - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + cyclop: + max-complexity: 20 + gocyclo: + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md index 9322b06..bac878f 100644 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md new file mode 100644 index 0000000..2ebebed --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -0,0 +1,24 @@ +# Contributors + +- Repository: ['go-openapi/jsonpointer'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 12 | 101 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 54 | | +| @casualjim | 33 | | +| @magodo | 3 | | +| @youyuanwu | 3 | | +| @gaiaz-iusipov | 1 | | +| @gbjk | 1 | | +| @gordallott | 1 | | +| @ianlancetaylor | 1 | | +| @mfleader | 1 | | +| @Neo2308 | 1 | | +| @olivierlemasle | 1 | | +| @testwill | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE index d645695..261eeb9 100644 --- a/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ b/vendor/github.com/go-openapi/jsonpointer/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/vendor/github.com/go-openapi/jsonpointer/NOTICE b/vendor/github.com/go-openapi/jsonpointer/NOTICE new file mode 100644 index 0000000..f3b5193 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/NOTICE @@ -0,0 +1,39 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed 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. diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md index 0108f1d..c52803e 100644 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/vendor/github.com/go-openapi/jsonpointer/README.md @@ -1,19 +1,158 @@ -# gojsonpointer [![Build Status](https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonpointer/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) +# jsonpointer -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer.svg)](https://pkg.go.dev/github.com/go-openapi/jsonpointer) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonpointer)](https://goreportcard.com/report/github.com/go-openapi/jsonpointer) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -An implementation of JSON Pointer - Go language +--- + +An implementation of JSON Pointer for golang, which supports go `struct`. + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + * our venerable Slack channel remains open, and will be eventually discontinued on **2026-03-31** + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +Or join our Slack channel: [![Slack Channel][slack-logo]![slack-badge]][slack-url] ## Status -Completed YES -Tested YES +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/jsonpointer +``` + +## Basic usage + +See also some [examples](./examples_test.go) + +### Retrieving a value + +```go + import ( + "github.com/go-openapi/jsonpointer" + ) + + + var doc any + + ... + + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + value, kind, err := pointer.Get(doc) + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } + + ... +``` + +### Setting a value + +```go + ... + var doc any + ... + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + doc, err = p.Set(doc, "value") + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } +``` + +## Change log + +See ## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. + + +also known as [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Limitations + +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, +the reference token MUST contain either...' is not implemented. + +That is because our implementation of the JSON pointer only supports explicit references to array elements: +the provision in the spec to resolve non-existent members as "the last element in the array", +using the special trailing character "-" is not implemented. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/jsonpointer/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/jsonpointer +[vuln-scan-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonpointer +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonpointer +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonpointer +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonpointer + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonpointer +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/twZ9BwT3 + + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/jsonpointer/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonpointer +[goversion-url]: https://github.com/go-openapi/jsonpointer/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonpointer +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonpointer/latest diff --git a/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md new file mode 100644 index 0000000..1fea2c5 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability diff --git a/vendor/github.com/go-openapi/jsonpointer/errors.go b/vendor/github.com/go-openapi/jsonpointer/errors.go new file mode 100644 index 0000000..8c50dde --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/errors.go @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonpointer + +import "fmt" + +type pointerError string + +func (e pointerError) Error() string { + return string(e) +} + +const ( + // ErrPointer is a sentinel error raised by all errors from this package. + ErrPointer pointerError = "JSON pointer error" + + // ErrInvalidStart states that a JSON pointer must start with a separator ("/"). + ErrInvalidStart pointerError = `JSON pointer must be empty or start with a "` + pointerSeparator + + // ErrUnsupportedValueType indicates that a value of the wrong type is being set. + ErrUnsupportedValueType pointerError = "only structs, pointers, maps and slices are supported for setting values" +) + +func errNoKey(key string) error { + return fmt.Errorf("object has no key %q: %w", key, ErrPointer) +} + +func errOutOfBounds(length, idx int) error { + return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", length-1, idx, ErrPointer) +} + +func errInvalidReference(token string) error { + return fmt.Errorf("invalid token reference %q: %w", token, ErrPointer) +} diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go index d970c7c..7df49af 100644 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -1,28 +1,7 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 +// Package jsonpointer provides a golang implementation for json pointers. package jsonpointer import ( @@ -33,81 +12,281 @@ import ( "strconv" "strings" - "github.com/go-openapi/swag" + "github.com/go-openapi/swag/jsonname" ) const ( emptyPointer = `` pointerSeparator = `/` - - invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator - notFound = `Can't find the pointer in the document` ) -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONPointable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONPointable interface { - JSONLookup(string) (any, error) + // JSONLookup returns a value pointed at this (unescaped) key. + JSONLookup(key string) (any, error) } -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONSetable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONSetable interface { - JSONSet(string, any) error + // JSONSet sets the value pointed at the (unescaped) key. + JSONSet(key string, value any) error } -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { +// Pointer is a representation of a json pointer. +// +// Use [Pointer.Get] to retrieve a value or [Pointer.Set] to set a value. +// +// It works with any go type interpreted as a JSON document, which means: +// +// - if a type implements [JSONPointable], its [JSONPointable.JSONLookup] method is used to resolve [Pointer.Get] +// - if a type implements [JSONSetable], its [JSONPointable.JSONSet] method is used to resolve [Pointer.Set] +// - a go map[K]V is interpreted as an object, with type K assignable to a string +// - a go slice []T is interpreted as an array +// - a go struct is interpreted as an object, with exported fields interpreted as keys +// - promoted fields from an embedded struct are traversed +// - scalars (e.g. int, float64 ...), channels, functions and go arrays cannot be traversed +// +// For struct s resolved by reflection, key mappings honor the conventional struct tag `json`. +// +// Fields that do not specify a `json` tag, or specify an empty one, or are tagged as `json:"-"` are ignored. +// +// # Limitations +// +// - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored. +// - anonymous fields are not traversed if untagged +type Pointer struct { + referenceTokens []string +} +// New creates a new json pointer from its string representation. +func New(jsonPointerString string) (Pointer, error) { var p Pointer err := p.parse(jsonPointerString) + return p, err +} +// Get uses the pointer to retrieve a value from a JSON document. +// +// It returns the value with its type as a [reflect.Kind] or an error. +func (p *Pointer) Get(document any) (any, reflect.Kind, error) { + return p.get(document, jsonname.DefaultJSONNameProvider) } -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string +// Set uses the pointer to set a value from a data type +// that represent a JSON document. +// +// It returns the updated document. +func (p *Pointer) Set(document any, value any) (any, error) { + return document, p.set(document, value, jsonname.DefaultJSONNameProvider) } -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { +// DecodedTokens returns the decoded (unescaped) tokens of this JSON pointer. +func (p *Pointer) DecodedTokens() []string { + result := make([]string, 0, len(p.referenceTokens)) + for _, token := range p.referenceTokens { + result = append(result, Unescape(token)) + } - var err error + return result +} - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.New(invalidStart) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) - } +// IsEmpty returns true if this is an empty json pointer. +// +// This indicates that it points to the root document. +func (p *Pointer) IsEmpty() bool { + return len(p.referenceTokens) == 0 +} + +// String representation of a pointer. +func (p *Pointer) String() string { + if len(p.referenceTokens) == 0 { + return emptyPointer } - return err + return pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) } -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document any) (any, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) +func (p *Pointer) Offset(document string) (int64, error) { + dec := json.NewDecoder(strings.NewReader(document)) + var offset int64 + for _, ttk := range p.DecodedTokens() { + tk, err := dec.Token() + if err != nil { + return 0, err + } + switch tk := tk.(type) { + case json.Delim: + switch tk { + case '{': + offset, err = offsetSingleObject(dec, ttk) + if err != nil { + return 0, err + } + case '[': + offset, err = offsetSingleArray(dec, ttk) + if err != nil { + return 0, err + } + default: + return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) + } + default: + return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) + } + } + return offset, nil } -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document any, value any) (any, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) +// "Constructor", parses the given string JSON pointer. +func (p *Pointer) parse(jsonPointerString string) error { + if jsonPointerString == emptyPointer { + return nil + } + + if !strings.HasPrefix(jsonPointerString, pointerSeparator) { + // non empty pointer must start with "/" + return errors.Join(ErrInvalidStart, ErrPointer) + } + + referenceTokens := strings.Split(jsonPointerString, pointerSeparator) + p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) + + return nil } -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) get(node any, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + kind := reflect.Invalid + + // full document when empty + if len(p.referenceTokens) == 0 { + return node, kind, nil + } + + for _, token := range p.referenceTokens { + decodedToken := Unescape(token) + + r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + if err != nil { + return nil, knd, err + } + node = r + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + return node, kind, nil } -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document any, decodedToken string, value any) (any, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) set(node, data any, nameProvider *jsonname.NameProvider) error { + knd := reflect.ValueOf(node).Kind() + + if knd != reflect.Pointer && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return errors.Join( + fmt.Errorf("unexpected type: %T", node), //nolint:err113 // err wrapping is carried out by errors.Join, not fmt.Errorf. + ErrUnsupportedValueType, + ErrPointer, + ) + } + + l := len(p.referenceTokens) + + // full document when empty + if l == 0 { + return nil + } + + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + var decodedToken string + lastIndex := l - 1 + + if lastIndex > 0 { // skip if we only have one token in pointer + for _, token := range p.referenceTokens[:lastIndex] { + decodedToken = Unescape(token) + next, err := p.resolveNodeForToken(node, decodedToken, nameProvider) + if err != nil { + return err + } + + node = next + } + } + + // last token + decodedToken = Unescape(p.referenceTokens[lastIndex]) + + return setSingleImpl(node, data, decodedToken, nameProvider) +} + +func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvider *jsonname.NameProvider) (next any, err error) { + // check for nil during traversal + if isNil(node) { + return nil, fmt.Errorf("cannot traverse through nil value at %q: %w", decodedToken, ErrPointer) + } + + pointable, ok := node.(JSONPointable) + if ok { + r, err := pointable.JSONLookup(decodedToken) + if err != nil { + return nil, err + } + + fld := reflect.ValueOf(r) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Pointer { + return fld.Addr().Interface(), nil + } + + return r, nil + } + + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) + } + + return typeFromValue(rValue.FieldByName(nm)), nil + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if !mv.IsValid() { + return nil, errNoKey(decodedToken) + } + + return typeFromValue(mv), nil + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, errors.Join(err, ErrPointer) + } + + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, errOutOfBounds(sLength, tokenIndex) + } + + return typeFromValue(rValue.Index(tokenIndex)), nil + + default: + return nil, errInvalidReference(decodedToken) + } } func isNil(input any) bool { @@ -116,19 +295,37 @@ func isNil(input any) bool { } kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: + switch kind { + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan: return reflect.ValueOf(input).IsNil() default: return false } } -func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { +func typeFromValue(v reflect.Value) any { + if v.CanAddr() && v.Kind() != reflect.Interface && v.Kind() != reflect.Map && v.Kind() != reflect.Slice && v.Kind() != reflect.Pointer { + return v.Addr().Interface() + } + + return v.Interface() +} + +// GetForToken gets a value for a json pointer token 1 level deep. +func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { + return getSingleImpl(document, decodedToken, jsonname.DefaultJSONNameProvider) +} + +// SetForToken sets a value for a json pointer token 1 level deep. +func SetForToken(document any, decodedToken string, value any) (any, error) { + return document, setSingleImpl(document, value, decodedToken, jsonname.DefaultJSONNameProvider) +} + +func getSingleImpl(node any, decodedToken string, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { rValue := reflect.Indirect(reflect.ValueOf(node)) kind := rValue.Kind() if isNil(node) { - return nil, kind, fmt.Errorf("nil value has not field %q", decodedToken) + return nil, kind, fmt.Errorf("nil value has no field %q: %w", decodedToken, ErrPointer) } switch typed := node.(type) { @@ -142,13 +339,15 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide return getSingleImpl(*typed, decodedToken, nameProvider) } - switch kind { //nolint:exhaustive + switch kind { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { - return nil, kind, fmt.Errorf("object has no field %q", decodedToken) + return nil, kind, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) + return fld.Interface(), kind, nil case reflect.Map: @@ -158,259 +357,100 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide if mv.IsValid() { return mv.Interface(), kind, nil } - return nil, kind, fmt.Errorf("object has no key %q", decodedToken) + + return nil, kind, errNoKey(decodedToken) case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return nil, kind, err + return nil, kind, errors.Join(err, ErrPointer) } sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) + return nil, kind, errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) return elem.Interface(), kind, nil default: - return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) + return nil, kind, errInvalidReference(decodedToken) } - } -func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) +func setSingleImpl(node, data any, decodedToken string, nameProvider *jsonname.NameProvider) error { + // check for nil to prevent panic when calling rValue.Type() + if isNil(node) { + return fmt.Errorf("cannot set field %q on nil value: %w", decodedToken, ErrPointer) + } - if ns, ok := node.(JSONSetable); ok { // pointer impl + if ns, ok := node.(JSONSetable); ok { return ns.JSONSet(decodedToken, data) } - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } + rValue := reflect.Indirect(reflect.ValueOf(node)) - switch rValue.Kind() { //nolint:exhaustive + switch rValue.Kind() { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { - return fmt.Errorf("object has no field %q", decodedToken) + return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) + if !fld.CanSet() { + return fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer) } + + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := fld.Type() + + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer) + } + + fld.Set(value) + return nil case reflect.Map: kv := reflect.ValueOf(decodedToken) rValue.SetMapIndex(kv, reflect.ValueOf(data)) + return nil case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return err + return errors.Join(err, ErrPointer) } + sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + return errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) if !elem.CanSet() { - return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) + return fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer) } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } -} + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := elem.Type() -func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer) } - node = r - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - return node, kind, nil -} - -func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error { - knd := reflect.ValueOf(node).Kind() - - if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { - return errors.New("only structs, pointers, maps and slices are supported for setting values") - } + elem.Set(value) - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q", decodedToken) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - return pointerString -} - -func (p *Pointer) Offset(document string) (int64, error) { - dec := json.NewDecoder(strings.NewReader(document)) - var offset int64 - for _, ttk := range p.DecodedTokens() { - tk, err := dec.Token() - if err != nil { - return 0, err - } - switch tk := tk.(type) { - case json.Delim: - switch tk { - case '{': - offset, err = offsetSingleObject(dec, ttk) - if err != nil { - return 0, err - } - case '[': - offset, err = offsetSingleArray(dec, ttk) - if err != nil { - return 0, err - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } + default: + return errInvalidReference(decodedToken) } - return offset, nil } func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { @@ -437,16 +477,17 @@ func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { return offset, nil } default: - return 0, fmt.Errorf("invalid token %#v", tk) + return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) } } - return 0, fmt.Errorf("token reference %q not found", decodedToken) + + return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { idx, err := strconv.Atoi(decodedToken) if err != nil { - return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err) + return 0, fmt.Errorf("token reference %q is not a number: %w: %w", decodedToken, err, ErrPointer) } var i int for i = 0; i < idx && dec.More(); i++ { @@ -470,12 +511,14 @@ func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { } if !dec.More() { - return 0, fmt.Errorf("token reference %q not found", decodedToken) + return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } + return dec.InputOffset(), nil } // drainSingle drains a single level of object or array. +// // The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed. func drainSingle(dec *json.Decoder) error { for dec.More() { @@ -497,14 +540,15 @@ func drainSingle(dec *json.Decoder) error { } } - // Consumes the ending delim + // consumes the ending delim if _, err := dec.Token(); err != nil { return err } + return nil } -// Specific JSON pointer encoding here +// JSON pointer encoding: // ~0 => ~ // ~1 => / // ... and vice versa @@ -516,16 +560,24 @@ const ( decRefTok1 = `/` ) -// Unescape unescapes a json pointer reference token string to the original representation +var ( + encRefTokReplacer = strings.NewReplacer(encRefTok1, decRefTok1, encRefTok0, decRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global + decRefTokReplacer = strings.NewReplacer(decRefTok1, encRefTok1, decRefTok0, encRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global +) + +// Unescape unescapes a json pointer reference token string to the original representation. func Unescape(token string) string { - step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1) - step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0) - return step2 + return encRefTokReplacer.Replace(token) } -// Escape escapes a pointer reference token string +// Escape escapes a pointer reference token string. +// +// The JSONPointer specification defines "/" as a separator and "~" as an escape prefix. +// +// Keys containing such characters are escaped with the following rules: +// +// - "~" is escaped as "~0" +// - "/" is escaped as "~1" func Escape(token string) string { - step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0) - step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1) - return step2 + return decRefTokReplacer.Replace(token) } diff --git a/vendor/github.com/go-openapi/swag/.editorconfig b/vendor/github.com/go-openapi/swag/.editorconfig deleted file mode 100644 index 3152da6..0000000 --- a/vendor/github.com/go-openapi/swag/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/swag/.gitattributes b/vendor/github.com/go-openapi/swag/.gitattributes deleted file mode 100644 index 49ad527..0000000 --- a/vendor/github.com/go-openapi/swag/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# gofmt always uses LF, whereas Git uses CRLF on Windows. -*.go text eol=lf diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore deleted file mode 100644 index c4b1b64..0000000 --- a/vendor/github.com/go-openapi/swag/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -secrets.yml -vendor -Godeps -.idea -*.out diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml deleted file mode 100644 index 80e2be0..0000000 --- a/vendor/github.com/go-openapi/swag/.golangci.yml +++ /dev/null @@ -1,60 +0,0 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 3 - min-occurrences: 3 - -linters: - enable-all: true - disable: - - maligned - - lll - - gochecknoinits - - gochecknoglobals - - funlen - - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt - - paralleltest - - tparallel - - thelper - - ifshort - - exhaustruct - - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase diff --git a/vendor/github.com/go-openapi/swag/BENCHMARK.md b/vendor/github.com/go-openapi/swag/BENCHMARK.md deleted file mode 100644 index e7f28ed..0000000 --- a/vendor/github.com/go-openapi/swag/BENCHMARK.md +++ /dev/null @@ -1,52 +0,0 @@ -# Benchmarks - -## Name mangling utilities - -```bash -go test -bench XXX -run XXX -benchtime 30s -``` - -### Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz -BenchmarkToXXXName/ToGoName-4 862623 44101 ns/op 10450 B/op 732 allocs/op -BenchmarkToXXXName/ToVarName-4 853656 40728 ns/op 10468 B/op 734 allocs/op -BenchmarkToXXXName/ToFileName-4 1268312 27813 ns/op 9785 B/op 617 allocs/op -BenchmarkToXXXName/ToCommandName-4 1276322 27903 ns/op 9785 B/op 617 allocs/op -BenchmarkToXXXName/ToHumanNameLower-4 895334 40354 ns/op 10472 B/op 731 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-4 882441 40678 ns/op 10566 B/op 749 allocs/op -``` - -### Benchmarks after PR #79 - -~ x10 performance improvement and ~ /100 memory allocations. - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz -BenchmarkToXXXName/ToGoName-4 9595830 3991 ns/op 42 B/op 5 allocs/op -BenchmarkToXXXName/ToVarName-4 9194276 3984 ns/op 62 B/op 7 allocs/op -BenchmarkToXXXName/ToFileName-4 17002711 2123 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToCommandName-4 16772926 2111 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToHumanNameLower-4 9788331 3749 ns/op 92 B/op 6 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-4 9188260 3941 ns/op 104 B/op 6 allocs/op -``` - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: AMD Ryzen 7 5800X 8-Core Processor -BenchmarkToXXXName/ToGoName-16 18527378 1972 ns/op 42 B/op 5 allocs/op -BenchmarkToXXXName/ToVarName-16 15552692 2093 ns/op 62 B/op 7 allocs/op -BenchmarkToXXXName/ToFileName-16 32161176 1117 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToCommandName-16 32256634 1137 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToHumanNameLower-16 18599661 1946 ns/op 92 B/op 6 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-16 17581353 2054 ns/op 105 B/op 6 allocs/op -``` diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b06..0000000 --- a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md deleted file mode 100644 index a729222..0000000 --- a/vendor/github.com/go-openapi/swag/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) - -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/swag.svg)](https://pkg.go.dev/github.com/go-openapi/swag) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) - -Contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - -* convert between value and pointers for builtin types -* convert from string to builtin types (wraps strconv) -* fast json concatenation -* search in path -* load from file or http -* name mangling - - -This repo has only few dependencies outside of the standard library: - -* YAML utilities depend on `gopkg.in/yaml.v3` -* `github.com/mailru/easyjson v0.7.7` diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index fc085ae..0000000 --- a/vendor/github.com/go-openapi/swag/convert.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "math" - "strconv" - "strings" -) - -// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER -const ( - maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 - minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 - epsilon float64 = 1e-9 -) - -// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive -func IsFloat64AJSONInteger(f float64) bool { - if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { - return false - } - fa := math.Abs(f) - g := float64(uint64(f)) - ga := math.Abs(g) - - diff := math.Abs(f - g) - - // more info: https://floating-point-gui.de/errors/comparison/#look-out-for-edge-cases - switch { - case f == g: // best case - return true - case f == float64(int64(f)) || f == float64(uint64(f)): // optimistic case - return true - case f == 0 || g == 0 || diff < math.SmallestNonzeroFloat64: // very close to 0 values - return diff < (epsilon * math.SmallestNonzeroFloat64) - } - // check the relative error - return diff/math.Min(fa+ga, math.MaxFloat64) < epsilon -} - -var evaluatesAsTrue map[string]struct{} - -func init() { - evaluatesAsTrue = map[string]struct{}{ - "true": {}, - "1": {}, - "yes": {}, - "ok": {}, - "y": {}, - "on": {}, - "selected": {}, - "checked": {}, - "t": {}, - "enabled": {}, - } -} - -// ConvertBool turn a string into a boolean -func ConvertBool(str string) (bool, error) { - _, ok := evaluatesAsTrue[strings.ToLower(str)] - return ok, nil -} - -// ConvertFloat32 turn a string into a float32 -func ConvertFloat32(str string) (float32, error) { - f, err := strconv.ParseFloat(str, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// ConvertFloat64 turn a string into a float64 -func ConvertFloat64(str string) (float64, error) { - return strconv.ParseFloat(str, 64) -} - -// ConvertInt8 turn a string into an int8 -func ConvertInt8(str string) (int8, error) { - i, err := strconv.ParseInt(str, 10, 8) - if err != nil { - return 0, err - } - return int8(i), nil -} - -// ConvertInt16 turn a string into an int16 -func ConvertInt16(str string) (int16, error) { - i, err := strconv.ParseInt(str, 10, 16) - if err != nil { - return 0, err - } - return int16(i), nil -} - -// ConvertInt32 turn a string into an int32 -func ConvertInt32(str string) (int32, error) { - i, err := strconv.ParseInt(str, 10, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// ConvertInt64 turn a string into an int64 -func ConvertInt64(str string) (int64, error) { - return strconv.ParseInt(str, 10, 64) -} - -// ConvertUint8 turn a string into an uint8 -func ConvertUint8(str string) (uint8, error) { - i, err := strconv.ParseUint(str, 10, 8) - if err != nil { - return 0, err - } - return uint8(i), nil -} - -// ConvertUint16 turn a string into an uint16 -func ConvertUint16(str string) (uint16, error) { - i, err := strconv.ParseUint(str, 10, 16) - if err != nil { - return 0, err - } - return uint16(i), nil -} - -// ConvertUint32 turn a string into an uint32 -func ConvertUint32(str string) (uint32, error) { - i, err := strconv.ParseUint(str, 10, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// ConvertUint64 turn a string into an uint64 -func ConvertUint64(str string) (uint64, error) { - return strconv.ParseUint(str, 10, 64) -} - -// FormatBool turns a boolean into a string -func FormatBool(value bool) string { - return strconv.FormatBool(value) -} - -// FormatFloat32 turns a float32 into a string -func FormatFloat32(value float32) string { - return strconv.FormatFloat(float64(value), 'f', -1, 32) -} - -// FormatFloat64 turns a float64 into a string -func FormatFloat64(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// FormatInt8 turns an int8 into a string -func FormatInt8(value int8) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt16 turns an int16 into a string -func FormatInt16(value int16) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt32 turns an int32 into a string -func FormatInt32(value int32) string { - return strconv.Itoa(int(value)) -} - -// FormatInt64 turns an int64 into a string -func FormatInt64(value int64) string { - return strconv.FormatInt(value, 10) -} - -// FormatUint8 turns an uint8 into a string -func FormatUint8(value uint8) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint16 turns an uint16 into a string -func FormatUint16(value uint16) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint32 turns an uint32 into a string -func FormatUint32(value uint32) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint64 turns an uint64 into a string -func FormatUint64(value uint64) string { - return strconv.FormatUint(value, 10) -} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c49cc47..0000000 --- a/vendor/github.com/go-openapi/swag/convert_types.go +++ /dev/null @@ -1,730 +0,0 @@ -package swag - -import "time" - -// This file was taken from the aws go sdk - -// String returns a pointer to of the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to of the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to of the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to of the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int32 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int32 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to of the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint16 returns a pointer to of the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Value returns the value of the uint16 pointer passed in or -// 0 if the pointer is nil. -func Uint16Value(v *uint16) uint16 { - if v != nil { - return *v - } - - return 0 -} - -// Uint16Slice converts a slice of uint16 values into a slice of -// uint16 pointers -func Uint16Slice(src []uint16) []*uint16 { - dst := make([]*uint16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Uint16ValueSlice converts a slice of uint16 pointers into a slice of -// uint16 values -func Uint16ValueSlice(src []*uint16) []uint16 { - dst := make([]uint16, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Uint16Map converts a string map of uint16 values into a string -// map of uint16 pointers -func Uint16Map(src map[string]uint16) map[string]*uint16 { - dst := make(map[string]*uint16) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Uint16ValueMap converts a string map of uint16 pointers into a string -// map of uint16 values -func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { - dst := make(map[string]uint16) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Uint returns a pointer to of the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pointer passed in or -// 0 if the pointer is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values into a slice of -// uint pointers -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pointers into a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values into a string -// map of uint pointers -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pointers into a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pointer to of the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint32 pointer passed in or -// 0 if the pointer is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint32 values into a slice of -// uint32 pointers -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pointers into a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values into a string -// map of uint32 pointers -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pointers into a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pointer to of the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pointer passed in or -// 0 if the pointer is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values into a slice of -// uint64 pointers -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pointers into a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values into a string -// map of uint64 pointers -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pointers into a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float32 returns a pointer to of the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Value returns the value of the float32 pointer passed in or -// 0 if the pointer is nil. -func Float32Value(v *float32) float32 { - if v != nil { - return *v - } - - return 0 -} - -// Float32Slice converts a slice of float32 values into a slice of -// float32 pointers -func Float32Slice(src []float32) []*float32 { - dst := make([]*float32, len(src)) - - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Float32ValueSlice converts a slice of float32 pointers into a slice of -// float32 values -func Float32ValueSlice(src []*float32) []float32 { - dst := make([]float32, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Float32Map converts a string map of float32 values into a string -// map of float32 pointers -func Float32Map(src map[string]float32) map[string]*float32 { - dst := make(map[string]*float32) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Float32ValueMap converts a string map of float32 pointers into a string -// map of float32 values -func Float32ValueMap(src map[string]*float32) map[string]float32 { - dst := make(map[string]float32) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Float64 returns a pointer to of the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to of the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/go-openapi/swag/doc.go b/vendor/github.com/go-openapi/swag/doc.go deleted file mode 100644 index 55094cb..0000000 --- a/vendor/github.com/go-openapi/swag/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - - - convert between value and pointers for builtin types - - convert from string to builtin types (wraps strconv) - - fast json concatenation - - search in path - - load from file or http - - name mangling - -This repo has only few dependencies outside of the standard library: - - - YAML utilities depend on gopkg.in/yaml.v2 -*/ -package swag diff --git a/vendor/github.com/go-openapi/swag/file.go b/vendor/github.com/go-openapi/swag/file.go deleted file mode 100644 index 16accc5..0000000 --- a/vendor/github.com/go-openapi/swag/file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import "mime/multipart" - -// File represents an uploaded file. -type File struct { - Data multipart.File - Header *multipart.FileHeader -} - -// Read bytes from the file -func (f *File) Read(p []byte) (n int, err error) { - return f.Data.Read(p) -} - -// Close the file -func (f *File) Close() error { - return f.Data.Close() -} diff --git a/vendor/github.com/go-openapi/swag/initialism_index.go b/vendor/github.com/go-openapi/swag/initialism_index.go deleted file mode 100644 index 20a359b..0000000 --- a/vendor/github.com/go-openapi/swag/initialism_index.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "sort" - "strings" - "sync" -) - -var ( - // commonInitialisms are common acronyms that are kept as whole uppercased words. - commonInitialisms *indexOfInitialisms - - // initialisms is a slice of sorted initialisms - initialisms []string - - // a copy of initialisms pre-baked as []rune - initialismsRunes [][]rune - initialismsUpperCased [][]rune - - isInitialism func(string) bool - - maxAllocMatches int -) - -func init() { - // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 - configuredInitialisms := map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTPS": true, - "HTTP": true, - "ID": true, - "IP": true, - "IPv4": true, - "IPv6": true, - "JSON": true, - "LHS": true, - "OAI": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, - } - - // a thread-safe index of initialisms - commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms) - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) - maxAllocMatches = maxAllocHeuristic(initialismsRunes) - - // a test function - isInitialism = commonInitialisms.isInitialism -} - -func asRunes(in []string) [][]rune { - out := make([][]rune, len(in)) - for i, initialism := range in { - out[i] = []rune(initialism) - } - - return out -} - -func asUpperCased(in []string) [][]rune { - out := make([][]rune, len(in)) - - for i, initialism := range in { - out[i] = []rune(upper(trim(initialism))) - } - - return out -} - -func maxAllocHeuristic(in [][]rune) int { - heuristic := make(map[rune]int) - for _, initialism := range in { - heuristic[initialism[0]]++ - } - - var maxAlloc int - for _, val := range heuristic { - if val > maxAlloc { - maxAlloc = val - } - } - - return maxAlloc -} - -// AddInitialisms add additional initialisms -func AddInitialisms(words ...string) { - for _, word := range words { - // commonInitialisms[upper(word)] = true - commonInitialisms.add(upper(word)) - } - // sort again - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) -} - -// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. -// Since go1.9, this may be implemented with sync.Map. -type indexOfInitialisms struct { - sortMutex *sync.Mutex - index *sync.Map -} - -func newIndexOfInitialisms() *indexOfInitialisms { - return &indexOfInitialisms{ - sortMutex: new(sync.Mutex), - index: new(sync.Map), - } -} - -func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - for k, v := range initial { - m.index.Store(k, v) - } - return m -} - -func (m *indexOfInitialisms) isInitialism(key string) bool { - _, ok := m.index.Load(key) - return ok -} - -func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { - m.index.Store(key, true) - return m -} - -func (m *indexOfInitialisms) sorted() (result []string) { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - m.index.Range(func(key, _ interface{}) bool { - k := key.(string) - result = append(result, k) - return true - }) - sort.Sort(sort.Reverse(byInitialism(result))) - return -} - -type byInitialism []string - -func (s byInitialism) Len() int { - return len(s) -} -func (s byInitialism) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byInitialism) Less(i, j int) bool { - if len(s[i]) != len(s[j]) { - return len(s[i]) < len(s[j]) - } - - return strings.Compare(s[i], s[j]) > 0 -} diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index 7e9902c..0000000 --- a/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "bytes" - "encoding/json" - "log" - "reflect" - "strings" - "sync" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -// nullJSON represents a JSON object with null type -var nullJSON = []byte("null") - -// DefaultJSONNameProvider the default cache for types -var DefaultJSONNameProvider = NewNameProvider() - -const comma = byte(',') - -var closers map[byte]byte - -func init() { - closers = map[byte]byte{ - '{': '}', - '[': ']', - } -} - -type ejMarshaler interface { - MarshalEasyJSON(w *jwriter.Writer) -} - -type ejUnmarshaler interface { - UnmarshalEasyJSON(w *jlexer.Lexer) -} - -// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaler -// so it takes the fastest option available. -func WriteJSON(data interface{}) ([]byte, error) { - if d, ok := data.(ejMarshaler); ok { - jw := new(jwriter.Writer) - d.MarshalEasyJSON(jw) - return jw.BuildBytes() - } - if d, ok := data.(json.Marshaler); ok { - return d.MarshalJSON() - } - return json.Marshal(data) -} - -// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaler -// so it takes the fastest option available -func ReadJSON(data []byte, value interface{}) error { - trimmedData := bytes.Trim(data, "\x00") - if d, ok := value.(ejUnmarshaler); ok { - jl := &jlexer.Lexer{Data: trimmedData} - d.UnmarshalEasyJSON(jl) - return jl.Error() - } - if d, ok := value.(json.Unmarshaler); ok { - return d.UnmarshalJSON(trimmedData) - } - return json.Unmarshal(trimmedData, value) -} - -// DynamicJSONToStruct converts an untyped json structure into a struct -func DynamicJSONToStruct(data interface{}, target interface{}) error { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := WriteJSON(data) - if err != nil { - return err - } - return ReadJSON(b, target) -} - -// ConcatJSON concatenates multiple json objects efficiently -func ConcatJSON(blobs ...[]byte) []byte { - if len(blobs) == 0 { - return nil - } - - last := len(blobs) - 1 - for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { - // strips trailing null objects - last-- - if last < 0 { - // there was nothing but "null"s or nil... - return nil - } - } - if last == 0 { - return blobs[0] - } - - var opening, closing byte - var idx, a int - buf := bytes.NewBuffer(nil) - - for i, b := range blobs[:last+1] { - if b == nil || bytes.Equal(b, nullJSON) { - // a null object is in the list: skip it - continue - } - if len(b) > 0 && opening == 0 { // is this an array or an object? - opening, closing = b[0], closers[b[0]] - } - - if opening != '{' && opening != '[' { - continue // don't know how to concatenate non container objects - } - - if len(b) < 3 { // yep empty but also the last one, so closing this thing - if i == last && a > 0 { - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - continue - } - - idx = 0 - if a > 0 { // we need to join with a comma for everything beyond the first non-empty item - if err := buf.WriteByte(comma); err != nil { - log.Println(err) - } - idx = 1 // this is not the first or the last so we want to drop the leading bracket - } - - if i != last { // not the last one, strip brackets - if _, err := buf.Write(b[idx : len(b)-1]); err != nil { - log.Println(err) - } - } else { // last one, strip only the leading bracket - if _, err := buf.Write(b[idx:]); err != nil { - log.Println(err) - } - } - a++ - } - // somehow it ended up being empty, so provide a default value - if buf.Len() == 0 { - if err := buf.WriteByte(opening); err != nil { - log.Println(err) - } - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - return buf.Bytes() -} - -// ToDynamicJSON turns an object into a properly JSON typed structure -func ToDynamicJSON(data interface{}) interface{} { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - var res interface{} - if err := json.Unmarshal(b, &res); err != nil { - log.Println(err) - } - return res -} - -// FromDynamicJSON turns an object into a properly JSON typed structure -func FromDynamicJSON(data, target interface{}) error { - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - return json.Unmarshal(b, target) -} - -// NameProvider represents an object capable of translating from go property names -// to json property names -// This type is thread-safe. -type NameProvider struct { - lock *sync.Mutex - index map[reflect.Type]nameIndex -} - -type nameIndex struct { - jsonNames map[string]string - goNames map[string]string -} - -// NewNameProvider creates a new name provider -func NewNameProvider() *NameProvider { - return &NameProvider{ - lock: &sync.Mutex{}, - index: make(map[reflect.Type]nameIndex), - } -} - -func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := 0; i < tpe.NumField(); i++ { - targetDes := tpe.Field(i) - - if targetDes.PkgPath != "" { // unexported - continue - } - - if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) - continue - } - - if tag := targetDes.Tag.Get("json"); tag != "" { - - parts := strings.Split(tag, ",") - if len(parts) == 0 { - continue - } - - nm := parts[0] - if nm == "-" { - continue - } - if nm == "" { // empty string means we want to use the Go name - nm = targetDes.Name - } - - idx[nm] = targetDes.Name - reverseIdx[targetDes.Name] = nm - } - } -} - -func newNameIndex(tpe reflect.Type) nameIndex { - var idx = make(map[string]string, tpe.NumField()) - var reverseIdx = make(map[string]string, tpe.NumField()) - - buildnameIndex(tpe, idx, reverseIdx) - return nameIndex{jsonNames: idx, goNames: reverseIdx} -} - -// GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { - n.lock.Lock() - defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - - res := make([]string, 0, len(names.jsonNames)) - for k := range names.jsonNames { - res = append(res, k) - } - return res -} - -// GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetJSONNameForType(tpe, name) -} - -// GetJSONNameForType gets the json name for a go property name on a given type -func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.goNames[name] - return nme, ok -} - -func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { - names := newNameIndex(tpe) - n.index[tpe] = names - return names -} - -// GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetGoNameForType(tpe, name) -} - -// GetGoNameForType gets the go name for a given type for a json property name -func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.jsonNames[name] - return nme, ok -} diff --git a/vendor/github.com/go-openapi/swag/LICENSE b/vendor/github.com/go-openapi/swag/jsonname/LICENSE similarity index 100% rename from vendor/github.com/go-openapi/swag/LICENSE rename to vendor/github.com/go-openapi/swag/jsonname/LICENSE diff --git a/vendor/github.com/go-openapi/swag/jsonname/doc.go b/vendor/github.com/go-openapi/swag/jsonname/doc.go new file mode 100644 index 0000000..79232ea --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package jsonname is a provider of json property names from go properties. +package jsonname diff --git a/vendor/github.com/go-openapi/swag/jsonname/name_provider.go b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go new file mode 100644 index 0000000..8eaf1be --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonname + +import ( + "reflect" + "strings" + "sync" +) + +// DefaultJSONNameProvider is the default cache for types. +var DefaultJSONNameProvider = NewNameProvider() + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// This type is thread-safe. +// +// See [github.com/go-openapi/jsonpointer.Pointer] for an example. +type NameProvider struct { + lock *sync.Mutex + index map[reflect.Type]nameIndex +} + +type nameIndex struct { + jsonNames map[string]string + goNames map[string]string +} + +// NewNameProvider creates a new name provider +func NewNameProvider() *NameProvider { + return &NameProvider{ + lock: &sync.Mutex{}, + index: make(map[reflect.Type]nameIndex), + } +} + +func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { + for i := 0; i < tpe.NumField(); i++ { + targetDes := tpe.Field(i) + + if targetDes.PkgPath != "" { // unexported + continue + } + + if targetDes.Anonymous { // walk embedded structures tree down first + buildnameIndex(targetDes.Type, idx, reverseIdx) + continue + } + + if tag := targetDes.Tag.Get("json"); tag != "" { + + parts := strings.Split(tag, ",") + if len(parts) == 0 { + continue + } + + nm := parts[0] + if nm == "-" { + continue + } + if nm == "" { // empty string means we want to use the Go name + nm = targetDes.Name + } + + idx[nm] = targetDes.Name + reverseIdx[targetDes.Name] = nm + } + } +} + +func newNameIndex(tpe reflect.Type) nameIndex { + var idx = make(map[string]string, tpe.NumField()) + var reverseIdx = make(map[string]string, tpe.NumField()) + + buildnameIndex(tpe, idx, reverseIdx) + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// GetJSONNames gets all the json property names for a type +func (n *NameProvider) GetJSONNames(subject any) []string { + n.lock.Lock() + defer n.lock.Unlock() + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + + res := make([]string, 0, len(names.jsonNames)) + for k := range names.jsonNames { + res = append(res, k) + } + return res +} + +// GetJSONName gets the json name for a go property name +func (n *NameProvider) GetJSONName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetJSONNameForType(tpe, name) +} + +// GetJSONNameForType gets the json name for a go property name on a given type +func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.goNames[name] + return nme, ok +} + +// GetGoName gets the go name for a json property name +func (n *NameProvider) GetGoName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetGoNameForType(tpe, name) +} + +// GetGoNameForType gets the go name for a given type for a json property name +func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.jsonNames[name] + return nme, ok +} + +func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { + names := newNameIndex(tpe) + n.index[tpe] = names + return names +} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading.go deleted file mode 100644 index 783442f..0000000 --- a/vendor/github.com/go-openapi/swag/loading.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "fmt" - "io" - "log" - "net/http" - "net/url" - "os" - "path" - "path/filepath" - "runtime" - "strings" - "time" -) - -// LoadHTTPTimeout the default timeout for load requests -var LoadHTTPTimeout = 30 * time.Second - -// LoadHTTPBasicAuthUsername the username to use when load requests require basic auth -var LoadHTTPBasicAuthUsername = "" - -// LoadHTTPBasicAuthPassword the password to use when load requests require basic auth -var LoadHTTPBasicAuthPassword = "" - -// LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests -var LoadHTTPCustomHeaders = map[string]string{} - -// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in -func LoadFromFileOrHTTP(pth string) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(pth) -} - -// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in -// timeout arg allows for per request overriding of the request timeout -func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(timeout))(pth) -} - -// LoadStrategy returns a loader function for a given path or URI. -// -// The load strategy returns the remote load for any path starting with `http`. -// So this works for any URI with a scheme `http` or `https`. -// -// The fallback strategy is to call the local loader. -// -// The local loader takes a local file system path (absolute or relative) as argument, -// or alternatively a `file://...` URI, **without host** (see also below for windows). -// -// There are a few liberalities, initially intended to be tolerant regarding the URI syntax, -// especially on windows. -// -// Before the local loader is called, the given path is transformed: -// - percent-encoded characters are unescaped -// - simple paths (e.g. `./folder/file`) are passed as-is -// - on windows, occurrences of `/` are replaced by `\`, so providing a relative path such a `folder/file` works too. -// -// For paths provided as URIs with the "file" scheme, please note that: -// - `file://` is simply stripped. -// This means that the host part of the URI is not parsed at all. -// For example, `file:///folder/file" becomes "/folder/file`, -// but `file://localhost/folder/file` becomes `localhost/folder/file` on unix systems. -// Similarly, `file://./folder/file` yields `./folder/file`. -// - on windows, `file://...` can take a host so as to specify an UNC share location. -// -// Reminder about windows-specifics: -// - `file://host/folder/file` becomes an UNC path like `\\host\folder\file` (no port specification is supported) -// - `file:///c:/folder/file` becomes `C:\folder\file` -// - `file://c:/folder/file` is tolerated (without leading `/`) and becomes `c:\folder\file` -func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { - if strings.HasPrefix(pth, "http") { - return remote - } - - return func(p string) ([]byte, error) { - upth, err := url.PathUnescape(p) - if err != nil { - return nil, err - } - - if !strings.HasPrefix(p, `file://`) { - // regular file path provided: just normalize slashes - return local(filepath.FromSlash(upth)) - } - - if runtime.GOOS != "windows" { - // crude processing: this leaves full URIs with a host with a (mostly) unexpected result - upth = strings.TrimPrefix(upth, `file://`) - - return local(filepath.FromSlash(upth)) - } - - // windows-only pre-processing of file://... URIs - - // support for canonical file URIs on windows. - u, err := url.Parse(filepath.ToSlash(upth)) - if err != nil { - return nil, err - } - - if u.Host != "" { - // assume UNC name (volume share) - // NOTE: UNC port not yet supported - - // when the "host" segment is a drive letter: - // file://C:/folder/... => C:\folder - upth = path.Clean(strings.Join([]string{u.Host, u.Path}, `/`)) - if !strings.HasSuffix(u.Host, ":") && u.Host[0] != '.' { - // tolerance: if we have a leading dot, this can't be a host - // file://host/share/folder\... ==> \\host\share\path\folder - upth = "//" + upth - } - } else { - // no host, let's figure out if this is a drive letter - upth = strings.TrimPrefix(upth, `file://`) - first, _, _ := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") - if strings.HasSuffix(first, ":") { - // drive letter in the first segment: - // file:///c:/folder/... ==> strip the leading slash - upth = strings.TrimPrefix(upth, `/`) - } - } - - return local(filepath.FromSlash(upth)) - } -} - -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { - return func(path string) ([]byte, error) { - client := &http.Client{Timeout: timeout} - req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx - if err != nil { - return nil, err - } - - if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { - req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) - } - - for key, val := range LoadHTTPCustomHeaders { - req.Header.Set(key, val) - } - - resp, err := client.Do(req) - defer func() { - if resp != nil { - if e := resp.Body.Close(); e != nil { - log.Println(e) - } - } - }() - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) - } - - return io.ReadAll(resp.Body) - } -} diff --git a/vendor/github.com/go-openapi/swag/name_lexem.go b/vendor/github.com/go-openapi/swag/name_lexem.go deleted file mode 100644 index 8bb64ac..0000000 --- a/vendor/github.com/go-openapi/swag/name_lexem.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "unicode" - "unicode/utf8" -) - -type ( - lexemKind uint8 - - nameLexem struct { - original string - matchedInitialism string - kind lexemKind - } -) - -const ( - lexemKindCasualName lexemKind = iota - lexemKindInitialismName -) - -func newInitialismNameLexem(original, matchedInitialism string) nameLexem { - return nameLexem{ - kind: lexemKindInitialismName, - original: original, - matchedInitialism: matchedInitialism, - } -} - -func newCasualNameLexem(original string) nameLexem { - return nameLexem{ - kind: lexemKindCasualName, - original: original, - } -} - -func (l nameLexem) GetUnsafeGoName() string { - if l.kind == lexemKindInitialismName { - return l.matchedInitialism - } - - var ( - first rune - rest string - ) - - for i, orig := range l.original { - if i == 0 { - first = orig - continue - } - - if i > 0 { - rest = l.original[i:] - break - } - } - - if len(l.original) > 1 { - b := poolOfBuffers.BorrowBuffer(utf8.UTFMax + len(rest)) - defer func() { - poolOfBuffers.RedeemBuffer(b) - }() - b.WriteRune(unicode.ToUpper(first)) - b.WriteString(lower(rest)) - return b.String() - } - - return l.original -} - -func (l nameLexem) GetOriginal() string { - return l.original -} - -func (l nameLexem) IsInitialism() bool { - return l.kind == lexemKindInitialismName -} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 821235f..0000000 --- a/vendor/github.com/go-openapi/swag/net.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "net" - "strconv" -) - -// SplitHostPort splits a network address into a host and a port. -// The port is -1 when there is no port to be found -func SplitHostPort(addr string) (host string, port int, err error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", -1, err - } - if p == "" { - return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} - } - - pi, err := strconv.Atoi(p) - if err != nil { - return "", -1, err - } - return h, pi, nil -} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/path.go deleted file mode 100644 index 941bd01..0000000 --- a/vendor/github.com/go-openapi/swag/path.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "os" - "path/filepath" - "runtime" - "strings" -) - -const ( - // GOPATHKey represents the env key for gopath - GOPATHKey = "GOPATH" -) - -// FindInSearchPath finds a package in a provided lists of paths -func FindInSearchPath(searchPath, pkg string) string { - pathsList := filepath.SplitList(searchPath) - for _, path := range pathsList { - if evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", pkg)); err == nil { - if _, err := os.Stat(evaluatedPath); err == nil { - return evaluatedPath - } - } - } - return "" -} - -// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT -func FindInGoSearchPath(pkg string) string { - return FindInSearchPath(FullGoSearchPath(), pkg) -} - -// FullGoSearchPath gets the search paths for finding packages -func FullGoSearchPath() string { - allPaths := os.Getenv(GOPATHKey) - if allPaths == "" { - allPaths = filepath.Join(os.Getenv("HOME"), "go") - } - if allPaths != "" { - allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":") - } else { - allPaths = runtime.GOROOT() - } - return allPaths -} diff --git a/vendor/github.com/go-openapi/swag/split.go b/vendor/github.com/go-openapi/swag/split.go deleted file mode 100644 index 274727a..0000000 --- a/vendor/github.com/go-openapi/swag/split.go +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "bytes" - "sync" - "unicode" - "unicode/utf8" -) - -type ( - splitter struct { - initialisms []string - initialismsRunes [][]rune - initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version - postSplitInitialismCheck bool - } - - splitterOption func(*splitter) - - initialismMatch struct { - body []rune - start, end int - complete bool - } - initialismMatches []initialismMatch -) - -type ( - // memory pools of temporary objects. - // - // These are used to recycle temporarily allocated objects - // and relieve the GC from undue pressure. - - matchesPool struct { - *sync.Pool - } - - buffersPool struct { - *sync.Pool - } - - lexemsPool struct { - *sync.Pool - } - - splittersPool struct { - *sync.Pool - } -) - -var ( - // poolOfMatches holds temporary slices for recycling during the initialism match process - poolOfMatches = matchesPool{ - Pool: &sync.Pool{ - New: func() any { - s := make(initialismMatches, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfBuffers = buffersPool{ - Pool: &sync.Pool{ - New: func() any { - return new(bytes.Buffer) - }, - }, - } - - poolOfLexems = lexemsPool{ - Pool: &sync.Pool{ - New: func() any { - s := make([]nameLexem, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfSplitters = splittersPool{ - Pool: &sync.Pool{ - New: func() any { - s := newSplitter() - - return &s - }, - }, - } -) - -// nameReplaceTable finds a word representation for special characters. -func nameReplaceTable(r rune) (string, bool) { - switch r { - case '@': - return "At ", true - case '&': - return "And ", true - case '|': - return "Pipe ", true - case '$': - return "Dollar ", true - case '!': - return "Bang ", true - case '-': - return "", true - case '_': - return "", true - default: - return "", false - } -} - -// split calls the splitter. -// -// Use newSplitter for more control and options -func split(str string) []string { - s := poolOfSplitters.BorrowSplitter() - lexems := s.split(str) - result := make([]string, 0, len(*lexems)) - - for _, lexem := range *lexems { - result = append(result, lexem.GetOriginal()) - } - poolOfLexems.RedeemLexems(lexems) - poolOfSplitters.RedeemSplitter(s) - - return result - -} - -func newSplitter(options ...splitterOption) splitter { - s := splitter{ - postSplitInitialismCheck: false, - initialisms: initialisms, - initialismsRunes: initialismsRunes, - initialismsUpperCased: initialismsUpperCased, - } - - for _, option := range options { - option(&s) - } - - return s -} - -// withPostSplitInitialismCheck allows to catch initialisms after main split process -func withPostSplitInitialismCheck(s *splitter) { - s.postSplitInitialismCheck = true -} - -func (p matchesPool) BorrowMatches() *initialismMatches { - s := p.Get().(*initialismMatches) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { - s := p.Get().(*bytes.Buffer) - s.Reset() - - if s.Cap() < size { - s.Grow(size) - } - - return s -} - -func (p lexemsPool) BorrowLexems() *[]nameLexem { - s := p.Get().(*[]nameLexem) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p splittersPool) BorrowSplitter(options ...splitterOption) *splitter { - s := p.Get().(*splitter) - s.postSplitInitialismCheck = false // reset options - for _, apply := range options { - apply(s) - } - - return s -} - -func (p matchesPool) RedeemMatches(s *initialismMatches) { - p.Put(s) -} - -func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { - p.Put(s) -} - -func (p lexemsPool) RedeemLexems(s *[]nameLexem) { - p.Put(s) -} - -func (p splittersPool) RedeemSplitter(s *splitter) { - p.Put(s) -} - -func (m initialismMatch) isZero() bool { - return m.start == 0 && m.end == 0 -} - -func (s splitter) split(name string) *[]nameLexem { - nameRunes := []rune(name) - matches := s.gatherInitialismMatches(nameRunes) - if matches == nil { - return poolOfLexems.BorrowLexems() - } - - return s.mapMatchesToNameLexems(nameRunes, matches) -} - -func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { - var matches *initialismMatches - - for currentRunePosition, currentRune := range nameRunes { - // recycle these allocations as we loop over runes - // with such recycling, only 2 slices should be allocated per call - // instead of o(n). - newMatches := poolOfMatches.BorrowMatches() - - // check current initialism matches - if matches != nil { // skip first iteration - for _, match := range *matches { - if keepCompleteMatch := match.complete; keepCompleteMatch { - *newMatches = append(*newMatches, match) - continue - } - - // drop failed match - currentMatchRune := match.body[currentRunePosition-match.start] - if currentMatchRune != currentRune { - continue - } - - // try to complete ongoing match - if currentRunePosition-match.start == len(match.body)-1 { - // we are close; the next step is to check the symbol ahead - // if it is a small letter, then it is not the end of match - // but beginning of the next word - - if currentRunePosition < len(nameRunes)-1 { - nextRune := nameRunes[currentRunePosition+1] - if newWord := unicode.IsLower(nextRune); newWord { - // oh ok, it was the start of a new word - continue - } - } - - match.complete = true - match.end = currentRunePosition - } - - *newMatches = append(*newMatches, match) - } - } - - // check for new initialism matches - for i := range s.initialisms { - initialismRunes := s.initialismsRunes[i] - if initialismRunes[0] == currentRune { - *newMatches = append(*newMatches, initialismMatch{ - start: currentRunePosition, - body: initialismRunes, - complete: false, - }) - } - } - - if matches != nil { - poolOfMatches.RedeemMatches(matches) - } - matches = newMatches - } - - // up to the caller to redeem this last slice - return matches -} - -func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { - nameLexems := poolOfLexems.BorrowLexems() - - var lastAcceptedMatch initialismMatch - for _, match := range *matches { - if !match.complete { - continue - } - - if firstMatch := lastAcceptedMatch.isZero(); firstMatch { - s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - - continue - } - - if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { - continue - } - - middle := nameRunes[lastAcceptedMatch.end+1 : match.start] - s.appendBrokenDownCasualString(nameLexems, middle) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - } - - // we have not found any accepted matches - if lastAcceptedMatch.isZero() { - *nameLexems = (*nameLexems)[:0] - s.appendBrokenDownCasualString(nameLexems, nameRunes) - } else if lastAcceptedMatch.end+1 != len(nameRunes) { - rest := nameRunes[lastAcceptedMatch.end+1:] - s.appendBrokenDownCasualString(nameLexems, rest) - } - - poolOfMatches.RedeemMatches(matches) - - return nameLexems -} - -func (s splitter) breakInitialism(original string) nameLexem { - return newInitialismNameLexem(original, original) -} - -func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { - currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused - defer func() { - poolOfBuffers.RedeemBuffer(currentSegment) - }() - - addCasualNameLexem := func(original string) { - *segments = append(*segments, newCasualNameLexem(original)) - } - - addInitialismNameLexem := func(original, match string) { - *segments = append(*segments, newInitialismNameLexem(original, match)) - } - - var addNameLexem func(string) - if s.postSplitInitialismCheck { - addNameLexem = func(original string) { - for i := range s.initialisms { - if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { - addInitialismNameLexem(original, s.initialisms[i]) - - return - } - } - - addCasualNameLexem(original) - } - } else { - addNameLexem = addCasualNameLexem - } - - for _, rn := range str { - if replace, found := nameReplaceTable(rn); found { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - if replace != "" { - addNameLexem(replace) - } - - continue - } - - if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - continue - } - - if unicode.IsUpper(rn) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } - currentSegment.Reset() - } - - currentSegment.WriteRune(rn) - } - - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } -} - -// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but -// it ignores leading and trailing blank spaces in the compared -// string. -// -// base is assumed to be composed of upper-cased runes, and be already -// trimmed. -// -// This code is heavily inspired from strings.EqualFold. -func isEqualFoldIgnoreSpace(base []rune, str string) bool { - var i, baseIndex int - // equivalent to b := []byte(str), but without data copy - b := hackStringBytes(str) - - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - break - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - break - } - i += size - } - - if i >= len(b) { - return len(base) == 0 - } - - for _, baseRune := range base { - if i >= len(b) { - break - } - - if c := b[i]; c < utf8.RuneSelf { - // single byte rune case (ASCII) - if baseRune >= utf8.RuneSelf { - return false - } - - baseChar := byte(baseRune) - if c != baseChar && - !('a' <= c && c <= 'z' && c-'a'+'A' == baseChar) { - return false - } - - baseIndex++ - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if unicode.ToUpper(r) != baseRune { - return false - } - baseIndex++ - i += size - } - - if baseIndex != len(base) { - return false - } - - // all passed: now we should only have blanks - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - return false - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - return false - } - - i += size - } - - return true -} diff --git a/vendor/github.com/go-openapi/swag/string_bytes.go b/vendor/github.com/go-openapi/swag/string_bytes.go deleted file mode 100644 index 90745d5..0000000 --- a/vendor/github.com/go-openapi/swag/string_bytes.go +++ /dev/null @@ -1,8 +0,0 @@ -package swag - -import "unsafe" - -// hackStringBytes returns the (unsafe) underlying bytes slice of a string. -func hackStringBytes(str string) []byte { - return unsafe.Slice(unsafe.StringData(str), len(str)) -} diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 5051401..0000000 --- a/vendor/github.com/go-openapi/swag/util.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// GoNamePrefixFunc sets an optional rule to prefix go names -// which do not start with a letter. -// -// The prefix function is assumed to return a string that starts with an upper case letter. -// -// e.g. to help convert "123" into "{prefix}123" -// -// The default is to prefix with "X" -var GoNamePrefixFunc func(string) string - -func prefixFunc(name, in string) string { - if GoNamePrefixFunc == nil { - return "X" + in - } - - return GoNamePrefixFunc(name) + in -} - -const ( - // collectionFormatComma = "csv" - collectionFormatSpace = "ssv" - collectionFormatTab = "tsv" - collectionFormatPipe = "pipes" - collectionFormatMulti = "multi" -) - -// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func JoinByFormat(data []string, format string) []string { - if len(data) == 0 { - return data - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return data - default: - sep = "," - } - return []string{strings.Join(data, sep)} -} - -// SplitByFormat splits a string by a known format: -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func SplitByFormat(data, format string) []string { - if data == "" { - return nil - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return nil - default: - sep = "," - } - var result []string - for _, s := range strings.Split(data, sep) { - if ts := strings.TrimSpace(s); ts != "" { - result = append(result, ts) - } - } - return result -} - -// Removes leading whitespaces -func trim(str string) string { - return strings.TrimSpace(str) -} - -// Shortcut to strings.ToUpper() -func upper(str string) string { - return strings.ToUpper(trim(str)) -} - -// Shortcut to strings.ToLower() -func lower(str string) string { - return strings.ToLower(trim(str)) -} - -// Camelize an uppercased word -func Camelize(word string) string { - camelized := poolOfBuffers.BorrowBuffer(len(word)) - defer func() { - poolOfBuffers.RedeemBuffer(camelized) - }() - - for pos, ru := range []rune(word) { - if pos > 0 { - camelized.WriteRune(unicode.ToLower(ru)) - } else { - camelized.WriteRune(unicode.ToUpper(ru)) - } - } - return camelized.String() -} - -// ToFileName lowercases and underscores a go type name -func ToFileName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - - return strings.Join(out, "_") -} - -// ToCommandName lowercases and underscores a go type name -func ToCommandName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - return strings.Join(out, "-") -} - -// ToHumanNameLower represents a code name as a human series of words -func ToHumanNameLower(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - out := make([]string, 0, len(*in)) - - for _, w := range *in { - if !w.IsInitialism() { - out = append(out, lower(w.GetOriginal())) - } else { - out = append(out, trim(w.GetOriginal())) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized -func ToHumanNameTitle(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - - out := make([]string, 0, len(*in)) - for _, w := range *in { - original := trim(w.GetOriginal()) - if !w.IsInitialism() { - out = append(out, Camelize(original)) - } else { - out = append(out, original) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToJSONName camelcases a name which can be underscored or pascal cased -func ToJSONName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for i, w := range in { - if i == 0 { - out = append(out, lower(w)) - continue - } - out = append(out, Camelize(trim(w))) - } - return strings.Join(out, "") -} - -// ToVarName camelcases a name which can be underscored or pascal cased -func ToVarName(name string) string { - res := ToGoName(name) - if isInitialism(res) { - return lower(res) - } - if len(res) <= 1 { - return lower(res) - } - return lower(res[:1]) + res[1:] -} - -// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes -func ToGoName(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - lexems := s.split(name) - poolOfSplitters.RedeemSplitter(s) - defer func() { - poolOfLexems.RedeemLexems(lexems) - }() - lexemes := *lexems - - if len(lexemes) == 0 { - return "" - } - - result := poolOfBuffers.BorrowBuffer(len(name)) - defer func() { - poolOfBuffers.RedeemBuffer(result) - }() - - // check if not starting with a letter, upper case - firstPart := lexemes[0].GetUnsafeGoName() - if lexemes[0].IsInitialism() { - firstPart = upper(firstPart) - } - - if c := firstPart[0]; c < utf8.RuneSelf { - // ASCII - switch { - case 'A' <= c && c <= 'Z': - result.WriteString(firstPart) - case 'a' <= c && c <= 'z': - result.WriteByte(c - 'a' + 'A') - result.WriteString(firstPart[1:]) - default: - result.WriteString(prefixFunc(name, firstPart)) - // NOTE: no longer check if prefixFunc returns a string that starts with uppercase: - // assume this is always the case - } - } else { - // unicode - firstRune, _ := utf8.DecodeRuneInString(firstPart) - switch { - case !unicode.IsLetter(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - case !unicode.IsUpper(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - /* - result.WriteRune(unicode.ToUpper(firstRune)) - result.WriteString(firstPart[offset:]) - */ - default: - result.WriteString(firstPart) - } - } - - for _, lexem := range lexemes[1:] { - goName := lexem.GetUnsafeGoName() - - // to support old behavior - if lexem.IsInitialism() { - goName = upper(goName) - } - result.WriteString(goName) - } - - return result.String() -} - -// ContainsStrings searches a slice of strings for a case-sensitive match -func ContainsStrings(coll []string, item string) bool { - for _, a := range coll { - if a == item { - return true - } - } - return false -} - -// ContainsStringsCI searches a slice of strings for a case-insensitive match -func ContainsStringsCI(coll []string, item string) bool { - for _, a := range coll { - if strings.EqualFold(a, item) { - return true - } - } - return false -} - -type zeroable interface { - IsZero() bool -} - -// IsZero returns true when the value passed into the function is a zero value. -// This allows for safer checking of interface values. -func IsZero(data interface{}) bool { - v := reflect.ValueOf(data) - // check for nil data - switch v.Kind() { //nolint:exhaustive - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - if v.IsNil() { - return true - } - } - - // check for things that have an IsZero method instead - if vv, ok := data.(zeroable); ok { - return vv.IsZero() - } - - // continue with slightly more complex reflection - switch v.Kind() { //nolint:exhaustive - case reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Struct, reflect.Array: - return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) - case reflect.Invalid: - return true - default: - return false - } -} - -// CommandLineOptionsGroup represents a group of user-defined command line options -type CommandLineOptionsGroup struct { - ShortDescription string - LongDescription string - Options interface{} -} diff --git a/vendor/github.com/go-openapi/swag/yaml.go b/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index f59e025..0000000 --- a/vendor/github.com/go-openapi/swag/yaml.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed 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 swag - -import ( - "encoding/json" - "errors" - "fmt" - "path/filepath" - "reflect" - "sort" - "strconv" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - yaml "gopkg.in/yaml.v3" -) - -// YAMLMatcher matches yaml -func YAMLMatcher(path string) bool { - ext := filepath.Ext(path) - return ext == ".yaml" || ext == ".yml" -} - -// YAMLToJSON converts YAML unmarshaled data into json compatible data -func YAMLToJSON(data interface{}) (json.RawMessage, error) { - jm, err := transformData(data) - if err != nil { - return nil, err - } - b, err := WriteJSON(jm) - return json.RawMessage(b), err -} - -// BytesToYAMLDoc converts a byte slice into a YAML document -func BytesToYAMLDoc(data []byte) (interface{}, error) { - var document yaml.Node // preserve order that is present in the document - if err := yaml.Unmarshal(data, &document); err != nil { - return nil, err - } - if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { - return nil, errors.New("only YAML documents that are objects are supported") - } - return &document, nil -} - -func yamlNode(root *yaml.Node) (interface{}, error) { - switch root.Kind { - case yaml.DocumentNode: - return yamlDocument(root) - case yaml.SequenceNode: - return yamlSequence(root) - case yaml.MappingNode: - return yamlMapping(root) - case yaml.ScalarNode: - return yamlScalar(root) - case yaml.AliasNode: - return yamlNode(root.Alias) - default: - return nil, fmt.Errorf("unsupported YAML node type: %v", root.Kind) - } -} - -func yamlDocument(node *yaml.Node) (interface{}, error) { - if len(node.Content) != 1 { - return nil, fmt.Errorf("unexpected YAML Document node content length: %d", len(node.Content)) - } - return yamlNode(node.Content[0]) -} - -func yamlMapping(node *yaml.Node) (interface{}, error) { - m := make(JSONMapSlice, len(node.Content)/2) - - var j int - for i := 0; i < len(node.Content); i += 2 { - var nmi JSONMapItem - k, err := yamlStringScalarC(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML map key: %w", err) - } - nmi.Key = k - v, err := yamlNode(node.Content[i+1]) - if err != nil { - return nil, fmt.Errorf("unable to process YAML map value for key %q: %w", k, err) - } - nmi.Value = v - m[j] = nmi - j++ - } - return m, nil -} - -func yamlSequence(node *yaml.Node) (interface{}, error) { - s := make([]interface{}, 0) - - for i := 0; i < len(node.Content); i++ { - - v, err := yamlNode(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML sequence value: %w", err) - } - s = append(s, v) - } - return s, nil -} - -const ( // See https://yaml.org/type/ - yamlStringScalar = "tag:yaml.org,2002:str" - yamlIntScalar = "tag:yaml.org,2002:int" - yamlBoolScalar = "tag:yaml.org,2002:bool" - yamlFloatScalar = "tag:yaml.org,2002:float" - yamlTimestamp = "tag:yaml.org,2002:timestamp" - yamlNull = "tag:yaml.org,2002:null" -) - -func yamlScalar(node *yaml.Node) (interface{}, error) { - switch node.LongTag() { - case yamlStringScalar: - return node.Value, nil - case yamlBoolScalar: - b, err := strconv.ParseBool(node.Value) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w", node.Value, err) - } - return b, nil - case yamlIntScalar: - i, err := strconv.ParseInt(node.Value, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w", node.Value, err) - } - return i, nil - case yamlFloatScalar: - f, err := strconv.ParseFloat(node.Value, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w", node.Value, err) - } - return f, nil - case yamlTimestamp: - return node.Value, nil - case yamlNull: - return nil, nil //nolint:nilnil - default: - return nil, fmt.Errorf("YAML tag %q is not supported", node.LongTag()) - } -} - -func yamlStringScalarC(node *yaml.Node) (string, error) { - if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q", node.Kind) - } - switch node.LongTag() { - case yamlStringScalar, yamlIntScalar, yamlFloatScalar: - return node.Value, nil - default: - return "", fmt.Errorf("YAML tag %q is not supported as map key", node.LongTag()) - } -} - -// JSONMapSlice represent a JSON object, with the order of keys maintained -type JSONMapSlice []JSONMapItem - -// MarshalJSON renders a JSONMapSlice as JSON -func (s JSONMapSlice) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON -func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { - w.RawByte('{') - - ln := len(s) - last := ln - 1 - for i := 0; i < ln; i++ { - s[i].MarshalEasyJSON(w) - if i != last { // last item - w.RawByte(',') - } - } - - w.RawByte('}') -} - -// UnmarshalJSON makes a JSONMapSlice from JSON -func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON -func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { - if in.IsNull() { - in.Skip() - return - } - - var result JSONMapSlice - in.Delim('{') - for !in.IsDelim('}') { - var mi JSONMapItem - mi.UnmarshalEasyJSON(in) - result = append(result, mi) - } - *s = result -} - -func (s JSONMapSlice) MarshalYAML() (interface{}, error) { - var n yaml.Node - n.Kind = yaml.DocumentNode - var nodes []*yaml.Node - for _, item := range s { - nn, err := json2yaml(item.Value) - if err != nil { - return nil, err - } - ns := []*yaml.Node{ - { - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: item.Key, - }, - nn, - } - nodes = append(nodes, ns...) - } - - n.Content = []*yaml.Node{ - { - Kind: yaml.MappingNode, - Content: nodes, - }, - } - - return yaml.Marshal(&n) -} - -func isNil(input interface{}) bool { - if input == nil { - return true - } - kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: - return reflect.ValueOf(input).IsNil() - default: - return false - } -} - -func json2yaml(item interface{}) (*yaml.Node, error) { - if isNil(item) { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Value: "null", - }, nil - } - - switch val := item.(type) { - case JSONMapSlice: - var n yaml.Node - n.Kind = yaml.MappingNode - for i := range val { - childNode, err := json2yaml(&val[i].Value) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val[i].Key, - }, childNode) - } - return &n, nil - case map[string]interface{}: - var n yaml.Node - n.Kind = yaml.MappingNode - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := val[k] - childNode, err := json2yaml(v) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: k, - }, childNode) - } - return &n, nil - case []interface{}: - var n yaml.Node - n.Kind = yaml.SequenceNode - for i := range val { - childNode, err := json2yaml(val[i]) - if err != nil { - return nil, err - } - n.Content = append(n.Content, childNode) - } - return &n, nil - case string: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val, - }, nil - case float64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlFloatScalar, - Value: strconv.FormatFloat(val, 'f', -1, 64), - }, nil - case int64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatInt(val, 10), - }, nil - case uint64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatUint(val, 10), - }, nil - case bool: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlBoolScalar, - Value: strconv.FormatBool(val), - }, nil - default: - return nil, fmt.Errorf("unhandled type: %T", val) - } -} - -// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice -type JSONMapItem struct { - Key string - Value interface{} -} - -// MarshalJSON renders a JSONMapItem as JSON -func (s JSONMapItem) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON -func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { - w.String(s.Key) - w.RawByte(':') - w.Raw(WriteJSON(s.Value)) -} - -// UnmarshalJSON makes a JSONMapItem from JSON -func (s *JSONMapItem) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON -func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { - key := in.UnsafeString() - in.WantColon() - value := in.Interface() - in.WantComma() - s.Key = key - s.Value = value -} - -func transformData(input interface{}) (out interface{}, err error) { - format := func(t interface{}) (string, error) { - switch k := t.(type) { - case string: - return k, nil - case uint: - return strconv.FormatUint(uint64(k), 10), nil - case uint8: - return strconv.FormatUint(uint64(k), 10), nil - case uint16: - return strconv.FormatUint(uint64(k), 10), nil - case uint32: - return strconv.FormatUint(uint64(k), 10), nil - case uint64: - return strconv.FormatUint(k, 10), nil - case int: - return strconv.Itoa(k), nil - case int8: - return strconv.FormatInt(int64(k), 10), nil - case int16: - return strconv.FormatInt(int64(k), 10), nil - case int32: - return strconv.FormatInt(int64(k), 10), nil - case int64: - return strconv.FormatInt(k, 10), nil - default: - return "", fmt.Errorf("unexpected map key type, got: %T", k) - } - } - - switch in := input.(type) { - case yaml.Node: - return yamlNode(&in) - case *yaml.Node: - return yamlNode(in) - case map[interface{}]interface{}: - o := make(JSONMapSlice, 0, len(in)) - for ke, va := range in { - var nmi JSONMapItem - if nmi.Key, err = format(ke); err != nil { - return nil, err - } - - v, ert := transformData(va) - if ert != nil { - return nil, ert - } - nmi.Value = v - o = append(o, nmi) - } - return o, nil - case []interface{}: - len1 := len(in) - o := make([]interface{}, len1) - for i := 0; i < len1; i++ { - o[i], err = transformData(in[i]) - if err != nil { - return nil, err - } - } - return o, nil - } - return input, nil -} - -// YAMLDoc loads a yaml document from either http or a file and converts it to json -func YAMLDoc(path string) (json.RawMessage, error) { - yamlDoc, err := YAMLData(path) - if err != nil { - return nil, err - } - - data, err := YAMLToJSON(yamlDoc) - if err != nil { - return nil, err - } - - return data, nil -} - -// YAMLData loads a yaml document from either http or a file -func YAMLData(path string) (interface{}, error) { - data, err := LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - - return BytesToYAMLDoc(data) -} diff --git a/vendor/github.com/josharian/intern/README.md b/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b2..0000000 --- a/vendor/github.com/josharian/intern/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Docs: https://godoc.org/github.com/josharian/intern - -See also [Go issue 5160](https://golang.org/issue/5160). - -License: MIT diff --git a/vendor/github.com/josharian/intern/intern.go b/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe..0000000 --- a/vendor/github.com/josharian/intern/intern.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package intern interns strings. -// Interning is best effort only. -// Interned strings may be removed automatically -// at any time without notification. -// All functions may be called concurrently -// with themselves and each other. -package intern - -import "sync" - -var ( - pool sync.Pool = sync.Pool{ - New: func() interface{} { - return make(map[string]string) - }, - } -) - -// String returns s, interned. -func String(s string) string { - m := pool.Get().(map[string]string) - c, ok := m[s] - if ok { - pool.Put(m) - return c - } - m[s] = s - pool.Put(m) - return s -} - -// Bytes returns b converted to a string, interned. -func Bytes(b []byte) string { - m := pool.Get().(map[string]string) - c, ok := m[string(b)] - if ok { - pool.Put(m) - return c - } - s := string(b) - m[s] = s - pool.Put(m) - return s -} diff --git a/vendor/github.com/josharian/intern/license.md b/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d305..0000000 --- a/vendor/github.com/josharian/intern/license.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -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. diff --git a/vendor/github.com/mailru/easyjson/LICENSE b/vendor/github.com/mailru/easyjson/LICENSE deleted file mode 100644 index fbff658..0000000 --- a/vendor/github.com/mailru/easyjson/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2016 Mail.Ru Group - -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. diff --git a/vendor/github.com/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go deleted file mode 100644 index 598a54a..0000000 --- a/vendor/github.com/mailru/easyjson/buffer/pool.go +++ /dev/null @@ -1,278 +0,0 @@ -// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to -// reduce copying and to allow reuse of individual chunks. -package buffer - -import ( - "io" - "net" - "sync" -) - -// PoolConfig contains configuration for the allocation and reuse strategy. -type PoolConfig struct { - StartSize int // Minimum chunk size that is allocated. - PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. - MaxSize int // Maximum chunk size that will be allocated. -} - -var config = PoolConfig{ - StartSize: 128, - PooledSize: 512, - MaxSize: 32768, -} - -// Reuse pool: chunk size -> pool. -var buffers = map[int]*sync.Pool{} - -func initBuffers() { - for l := config.PooledSize; l <= config.MaxSize; l *= 2 { - buffers[l] = new(sync.Pool) - } -} - -func init() { - initBuffers() -} - -// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. -func Init(cfg PoolConfig) { - config = cfg - initBuffers() -} - -// putBuf puts a chunk to reuse pool if it can be reused. -func putBuf(buf []byte) { - size := cap(buf) - if size < config.PooledSize { - return - } - if c := buffers[size]; c != nil { - c.Put(buf[:0]) - } -} - -// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. -func getBuf(size int) []byte { - if size >= config.PooledSize { - if c := buffers[size]; c != nil { - v := c.Get() - if v != nil { - return v.([]byte) - } - } - } - return make([]byte, 0, size) -} - -// Buffer is a buffer optimized for serialization without extra copying. -type Buffer struct { - - // Buf is the current chunk that can be used for serialization. - Buf []byte - - toPool []byte - bufs [][]byte -} - -// EnsureSpace makes sure that the current chunk contains at least s free bytes, -// possibly creating a new chunk. -func (b *Buffer) EnsureSpace(s int) { - if cap(b.Buf)-len(b.Buf) < s { - b.ensureSpaceSlow(s) - } -} - -func (b *Buffer) ensureSpaceSlow(s int) { - l := len(b.Buf) - if l > 0 { - if cap(b.toPool) != cap(b.Buf) { - // Chunk was reallocated, toPool can be pooled. - putBuf(b.toPool) - } - if cap(b.bufs) == 0 { - b.bufs = make([][]byte, 0, 8) - } - b.bufs = append(b.bufs, b.Buf) - l = cap(b.toPool) * 2 - } else { - l = config.StartSize - } - - if l > config.MaxSize { - l = config.MaxSize - } - b.Buf = getBuf(l) - b.toPool = b.Buf -} - -// AppendByte appends a single byte to buffer. -func (b *Buffer) AppendByte(data byte) { - b.EnsureSpace(1) - b.Buf = append(b.Buf, data) -} - -// AppendBytes appends a byte slice to buffer. -func (b *Buffer) AppendBytes(data []byte) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendBytesSlow(data) - } -} - -func (b *Buffer) appendBytesSlow(data []byte) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// AppendString appends a string to buffer. -func (b *Buffer) AppendString(data string) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendStringSlow(data) - } -} - -func (b *Buffer) appendStringSlow(data string) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// Size computes the size of a buffer by adding sizes of every chunk. -func (b *Buffer) Size() int { - size := len(b.Buf) - for _, buf := range b.bufs { - size += len(buf) - } - return size -} - -// DumpTo outputs the contents of a buffer to a writer and resets the buffer. -func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { - bufs := net.Buffers(b.bufs) - if len(b.Buf) > 0 { - bufs = append(bufs, b.Buf) - } - n, err := bufs.WriteTo(w) - - for _, buf := range b.bufs { - putBuf(buf) - } - putBuf(b.toPool) - - b.bufs = nil - b.Buf = nil - b.toPool = nil - - return int(n), err -} - -// BuildBytes creates a single byte slice with all the contents of the buffer. Data is -// copied if it does not fit in a single chunk. You can optionally provide one byte -// slice as argument that it will try to reuse. -func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { - if len(b.bufs) == 0 { - ret := b.Buf - b.toPool = nil - b.Buf = nil - return ret - } - - var ret []byte - size := b.Size() - - // If we got a buffer as argument and it is big enough, reuse it. - if len(reuse) == 1 && cap(reuse[0]) >= size { - ret = reuse[0][:0] - } else { - ret = make([]byte, 0, size) - } - for _, buf := range b.bufs { - ret = append(ret, buf...) - putBuf(buf) - } - - ret = append(ret, b.Buf...) - putBuf(b.toPool) - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} - -type readCloser struct { - offset int - bufs [][]byte -} - -func (r *readCloser) Read(p []byte) (n int, err error) { - for _, buf := range r.bufs { - // Copy as much as we can. - x := copy(p[n:], buf[r.offset:]) - n += x // Increment how much we filled. - - // Did we empty the whole buffer? - if r.offset+x == len(buf) { - // On to the next buffer. - r.offset = 0 - r.bufs = r.bufs[1:] - - // We can release this buffer. - putBuf(buf) - } else { - r.offset += x - } - - if n == len(p) { - break - } - } - // No buffers left or nothing read? - if len(r.bufs) == 0 { - err = io.EOF - } - return -} - -func (r *readCloser) Close() error { - // Release all remaining buffers. - for _, buf := range r.bufs { - putBuf(buf) - } - // In case Close gets called multiple times. - r.bufs = nil - - return nil -} - -// ReadCloser creates an io.ReadCloser with all the contents of the buffer. -func (b *Buffer) ReadCloser() io.ReadCloser { - ret := &readCloser{0, append(b.bufs, b.Buf)} - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go deleted file mode 100644 index ff7b27c..0000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ /dev/null @@ -1,24 +0,0 @@ -// This file will only be included to the build if neither -// easyjson_nounsafe nor appengine build tag is set. See README notes -// for more details. - -//+build !easyjson_nounsafe -//+build !appengine - -package jlexer - -import ( - "reflect" - "unsafe" -) - -// bytesToStr creates a string pointing at the slice to avoid copying. -// -// Warning: the string returned by the function should be used with care, as the whole input data -// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data -// may be garbage-collected even when the string exists. -func bytesToStr(data []byte) string { - h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) - shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} - return *(*string)(unsafe.Pointer(&shdr)) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go deleted file mode 100644 index 864d1be..0000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go +++ /dev/null @@ -1,13 +0,0 @@ -// This file is included to the build if any of the buildtags below -// are defined. Refer to README notes for more details. - -//+build easyjson_nounsafe appengine - -package jlexer - -// bytesToStr creates a string normally from []byte -// -// Note that this method is roughly 1.5x slower than using the 'unsafe' method. -func bytesToStr(data []byte) string { - return string(data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/error.go b/vendor/github.com/mailru/easyjson/jlexer/error.go deleted file mode 100644 index e90ec40..0000000 --- a/vendor/github.com/mailru/easyjson/jlexer/error.go +++ /dev/null @@ -1,15 +0,0 @@ -package jlexer - -import "fmt" - -// LexerError implements the error interface and represents all possible errors that can be -// generated during parsing the JSON data. -type LexerError struct { - Reason string - Offset int - Data string -} - -func (l *LexerError) Error() string { - return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go deleted file mode 100644 index b5f5e26..0000000 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ /dev/null @@ -1,1244 +0,0 @@ -// Package jlexer contains a JSON lexer implementation. -// -// It is expected that it is mostly used with generated parser code, so the interface is tuned -// for a parser that knows what kind of data is expected. -package jlexer - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" - - "github.com/josharian/intern" -) - -// tokenKind determines type of a token. -type tokenKind byte - -const ( - tokenUndef tokenKind = iota // No token. - tokenDelim // Delimiter: one of '{', '}', '[' or ']'. - tokenString // A string literal, e.g. "abc\u1234" - tokenNumber // Number literal, e.g. 1.5e5 - tokenBool // Boolean literal: true or false. - tokenNull // null keyword. -) - -// token describes a single token: type, position in the input and value. -type token struct { - kind tokenKind // Type of a token. - - boolValue bool // Value if a boolean literal token. - byteValueCloned bool // true if byteValue was allocated and does not refer to original json body - byteValue []byte // Raw value of a token. - delimValue byte -} - -// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. -type Lexer struct { - Data []byte // Input data given to the lexer. - - start int // Start of the current token. - pos int // Current unscanned position in the input stream. - token token // Last scanned token, if token.kind != tokenUndef. - - firstElement bool // Whether current element is the first in array or an object. - wantSep byte // A comma or a colon character, which need to occur before a token. - - UseMultipleErrors bool // If we want to use multiple errors. - fatalError error // Fatal error occurred during lexing. It is usually a syntax error. - multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. -} - -// FetchToken scans the input for the next token. -func (r *Lexer) FetchToken() { - r.token.kind = tokenUndef - r.start = r.pos - - // Check if r.Data has r.pos element - // If it doesn't, it mean corrupted input data - if len(r.Data) < r.pos { - r.errParse("Unexpected end of data") - return - } - // Determine the type of a token by skipping whitespace and reading the - // first character. - for _, c := range r.Data[r.pos:] { - switch c { - case ':', ',': - if r.wantSep == c { - r.pos++ - r.start++ - r.wantSep = 0 - } else { - r.errSyntax() - } - - case ' ', '\t', '\r', '\n': - r.pos++ - r.start++ - - case '"': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenString - r.fetchString() - return - - case '{', '[': - if r.wantSep != 0 { - r.errSyntax() - } - r.firstElement = true - r.token.kind = tokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '}', ']': - if !r.firstElement && (r.wantSep != ',') { - r.errSyntax() - } - r.wantSep = 0 - r.token.kind = tokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': - if r.wantSep != 0 { - r.errSyntax() - } - r.token.kind = tokenNumber - r.fetchNumber() - return - - case 'n': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenNull - r.fetchNull() - return - - case 't': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenBool - r.token.boolValue = true - r.fetchTrue() - return - - case 'f': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenBool - r.token.boolValue = false - r.fetchFalse() - return - - default: - r.errSyntax() - return - } - } - r.fatalError = io.EOF - return -} - -// isTokenEnd returns true if the char can follow a non-delimiter token -func isTokenEnd(c byte) bool { - return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' -} - -// fetchNull fetches and checks remaining bytes of null keyword. -func (r *Lexer) fetchNull() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'u' || - r.Data[r.pos-2] != 'l' || - r.Data[r.pos-1] != 'l' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchTrue fetches and checks remaining bytes of true keyword. -func (r *Lexer) fetchTrue() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'r' || - r.Data[r.pos-2] != 'u' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchFalse fetches and checks remaining bytes of false keyword. -func (r *Lexer) fetchFalse() { - r.pos += 5 - if r.pos > len(r.Data) || - r.Data[r.pos-4] != 'a' || - r.Data[r.pos-3] != 'l' || - r.Data[r.pos-2] != 's' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 5 - r.errSyntax() - } -} - -// fetchNumber scans a number literal token. -func (r *Lexer) fetchNumber() { - hasE := false - afterE := false - hasDot := false - - r.pos++ - for i, c := range r.Data[r.pos:] { - switch { - case c >= '0' && c <= '9': - afterE = false - case c == '.' && !hasDot: - hasDot = true - case (c == 'e' || c == 'E') && !hasE: - hasE = true - hasDot = true - afterE = true - case (c == '+' || c == '-') && afterE: - afterE = false - default: - r.pos += i - if !isTokenEnd(c) { - r.errSyntax() - } else { - r.token.byteValue = r.Data[r.start:r.pos] - } - return - } - } - - r.pos = len(r.Data) - r.token.byteValue = r.Data[r.start:] -} - -// findStringLen tries to scan into the string literal for ending quote char to determine required size. -// The size will be exact if no escapes are present and may be inexact if there are escaped chars. -func findStringLen(data []byte) (isValid bool, length int) { - for { - idx := bytes.IndexByte(data, '"') - if idx == -1 { - return false, len(data) - } - if idx == 0 || (idx > 0 && data[idx-1] != '\\') { - return true, length + idx - } - - // count \\\\\\\ sequences. even number of slashes means quote is not really escaped - cnt := 1 - for idx-cnt-1 >= 0 && data[idx-cnt-1] == '\\' { - cnt++ - } - if cnt%2 == 0 { - return true, length + idx - } - - length += idx + 1 - data = data[idx+1:] - } -} - -// unescapeStringToken performs unescaping of string token. -// if no escaping is needed, original string is returned, otherwise - a new one allocated -func (r *Lexer) unescapeStringToken() (err error) { - data := r.token.byteValue - var unescapedData []byte - - for { - i := bytes.IndexByte(data, '\\') - if i == -1 { - break - } - - escapedRune, escapedBytes, err := decodeEscape(data[i:]) - if err != nil { - r.errParse(err.Error()) - return err - } - - if unescapedData == nil { - unescapedData = make([]byte, 0, len(r.token.byteValue)) - } - - var d [4]byte - s := utf8.EncodeRune(d[:], escapedRune) - unescapedData = append(unescapedData, data[:i]...) - unescapedData = append(unescapedData, d[:s]...) - - data = data[i+escapedBytes:] - } - - if unescapedData != nil { - r.token.byteValue = append(unescapedData, data...) - r.token.byteValueCloned = true - } - return -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var val rune - for i := 2; i < len(s) && i < 6; i++ { - var v byte - c := s[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - v = c - '0' - case 'a', 'b', 'c', 'd', 'e', 'f': - v = c - 'a' + 10 - case 'A', 'B', 'C', 'D', 'E', 'F': - v = c - 'A' + 10 - default: - return -1 - } - - val <<= 4 - val |= rune(v) - } - return val -} - -// decodeEscape processes a single escape sequence and returns number of bytes processed. -func decodeEscape(data []byte) (decoded rune, bytesProcessed int, err error) { - if len(data) < 2 { - return 0, 0, errors.New("incorrect escape symbol \\ at the end of token") - } - - c := data[1] - switch c { - case '"', '/', '\\': - return rune(c), 2, nil - case 'b': - return '\b', 2, nil - case 'f': - return '\f', 2, nil - case 'n': - return '\n', 2, nil - case 'r': - return '\r', 2, nil - case 't': - return '\t', 2, nil - case 'u': - rr := getu4(data) - if rr < 0 { - return 0, 0, errors.New("incorrectly escaped \\uXXXX sequence") - } - - read := 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(data[read:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - read += 6 - rr = dec - } else { - rr = unicode.ReplacementChar - } - } - return rr, read, nil - } - - return 0, 0, errors.New("incorrectly escaped bytes") -} - -// fetchString scans a string literal token. -func (r *Lexer) fetchString() { - r.pos++ - data := r.Data[r.pos:] - - isValid, length := findStringLen(data) - if !isValid { - r.pos += length - r.errParse("unterminated string literal") - return - } - r.token.byteValue = data[:length] - r.pos += length + 1 // skip closing '"' as well -} - -// scanToken scans the next token if no token is currently available in the lexer. -func (r *Lexer) scanToken() { - if r.token.kind != tokenUndef || r.fatalError != nil { - return - } - - r.FetchToken() -} - -// consume resets the current token to allow scanning the next one. -func (r *Lexer) consume() { - r.token.kind = tokenUndef - r.token.byteValueCloned = false - r.token.delimValue = 0 -} - -// Ok returns true if no error (including io.EOF) was encountered during scanning. -func (r *Lexer) Ok() bool { - return r.fatalError == nil -} - -const maxErrorContextLen = 13 - -func (r *Lexer) errParse(what string) { - if r.fatalError == nil { - var str string - if len(r.Data)-r.pos <= maxErrorContextLen { - str = string(r.Data) - } else { - str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: what, - Offset: r.pos, - Data: str, - } - } -} - -func (r *Lexer) errSyntax() { - r.errParse("syntax error") -} - -func (r *Lexer) errInvalidToken(expected string) { - if r.fatalError != nil { - return - } - if r.UseMultipleErrors { - r.pos = r.start - r.consume() - r.SkipRecursive() - switch expected { - case "[": - r.token.delimValue = ']' - r.token.kind = tokenDelim - case "{": - r.token.delimValue = '}' - r.token.kind = tokenDelim - } - r.addNonfatalError(&LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - }) - return - } - - var str string - if len(r.token.byteValue) <= maxErrorContextLen { - str = string(r.token.byteValue) - } else { - str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.pos, - Data: str, - } -} - -func (r *Lexer) GetPos() int { - return r.pos -} - -// Delim consumes a token and verifies that it is the given delimiter. -func (r *Lexer) Delim(c byte) { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() || r.token.delimValue != c { - r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. - r.errInvalidToken(string([]byte{c})) - } else { - r.consume() - } -} - -// IsDelim returns true if there was no scanning error and next token is the given delimiter. -func (r *Lexer) IsDelim(c byte) bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - return !r.Ok() || r.token.delimValue == c -} - -// Null verifies that the next token is null and consumes it. -func (r *Lexer) Null() { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenNull { - r.errInvalidToken("null") - } - r.consume() -} - -// IsNull returns true if the next token is a null keyword. -func (r *Lexer) IsNull() bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - return r.Ok() && r.token.kind == tokenNull -} - -// Skip skips a single token. -func (r *Lexer) Skip() { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - r.consume() -} - -// SkipRecursive skips next array or object completely, or just skips a single token if not -// an array/object. -// -// Note: no syntax validation is performed on the skipped data. -func (r *Lexer) SkipRecursive() { - r.scanToken() - var start, end byte - startPos := r.start - - switch r.token.delimValue { - case '{': - start, end = '{', '}' - case '[': - start, end = '[', ']' - default: - r.consume() - return - } - - r.consume() - - level := 1 - inQuotes := false - wasEscape := false - - for i, c := range r.Data[r.pos:] { - switch { - case c == start && !inQuotes: - level++ - case c == end && !inQuotes: - level-- - if level == 0 { - r.pos += i + 1 - if !json.Valid(r.Data[startPos:r.pos]) { - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "skipped array/object json value is invalid", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } - } - return - } - case c == '\\' && inQuotes: - wasEscape = !wasEscape - continue - case c == '"' && inQuotes: - inQuotes = wasEscape - case c == '"': - inQuotes = true - } - wasEscape = false - } - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "EOF reached while skipping array/object or token", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } -} - -// Raw fetches the next item recursively as a data slice -func (r *Lexer) Raw() []byte { - r.SkipRecursive() - if !r.Ok() { - return nil - } - return r.Data[r.start:r.pos] -} - -// IsStart returns whether the lexer is positioned at the start -// of an input string. -func (r *Lexer) IsStart() bool { - return r.pos == 0 -} - -// Consumed reads all remaining bytes from the input, publishing an error if -// there is anything but whitespace remaining. -func (r *Lexer) Consumed() { - if r.pos > len(r.Data) || !r.Ok() { - return - } - - for _, c := range r.Data[r.pos:] { - if c != ' ' && c != '\t' && c != '\r' && c != '\n' { - r.AddError(&LexerError{ - Reason: "invalid character '" + string(c) + "' after top-level value", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - }) - return - } - - r.pos++ - r.start++ - } -} - -func (r *Lexer) unsafeString(skipUnescape bool) (string, []byte) { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return "", nil - } - if !skipUnescape { - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "", nil - } - } - - bytes := r.token.byteValue - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret, bytes -} - -// UnsafeString returns the string value if the token is a string literal. -// -// Warning: returned string may point to the input buffer, so the string should not outlive -// the input buffer. Intended pattern of usage is as an argument to a switch statement. -func (r *Lexer) UnsafeString() string { - ret, _ := r.unsafeString(false) - return ret -} - -// UnsafeBytes returns the byte slice if the token is a string literal. -func (r *Lexer) UnsafeBytes() []byte { - _, ret := r.unsafeString(false) - return ret -} - -// UnsafeFieldName returns current member name string token -func (r *Lexer) UnsafeFieldName(skipUnescape bool) string { - ret, _ := r.unsafeString(skipUnescape) - return ret -} - -// String reads a string literal. -func (r *Lexer) String() string { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - var ret string - if r.token.byteValueCloned { - ret = bytesToStr(r.token.byteValue) - } else { - ret = string(r.token.byteValue) - } - r.consume() - return ret -} - -// StringIntern reads a string literal, and performs string interning on it. -func (r *Lexer) StringIntern() string { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - ret := intern.Bytes(r.token.byteValue) - r.consume() - return ret -} - -// Bytes reads a string literal and base64 decodes it into a byte slice. -func (r *Lexer) Bytes() []byte { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return nil - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return nil - } - ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) - n, err := base64.StdEncoding.Decode(ret, r.token.byteValue) - if err != nil { - r.fatalError = &LexerError{ - Reason: err.Error(), - } - return nil - } - - r.consume() - return ret[:n] -} - -// Bool reads a true or false boolean keyword. -func (r *Lexer) Bool() bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenBool { - r.errInvalidToken("bool") - return false - } - ret := r.token.boolValue - r.consume() - return ret -} - -func (r *Lexer) number() string { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenNumber { - r.errInvalidToken("number") - return "" - } - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret -} - -func (r *Lexer) Uint8() uint8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16() uint16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32() uint32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64() uint64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Uint() uint { - return uint(r.Uint64()) -} - -func (r *Lexer) Int8() int8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int8(n) -} - -func (r *Lexer) Int16() int16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int16(n) -} - -func (r *Lexer) Int32() int32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int32(n) -} - -func (r *Lexer) Int64() int64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Int() int { - return int(r.Int64()) -} - -func (r *Lexer) Uint8Str() uint8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16Str() uint16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32Str() uint32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64Str() uint64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) UintStr() uint { - return uint(r.Uint64Str()) -} - -func (r *Lexer) UintptrStr() uintptr { - return uintptr(r.Uint64Str()) -} - -func (r *Lexer) Int8Str() int8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int8(n) -} - -func (r *Lexer) Int16Str() int16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int16(n) -} - -func (r *Lexer) Int32Str() int32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int32(n) -} - -func (r *Lexer) Int64Str() int64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) IntStr() int { - return int(r.Int64Str()) -} - -func (r *Lexer) Float32() float32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return float32(n) -} - -func (r *Lexer) Float32Str() float32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return float32(n) -} - -func (r *Lexer) Float64() float64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Float64Str() float64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) Error() error { - return r.fatalError -} - -func (r *Lexer) AddError(e error) { - if r.fatalError == nil { - r.fatalError = e - } -} - -func (r *Lexer) AddNonFatalError(e error) { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - Reason: e.Error(), - }) -} - -func (r *Lexer) addNonfatalError(err *LexerError) { - if r.UseMultipleErrors { - // We don't want to add errors with the same offset. - if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { - return - } - r.multipleErrors = append(r.multipleErrors, err) - return - } - r.fatalError = err -} - -func (r *Lexer) GetNonFatalErrors() []*LexerError { - return r.multipleErrors -} - -// JsonNumber fetches and json.Number from 'encoding/json' package. -// Both int, float or string, contains them are valid values -func (r *Lexer) JsonNumber() json.Number { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() { - r.errInvalidToken("json.Number") - return json.Number("") - } - - switch r.token.kind { - case tokenString: - return json.Number(r.String()) - case tokenNumber: - return json.Number(r.Raw()) - case tokenNull: - r.Null() - return json.Number("") - default: - r.errSyntax() - return json.Number("") - } -} - -// Interface fetches an interface{} analogous to the 'encoding/json' package. -func (r *Lexer) Interface() interface{} { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return nil - } - switch r.token.kind { - case tokenString: - return r.String() - case tokenNumber: - return r.Float64() - case tokenBool: - return r.Bool() - case tokenNull: - r.Null() - return nil - } - - if r.token.delimValue == '{' { - r.consume() - - ret := map[string]interface{}{} - for !r.IsDelim('}') { - key := r.String() - r.WantColon() - ret[key] = r.Interface() - r.WantComma() - } - r.Delim('}') - - if r.Ok() { - return ret - } else { - return nil - } - } else if r.token.delimValue == '[' { - r.consume() - - ret := []interface{}{} - for !r.IsDelim(']') { - ret = append(ret, r.Interface()) - r.WantComma() - } - r.Delim(']') - - if r.Ok() { - return ret - } else { - return nil - } - } - r.errSyntax() - return nil -} - -// WantComma requires a comma to be present before fetching next token. -func (r *Lexer) WantComma() { - r.wantSep = ',' - r.firstElement = false -} - -// WantColon requires a colon to be present before fetching next token. -func (r *Lexer) WantColon() { - r.wantSep = ':' - r.firstElement = false -} diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go deleted file mode 100644 index 2c5b201..0000000 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ /dev/null @@ -1,405 +0,0 @@ -// Package jwriter contains a JSON writer. -package jwriter - -import ( - "io" - "strconv" - "unicode/utf8" - - "github.com/mailru/easyjson/buffer" -) - -// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but -// Flags field in Writer is used to set and pass them around. -type Flags int - -const ( - NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. - NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. -) - -// Writer is a JSON writer. -type Writer struct { - Flags Flags - - Error error - Buffer buffer.Buffer - NoEscapeHTML bool -} - -// Size returns the size of the data that was written out. -func (w *Writer) Size() int { - return w.Buffer.Size() -} - -// DumpTo outputs the data to given io.Writer, resetting the buffer. -func (w *Writer) DumpTo(out io.Writer) (written int, err error) { - return w.Buffer.DumpTo(out) -} - -// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice -// as argument that it will try to reuse. -func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.BuildBytes(reuse...), nil -} - -// ReadCloser returns an io.ReadCloser that can be used to read the data. -// ReadCloser also resets the buffer. -func (w *Writer) ReadCloser() (io.ReadCloser, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.ReadCloser(), nil -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawByte(c byte) { - w.Buffer.AppendByte(c) -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawString(s string) { - w.Buffer.AppendString(s) -} - -// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for -// calling with results of MarshalJSON-like functions. -func (w *Writer) Raw(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.Buffer.AppendBytes(data) - default: - w.RawString("null") - } -} - -// RawText encloses raw binary data in quotes and appends in to the buffer. -// Useful for calling with results of MarshalText-like functions. -func (w *Writer) RawText(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.String(string(data)) - default: - w.RawString("null") - } -} - -// Base64Bytes appends data to the buffer after base64 encoding it -func (w *Writer) Base64Bytes(data []byte) { - if data == nil { - w.Buffer.AppendString("null") - return - } - w.Buffer.AppendByte('"') - w.base64(data) - w.Buffer.AppendByte('"') -} - -func (w *Writer) Uint8(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint16(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint32(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint64(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Int8(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int16(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int32(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int64(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Uint8Str(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint16Str(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint32Str(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintStr(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint64Str(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintptrStr(n uintptr) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int8Str(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int16Str(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int32Str(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) IntStr(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int64Str(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float32(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) -} - -func (w *Writer) Float32Str(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float64(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) -} - -func (w *Writer) Float64Str(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Bool(v bool) { - w.Buffer.EnsureSpace(5) - if v { - w.Buffer.Buf = append(w.Buffer.Buf, "true"...) - } else { - w.Buffer.Buf = append(w.Buffer.Buf, "false"...) - } -} - -const chars = "0123456789abcdef" - -func getTable(falseValues ...int) [128]bool { - table := [128]bool{} - - for i := 0; i < 128; i++ { - table[i] = true - } - - for _, v := range falseValues { - table[v] = false - } - - return table -} - -var ( - htmlEscapeTable = getTable(0, 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, '"', '&', '<', '>', '\\') - htmlNoEscapeTable = getTable(0, 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, '"', '\\') -) - -func (w *Writer) String(s string) { - w.Buffer.AppendByte('"') - - // Portions of the string that contain no escapes are appended as - // byte slices. - - p := 0 // last non-escape symbol - - escapeTable := &htmlEscapeTable - if w.NoEscapeHTML { - escapeTable = &htmlNoEscapeTable - } - - for i := 0; i < len(s); { - c := s[i] - - if c < utf8.RuneSelf { - if escapeTable[c] { - // single-width character, no escaping is required - i++ - continue - } - - w.Buffer.AppendString(s[p:i]) - switch c { - case '\t': - w.Buffer.AppendString(`\t`) - case '\r': - w.Buffer.AppendString(`\r`) - case '\n': - w.Buffer.AppendString(`\n`) - case '\\': - w.Buffer.AppendString(`\\`) - case '"': - w.Buffer.AppendString(`\"`) - default: - w.Buffer.AppendString(`\u00`) - w.Buffer.AppendByte(chars[c>>4]) - w.Buffer.AppendByte(chars[c&0xf]) - } - - i++ - p = i - continue - } - - // broken utf - runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) - if runeValue == utf8.RuneError && runeWidth == 1 { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\ufffd`) - i++ - p = i - continue - } - - // jsonp stuff - tab separator and line separator - if runeValue == '\u2028' || runeValue == '\u2029' { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\u202`) - w.Buffer.AppendByte(chars[runeValue&0xf]) - i += runeWidth - p = i - continue - } - i += runeWidth - } - w.Buffer.AppendString(s[p:]) - w.Buffer.AppendByte('"') -} - -const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -const padChar = '=' - -func (w *Writer) base64(in []byte) { - - if len(in) == 0 { - return - } - - w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) - - si := 0 - n := (len(in) / 3) * 3 - - for si < n { - // Convert 3x 8bit source bytes into 4 bytes - val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) - - si += 3 - } - - remain := len(in) - si - if remain == 0 { - return - } - - // Add the remaining small block - val := uint(in[si+0]) << 16 - if remain == 2 { - val |= uint(in[si+1]) << 8 - } - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) - - switch remain { - case 2: - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) - case 1: - w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) - } -} diff --git a/vendor/github.com/mohae/deepcopy/.gitignore b/vendor/github.com/mohae/deepcopy/.gitignore deleted file mode 100644 index 5846dd1..0000000 --- a/vendor/github.com/mohae/deepcopy/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*~ -*.out -*.log diff --git a/vendor/github.com/mohae/deepcopy/.travis.yml b/vendor/github.com/mohae/deepcopy/.travis.yml deleted file mode 100644 index fd47a8c..0000000 --- a/vendor/github.com/mohae/deepcopy/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go - -go: - - tip - -matrix: - allow_failures: - - go: tip - -script: - - go test ./... diff --git a/vendor/github.com/mohae/deepcopy/LICENSE b/vendor/github.com/mohae/deepcopy/LICENSE deleted file mode 100644 index 419673f..0000000 --- a/vendor/github.com/mohae/deepcopy/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Joel - -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. diff --git a/vendor/github.com/mohae/deepcopy/README.md b/vendor/github.com/mohae/deepcopy/README.md deleted file mode 100644 index f818418..0000000 --- a/vendor/github.com/mohae/deepcopy/README.md +++ /dev/null @@ -1,8 +0,0 @@ -deepCopy -======== -[![GoDoc](https://godoc.org/github.com/mohae/deepcopy?status.svg)](https://godoc.org/github.com/mohae/deepcopy)[![Build Status](https://travis-ci.org/mohae/deepcopy.png)](https://travis-ci.org/mohae/deepcopy) - -DeepCopy makes deep copies of things: unexported field values are not copied. - -## Usage - cpy := deepcopy.Copy(orig) diff --git a/vendor/github.com/mohae/deepcopy/deepcopy.go b/vendor/github.com/mohae/deepcopy/deepcopy.go deleted file mode 100644 index ba763ad..0000000 --- a/vendor/github.com/mohae/deepcopy/deepcopy.go +++ /dev/null @@ -1,125 +0,0 @@ -// deepcopy makes deep copies of things. A standard copy will copy the -// pointers: deep copy copies the values pointed to. Unexported field -// values are not copied. -// -// Copyright (c)2014-2016, Joel Scoble (github.com/mohae), all rights reserved. -// License: MIT, for more details check the included LICENSE file. -package deepcopy - -import ( - "reflect" - "time" -) - -// Interface for delegating copy process to type -type Interface interface { - DeepCopy() interface{} -} - -// Iface is an alias to Copy; this exists for backwards compatibility reasons. -func Iface(iface interface{}) interface{} { - return Copy(iface) -} - -// Copy creates a deep copy of whatever is passed to it and returns the copy -// in an interface{}. The returned value will need to be asserted to the -// correct type. -func Copy(src interface{}) interface{} { - if src == nil { - return nil - } - - // Make the interface a reflect.Value - original := reflect.ValueOf(src) - - // Make a copy of the same type as the original. - cpy := reflect.New(original.Type()).Elem() - - // Recursively copy the original. - copyRecursive(original, cpy) - - // Return the copy as an interface. - return cpy.Interface() -} - -// copyRecursive does the actual copying of the interface. It currently has -// limited support for what it can handle. Add as needed. -func copyRecursive(original, cpy reflect.Value) { - // check for implement deepcopy.Interface - if original.CanInterface() { - if copier, ok := original.Interface().(Interface); ok { - cpy.Set(reflect.ValueOf(copier.DeepCopy())) - return - } - } - - // handle according to original's Kind - switch original.Kind() { - case reflect.Ptr: - // Get the actual value being pointed to. - originalValue := original.Elem() - - // if it isn't valid, return. - if !originalValue.IsValid() { - return - } - cpy.Set(reflect.New(originalValue.Type())) - copyRecursive(originalValue, cpy.Elem()) - - case reflect.Interface: - // If this is a nil, don't do anything - if original.IsNil() { - return - } - // Get the value for the interface, not the pointer. - originalValue := original.Elem() - - // Get the value by calling Elem(). - copyValue := reflect.New(originalValue.Type()).Elem() - copyRecursive(originalValue, copyValue) - cpy.Set(copyValue) - - case reflect.Struct: - t, ok := original.Interface().(time.Time) - if ok { - cpy.Set(reflect.ValueOf(t)) - return - } - // Go through each field of the struct and copy it. - for i := 0; i < original.NumField(); i++ { - // The Type's StructField for a given field is checked to see if StructField.PkgPath - // is set to determine if the field is exported or not because CanSet() returns false - // for settable fields. I'm not sure why. -mohae - if original.Type().Field(i).PkgPath != "" { - continue - } - copyRecursive(original.Field(i), cpy.Field(i)) - } - - case reflect.Slice: - if original.IsNil() { - return - } - // Make a new slice and copy each element. - cpy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap())) - for i := 0; i < original.Len(); i++ { - copyRecursive(original.Index(i), cpy.Index(i)) - } - - case reflect.Map: - if original.IsNil() { - return - } - cpy.Set(reflect.MakeMap(original.Type())) - for _, key := range original.MapKeys() { - originalValue := original.MapIndex(key) - copyValue := reflect.New(originalValue.Type()).Elem() - copyRecursive(originalValue, copyValue) - copyKey := Copy(key.Interface()) - cpy.SetMapIndex(reflect.ValueOf(copyKey), copyValue) - } - - default: - cpy.Set(original) - } -} diff --git a/vendor/github.com/perimeterx/marshmallow/.gitignore b/vendor/github.com/perimeterx/marshmallow/.gitignore deleted file mode 100644 index cf53c0a..0000000 --- a/vendor/github.com/perimeterx/marshmallow/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/.idea - -coverage.out -profile.out diff --git a/vendor/github.com/perimeterx/marshmallow/CHANGELOG.md b/vendor/github.com/perimeterx/marshmallow/CHANGELOG.md deleted file mode 100644 index 92937d0..0000000 --- a/vendor/github.com/perimeterx/marshmallow/CHANGELOG.md +++ /dev/null @@ -1,49 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [[1.1.5](https://github.com/PerimeterX/marshmallow/compare/v1.1.4...v1.1.5)] - 2023-07-03 - -### Added - -- Support for reporting errors from `HandleJSONData` - [info](https://github.com/PerimeterX/marshmallow/issues/27). - -## [[1.1.4](https://github.com/PerimeterX/marshmallow/compare/v1.1.3...v1.1.4)] - 2022-11-10 - -### Fixed - -- Fixed problem with nested object implementing JSONDataHandler with skipPopulateStruct - [info](https://github.com/PerimeterX/marshmallow/issues/18). -- Fixed problem with nested object implementing JSONDataHandler with skipPopulateStruct in ModeFailOverToOriginalValue - [info](https://github.com/PerimeterX/marshmallow/issues/19). - -## [[1.1.3](https://github.com/PerimeterX/marshmallow/compare/v1.1.2...v1.1.3)] - 2022-08-31 - -### Added - -- Support for excluding known fields from the result map - [info](https://github.com/PerimeterX/marshmallow/issues/16). - -## [[1.1.2](https://github.com/PerimeterX/marshmallow/compare/v1.1.1...v1.1.2)] - 2022-08-23 - -### Added - -- Support capturing nested unknown fields - [info](https://github.com/PerimeterX/marshmallow/issues/15). - -## [[1.1.1](https://github.com/PerimeterX/marshmallow/compare/v1.1.0...v1.1.1)] - 2022-08-21 - -### Fixed - -- Fix parsing bug for unknown nested fields - [info](https://github.com/PerimeterX/marshmallow/issues/12). - -## [[1.1.0](https://github.com/PerimeterX/marshmallow/compare/v0.0.1...v1.1.0)] - 2022-07-10 - -### Fixed - -- Fixed an issue with embedded fields - [info](https://github.com/PerimeterX/marshmallow/issues/9). - -## [[0.0.1](https://github.com/PerimeterX/marshmallow/tree/v0.0.1)] - 2022-04-21 - -### Added - -- All functionality from our internal repository, after it has been stabilized on production for several months - [info](https://www.perimeterx.com/tech-blog/2022/boosting-up-json-performance-of-unstructured-structs-in-go/). diff --git a/vendor/github.com/perimeterx/marshmallow/CODE_OF_CONDUCT.md b/vendor/github.com/perimeterx/marshmallow/CODE_OF_CONDUCT.md deleted file mode 100644 index 0f6c45e..0000000 --- a/vendor/github.com/perimeterx/marshmallow/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,133 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -[opensource-conduct@humansecurity.com](mailto:opensource-conduct@humansecurity.com). -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/vendor/github.com/perimeterx/marshmallow/CONTRIBUTING.md b/vendor/github.com/perimeterx/marshmallow/CONTRIBUTING.md deleted file mode 100644 index a265c9a..0000000 --- a/vendor/github.com/perimeterx/marshmallow/CONTRIBUTING.md +++ /dev/null @@ -1,47 +0,0 @@ -# How To Contribute - -We'd love to accept your patches and contributions to this project. There are just a few guidelines you need to follow which are described in detail below. - -## 1. Fork this repo - -You should create a fork of this project in your account and work from there. You can create a fork by clicking the fork button in GitHub. - -## 2. One feature, one branch - -Work for each new feature/issue should occur in its own branch. To create a new branch from the command line: -```shell -git checkout -b my-new-feature -``` -where "my-new-feature" describes what you're working on. - -## 3. Add unit tests -If your contribution modifies existing or adds new code please add corresponding unit tests for this. - -## 4. Ensure that the build passes - -Run -```shell -go test -v -``` -and check that there are no errors. - -## 5. Add documentation for new or updated functionality - -Please review the [README.md](README.md) file in this project to see if they are impacted by your change and update them accordingly. - -## 6. Add to CHANGELOG.md - -Any notable changes should be recorded in the CHANGELOG.md following the [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) conventions. - -## 7. Submit a pull request and describe the change - -Push your changes to your branch and open a pull request against the parent repo on GitHub. The project administrators will review your pull request and respond with feedback. - -# How your contribution gets merged - -Upon pull request submission, your code will be reviewed by the maintainers. They will confirm at least the following: - -- Tests run successfully (unit, coverage, style). -- Contribution policy has been followed. - -A (human) reviewer will need to sign off on your pull request before it can be merged. diff --git a/vendor/github.com/perimeterx/marshmallow/LICENSE b/vendor/github.com/perimeterx/marshmallow/LICENSE deleted file mode 100644 index 8ffe869..0000000 --- a/vendor/github.com/perimeterx/marshmallow/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 PerimeterX - -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. diff --git a/vendor/github.com/perimeterx/marshmallow/README.md b/vendor/github.com/perimeterx/marshmallow/README.md deleted file mode 100644 index bfa9036..0000000 --- a/vendor/github.com/perimeterx/marshmallow/README.md +++ /dev/null @@ -1,205 +0,0 @@ -# Marshmallow - -![Marshmallow Campfire](https://raw.githubusercontent.com/PerimeterX/marshmallow/assets/campfire.png) - -[![CodeQL Status](https://img.shields.io/github/actions/workflow/status/perimeterx/marshmallow/codeql.yml?branch=main&logo=github&label=CodeQL)](https://github.com/PerimeterX/marshmallow/actions/workflows/codeql.yml?query=branch%3Amain++) -[![Run Tests](https://img.shields.io/github/actions/workflow/status/perimeterx/marshmallow/go.yml?branch=main&logo=github&label=Run%20Tests)](https://github.com/PerimeterX/marshmallow/actions/workflows/go.yml?query=branch%3Amain) -[![Dependency Review](https://img.shields.io/github/actions/workflow/status/perimeterx/marshmallow/dependency-review.yml?logo=github&label=Dependency%20Review)](https://github.com/PerimeterX/marshmallow/actions/workflows/dependency-review.yml?query=branch%3Amain) -[![Go Report Card](https://goreportcard.com/badge/github.com/perimeterx/marshmallow)](https://goreportcard.com/report/github.com/perimeterx/marshmallow) -![Manual Code Coverage](https://img.shields.io/badge/coverage-92.6%25-green) -[![Go Reference](https://pkg.go.dev/badge/github.com/perimeterx/marshmallow.svg)](https://pkg.go.dev/github.com/perimeterx/marshmallow) -[![Licence](https://img.shields.io/github/license/perimeterx/marshmallow)](LICENSE) -[![Latest Release](https://img.shields.io/github/v/release/perimeterx/marshmallow)](https://github.com/PerimeterX/marshmallow/releases) -![Top Languages](https://img.shields.io/github/languages/top/perimeterx/marshmallow) -[![Issues](https://img.shields.io/github/issues-closed/perimeterx/marshmallow?color=%238250df&logo=github)](https://github.com/PerimeterX/marshmallow/issues) -[![Pull Requests](https://img.shields.io/github/issues-pr-closed-raw/perimeterx/marshmallow?color=%238250df&label=merged%20pull%20requests&logo=github)](https://github.com/PerimeterX/marshmallow/pulls) -[![Commits](https://img.shields.io/github/last-commit/perimeterx/marshmallow)](https://github.com/PerimeterX/marshmallow/commits/main) -[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](CODE_OF_CONDUCT.md) - -marshmallow-gopher - -Marshmallow package provides a simple API to perform flexible and performant JSON unmarshalling in Go. - -Marshmallow specializes in dealing with **unstructured struct** - when some fields are known and some aren't, -with zero performance overhead nor extra coding needed. -While unmarshalling, marshmallow allows fully retaining the original data and access -it via a typed struct and a dynamic map. - -## Contents - -- [Install](#install) -- [Usage](#usage) -- [Performance Benchmark And Alternatives](#performance-benchmark-and-alternatives) -- [When Should I Use Marshmallow](#when-should-i-use-marshmallow) -- [API](#api) - -## Install - -```sh -go get -u github.com/perimeterx/marshmallow -``` - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/perimeterx/marshmallow" -) - -func main() { - v := struct { - Foo string `json:"foo"` - Boo []int `json:"boo"` - }{} - result, err := marshmallow.Unmarshal([]byte(`{"foo":"bar","boo":[1,2,3],"goo":12.6}`), &v) - fmt.Printf("v=%+v, result=%+v, err=%v", v, result, err) - // Output: v={Foo:bar Boo:[1 2 3]}, result=map[boo:[1 2 3] foo:bar goo:12.6], err= -} -``` - -**Examples can be found [here](example_test.go)** - -## Performance Benchmark And Alternatives - -Marshmallow performs best when dealing with mixed data - when some fields are known and some are unknown. -More info [below](#when-should-i-use-marshmallow). -Other solutions are available for this kind of use case, each solution is explained and documented in the link below. -The full benchmark test can be found -[here](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go). - -|Benchmark|Iterations|Time/Iteration|Bytes Allocated|Allocations| -|--|--|--|--|--| -|[unmarshall twice](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L40)|228693|5164 ns/op|1640 B/op|51 allocs/op| -|[raw map](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L66)|232236|5116 ns/op|2296 B/op|53 allocs/op| -|[go codec](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L121)|388442|3077 ns/op|2512 B/op|37 allocs/op| -|[marshmallow](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L16)|626168|1853 ns/op|608 B/op|18 allocs/op| -|[marshmallow without populating struct](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L162)|678616|1751 ns/op|608 B/op|18 allocs/op| - -![marshmallow performance comparison](https://raw.githubusercontent.com/PerimeterX/marshmallow/e45088ca20d4ea5be4143d418d12da63a68d6dfd/performance-chart.svg) - -**Marshmallow provides the best performance (up to X3 faster) while not requiring any extra coding.** -In fact, marshmallow performs as fast as normal `json.Unmarshal` call, however, such a call causes loss of data for all -the fields that did not match the given struct. With marshmallow you never lose any data. - -|Benchmark|Iterations|Time/Iteration|Bytes Allocated|Allocations| -|--|--|--|--|--| -|[marshmallow](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L16)|626168|1853 ns/op|608 B/op|18 allocs/op| -|[native library](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L143)|652106|1845 ns/op|304 B/op|11 allocs/op| -|[marshmallow without populating struct](https://github.com/PerimeterX/marshmallow/blob/8c5bba9e6dc0033f4324eca554737089a99f6e5e/benchmark_test.go#L162)|678616|1751 ns/op|608 B/op|18 allocs/op| - -## When Should I Use Marshmallow - -Marshmallow is best suited for use cases where you are interested in all the input data, but you have predetermined -information only about a subset of it. For instance, if you plan to reference two specific fields from the data, then -iterate all the data and apply some generic logic. How does it look with the native library: - -```go -func isAllowedToDrive(data []byte) (bool, error) { - result := make(map[string]interface{}) - err := json.Unmarshal(data, &result) - if err != nil { - return false, err - } - - age, ok := result["age"] - if !ok { - return false, nil - } - a, ok := age.(float64) - if !ok { - return false, nil - } - if a < 17 { - return false, nil - } - - hasDriversLicense, ok := result["has_drivers_license"] - if !ok { - return false, nil - } - h, ok := hasDriversLicense.(bool) - if !ok { - return false, nil - } - if !h { - return false, nil - } - - for key := range result { - if strings.Contains(key, "prior_conviction") { - return false, nil - } - } - - return true, nil -} -``` - -And with marshmallow: - -```go -func isAllowedToDrive(data []byte) (bool, error) { - v := struct { - Age int `json:"age"` - HasDriversLicense bool `json:"has_drivers_license"` - }{} - result, err := marshmallow.Unmarshal(data, &v) - if err != nil { - return false, err - } - - if v.Age < 17 || !v.HasDriversLicense { - return false, nil - } - - for key := range result { - if strings.Contains(key, "prior_conviction") { - return false, nil - } - } - - return true, nil -} -``` - -## API - -Marshmallow exposes two main API functions - -[Unmarshal](https://github.com/PerimeterX/marshmallow/blob/0e0218ab860be8a4b5f57f5ff239f281c250c5da/unmarshal.go#L27) -and -[UnmarshalFromJSONMap](https://github.com/PerimeterX/marshmallow/blob/0e0218ab860be8a4b5f57f5ff239f281c250c5da/unmarshal_from_json_map.go#L37). -While unmarshalling, marshmallow supports the following optional options: - -* Setting the mode for handling invalid data using the [WithMode](https://github.com/PerimeterX/marshmallow/blob/0e0218ab860be8a4b5f57f5ff239f281c250c5da/options.go#L30) function. -* Excluding known fields from the result map using the [WithExcludeKnownFieldsFromMap](https://github.com/PerimeterX/marshmallow/blob/457669ae9973895584f2636eabfc104140d3b700/options.go#L50) function. -* Skipping struct population to boost performance using the [WithSkipPopulateStruct](https://github.com/PerimeterX/marshmallow/blob/0e0218ab860be8a4b5f57f5ff239f281c250c5da/options.go#L41) function. - -In order to capture unknown nested fields, structs must implement [JSONDataErrorHandler](https://github.com/PerimeterX/marshmallow/blob/195c994aa6e3e0852601ad9cf65bcddef0dd7479/options.go#L76). -More info [here](https://github.com/PerimeterX/marshmallow/issues/15). - -Marshmallow also supports caching of refection information using -[EnableCache](https://github.com/PerimeterX/marshmallow/blob/d3500aa5b0f330942b178b155da933c035dd3906/cache.go#L40) -and -[EnableCustomCache](https://github.com/PerimeterX/marshmallow/blob/d3500aa5b0f330942b178b155da933c035dd3906/cache.go#L35). - -## Contact and Contribute - -Reporting issues and requesting features may be done in our [GitHub issues page](https://github.com/PerimeterX/marshmallow/issues). -Discussions may be conducted in our [GitHub discussions page](https://github.com/PerimeterX/marshmallow/discussions). -For any further questions or comments you can reach us out at [open-source@humansecurity.com](mailto:open-source@humansecurity.com). - -Any type of contribution is warmly welcome and appreciated ❤️ -Please read our [contribution](CONTRIBUTING.md) guide for more info. - -If you're looking for something to get started with, tou can always follow our [issues page](https://github.com/PerimeterX/marshmallow/issues) and look for -[good first issue](https://github.com/PerimeterX/marshmallow/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) and -[help wanted](https://github.com/PerimeterX/marshmallow/issues?q=is%3Aissue+label%3A%22help+wanted%22+is%3Aopen) labels. - -## Marshmallow Logo - -Marshmallow logo and assets by [Adva Rom](https://www.linkedin.com/in/adva-rom-7a6738127/) are licensed under a Creative Commons Attribution 4.0 International License.
- -![Marshmallow Logo](https://raw.githubusercontent.com/PerimeterX/marshmallow/assets/marshmallow.png) diff --git a/vendor/github.com/perimeterx/marshmallow/cache.go b/vendor/github.com/perimeterx/marshmallow/cache.go deleted file mode 100644 index a67cea6..0000000 --- a/vendor/github.com/perimeterx/marshmallow/cache.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -import ( - "reflect" - "sync" -) - -// Cache allows unmarshalling to use a cached version of refection information about types. -// Cache interface follows the implementation of sync.Map, but you may wrap any cache implementation -// to match it. This allows you to control max cache size, eviction policies and any other caching aspect. -type Cache interface { - // Load returns the value stored in the map for a key, or nil if no value is present. - // The ok result indicates whether value was found in the map. - Load(key interface{}) (interface{}, bool) - // Store sets the value for a key. - Store(key, value interface{}) -} - -// EnableCustomCache enables unmarshalling cache. It allows reuse of refection information about types needed -// to perform the unmarshalling. A use of such cache can boost up unmarshalling by x1.4. -// Check out benchmark_test.go for an example. -// -// EnableCustomCache is not thread safe! Do not use it while performing unmarshalling, or it will -// cause an unsafe race condition. Typically, EnableCustomCache should be called once when the process boots. -// -// Caching is disabled by default. The use of this function allows enabling it and controlling the -// behavior of the cache. Typically, the use of sync.Map should be good enough. The caching mechanism -// stores a single map per struct type. If you plan to unmarshal a huge amount of distinct -// struct it may get to consume a lot of resources, in which case you have the control to choose -// the caching implementation you like and its setup. -func EnableCustomCache(c Cache) { - cache = c -} - -// EnableCache enables unmarshalling cache with default implementation. More info at EnableCustomCache. -func EnableCache() { - EnableCustomCache(&sync.Map{}) -} - -var cache Cache - -func cacheLookup(t reflect.Type) map[string]reflectionInfo { - if cache == nil { - return nil - } - value, exists := cache.Load(t) - if !exists { - return nil - } - result, _ := value.(map[string]reflectionInfo) - return result -} - -func cacheStore(t reflect.Type, fields map[string]reflectionInfo) { - if cache == nil { - return - } - cache.Store(t, fields) -} diff --git a/vendor/github.com/perimeterx/marshmallow/doc.go b/vendor/github.com/perimeterx/marshmallow/doc.go deleted file mode 100644 index c179e65..0000000 --- a/vendor/github.com/perimeterx/marshmallow/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -/* -Package marshmallow provides a simple API to perform flexible and performant JSON unmarshalling. -Unlike other packages, marshmallow supports unmarshalling of some known and some unknown fields -with zero performance overhead nor extra coding needed. While unmarshalling, -marshmallow allows fully retaining the original data and access it via a typed struct and a -dynamic map. - -https://github.com/perimeterx/marshmallow -*/ -package marshmallow diff --git a/vendor/github.com/perimeterx/marshmallow/errors.go b/vendor/github.com/perimeterx/marshmallow/errors.go deleted file mode 100644 index c4d341c..0000000 --- a/vendor/github.com/perimeterx/marshmallow/errors.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -import ( - "errors" - "fmt" - "github.com/mailru/easyjson/jlexer" - "reflect" - "strings" -) - -var ( - // ErrInvalidInput indicates the input JSON is invalid - ErrInvalidInput = errors.New("invalid JSON input") - - // ErrInvalidValue indicates the target struct has invalid type - ErrInvalidValue = errors.New("unexpected non struct value") -) - -// MultipleLexerError indicates one or more unmarshalling errors during JSON bytes decode -type MultipleLexerError struct { - Errors []*jlexer.LexerError -} - -func (m *MultipleLexerError) Error() string { - errs := make([]string, len(m.Errors)) - for i, lexerError := range m.Errors { - errs[i] = lexerError.Error() - } - return strings.Join(errs, ", ") -} - -// MultipleError indicates one or more unmarshalling errors during JSON map decode -type MultipleError struct { - Errors []error -} - -func (m *MultipleError) Error() string { - errs := make([]string, len(m.Errors)) - for i, lexerError := range m.Errors { - errs[i] = lexerError.Error() - } - return strings.Join(errs, ", ") -} - -// ParseError indicates a JSON map decode error -type ParseError struct { - Reason string - Path string -} - -func (p *ParseError) Error() string { - return fmt.Sprintf("parse error: %s in %s", p.Reason, p.Path) -} - -func newUnexpectedTypeParseError(expectedType reflect.Type, path []string) *ParseError { - return &ParseError{ - Reason: fmt.Sprintf("expected type %s", externalTypeName(expectedType)), - Path: strings.Join(path, "."), - } -} - -func newUnsupportedTypeParseError(unsupportedType reflect.Type, path []string) *ParseError { - return &ParseError{ - Reason: fmt.Sprintf("unsupported type %s", externalTypeName(unsupportedType)), - Path: strings.Join(path, "."), - } -} - -func addUnexpectedTypeLexerError(lexer *jlexer.Lexer, expectedType reflect.Type) { - lexer.AddNonFatalError(fmt.Errorf("expected type %s", externalTypeName(expectedType))) -} - -func addUnsupportedTypeLexerError(lexer *jlexer.Lexer, unsupportedType reflect.Type) { - lexer.AddNonFatalError(fmt.Errorf("unsupported type %s", externalTypeName(unsupportedType))) -} - -func externalTypeName(t reflect.Type) string { - switch t.Kind() { - case reflect.String: - return "string" - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, - reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, - reflect.Float64, reflect.Complex64, reflect.Complex128: - return "number" - case reflect.Bool: - return "boolean" - case reflect.Array, reflect.Slice: - return "array" - case reflect.Interface: - return "any" - case reflect.Map, reflect.Struct: - return "object" - case reflect.Ptr: - return externalTypeName(t.Elem()) - } - return "invalid" -} diff --git a/vendor/github.com/perimeterx/marshmallow/options.go b/vendor/github.com/perimeterx/marshmallow/options.go deleted file mode 100644 index ff97d33..0000000 --- a/vendor/github.com/perimeterx/marshmallow/options.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -// Mode dictates the unmarshalling mode. -// Each mode is self documented below. -type Mode uint8 - -const ( - // ModeFailOnFirstError is the default mode. It makes unmarshalling terminate - // immediately on any kind of error. This error will then be returned. - ModeFailOnFirstError Mode = iota - - // ModeAllowMultipleErrors mode makes unmarshalling keep decoding even if - // errors are encountered. In case of such error, the erroneous value will be omitted from the result. - // Eventually, all errors will all be returned, alongside the partial result. - ModeAllowMultipleErrors - - // ModeFailOverToOriginalValue mode makes unmarshalling keep decoding even if - // errors are encountered. In case of such error, the original external value be placed in the - // result data, even though it does not meet the schematic requirements. - // Eventually, all errors will be returned, alongside the full result. Note that the result map - // will contain values that do not match the struct schema. - ModeFailOverToOriginalValue -) - -// WithMode is an UnmarshalOption function to set the unmarshalling mode. -func WithMode(mode Mode) UnmarshalOption { - return func(options *unmarshalOptions) { - options.mode = mode - } -} - -// WithSkipPopulateStruct is an UnmarshalOption function to set the skipPopulateStruct option. -// Skipping populate struct is set to false by default. -// If you do not intend to use the struct value once unmarshalling is finished, set this -// option to true to boost performance. This would mean the struct fields will not be set -// with values, but rather it will only be used as the target schema when populating the result map. -func WithSkipPopulateStruct(skipPopulateStruct bool) UnmarshalOption { - return func(options *unmarshalOptions) { - options.skipPopulateStruct = skipPopulateStruct - } -} - -// WithExcludeKnownFieldsFromMap is an UnmarshalOption function to set the excludeKnownFieldsFromMap option. -// Exclude known fields flag is set to false by default. -// When the flag is set to true, fields specified in the input struct (known fields) will be excluded from the result map -func WithExcludeKnownFieldsFromMap(excludeKnownFields bool) UnmarshalOption { - return func(options *unmarshalOptions) { - options.excludeKnownFieldsFromMap = excludeKnownFields - } -} - -type UnmarshalOption func(*unmarshalOptions) - -type unmarshalOptions struct { - mode Mode - skipPopulateStruct bool - excludeKnownFieldsFromMap bool -} - -func buildUnmarshalOptions(options []UnmarshalOption) *unmarshalOptions { - result := &unmarshalOptions{} - for _, option := range options { - option(result) - } - return result -} - -// JSONDataErrorHandler allow types to handle JSON data as maps. -// Types should implement this interface if they wish to act on the map representation of parsed JSON input. -// This is mainly used to allow nested objects to capture unknown fields and leverage marshmallow's abilities. -// If HandleJSONData returns an error, it will be propagated as an unmarshal error -type JSONDataErrorHandler interface { - HandleJSONData(data map[string]interface{}) error -} - -// Deprecated: use JSONDataErrorHandler instead -type JSONDataHandler interface { - HandleJSONData(data map[string]interface{}) -} - -func asJSONDataHandler(value interface{}) (func(map[string]interface{}) error, bool) { - if handler, ok := value.(JSONDataErrorHandler); ok { - return handler.HandleJSONData, true - } - if handler, ok := value.(JSONDataHandler); ok { - return func(m map[string]interface{}) error { - handler.HandleJSONData(m) - return nil - }, true - } - return nil, false -} diff --git a/vendor/github.com/perimeterx/marshmallow/reflection.go b/vendor/github.com/perimeterx/marshmallow/reflection.go deleted file mode 100644 index 9b7d88c..0000000 --- a/vendor/github.com/perimeterx/marshmallow/reflection.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -import ( - "encoding/json" - "reflect" - "strings" -) - -var unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - -type reflectionInfo struct { - path []int - t reflect.Type -} - -func (r reflectionInfo) field(target reflect.Value) reflect.Value { - current := target - for _, i := range r.path { - current = current.Field(i) - } - return current -} - -func mapStructFields(target interface{}) map[string]reflectionInfo { - t := reflectStructType(target) - result := cacheLookup(t) - if result != nil { - return result - } - result = make(map[string]reflectionInfo, t.NumField()) - mapTypeFields(t, result, nil) - cacheStore(t, result) - return result -} - -func mapTypeFields(t reflect.Type, result map[string]reflectionInfo, path []int) { - num := t.NumField() - for i := 0; i < num; i++ { - field := t.Field(i) - fieldPath := append(path, i) - if field.Anonymous && field.Type.Kind() == reflect.Struct { - mapTypeFields(field.Type, result, fieldPath) - continue - } - name := field.Tag.Get("json") - if name == "" || name == "-" { - continue - } - if index := strings.Index(name, ","); index > -1 { - name = name[:index] - } - result[name] = reflectionInfo{ - path: fieldPath, - t: field.Type, - } - } -} - -func reflectStructValue(target interface{}) reflect.Value { - v := reflect.ValueOf(target) - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - return v -} - -func reflectStructType(target interface{}) reflect.Type { - t := reflect.TypeOf(target) - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t -} - -var primitiveConverters = map[reflect.Kind]func(v interface{}) (interface{}, bool){ - reflect.Bool: func(v interface{}) (interface{}, bool) { - res, ok := v.(bool) - return res, ok - }, - reflect.Int: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return int(res), true - } - return v, false - }, - reflect.Int8: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return int8(res), true - } - return v, false - }, - reflect.Int16: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return int16(res), true - } - return v, false - }, - reflect.Int32: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return int32(res), true - } - return v, false - }, - reflect.Int64: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return int64(res), true - } - return v, false - }, - reflect.Uint: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return uint(res), true - } - return v, false - }, - reflect.Uint8: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return uint8(res), true - } - return v, false - }, - reflect.Uint16: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return uint16(res), true - } - return v, false - }, - reflect.Uint32: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return uint32(res), true - } - return v, false - }, - reflect.Uint64: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return uint64(res), true - } - return v, false - }, - reflect.Float32: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return float32(res), true - } - return v, false - }, - reflect.Float64: func(v interface{}) (interface{}, bool) { - res, ok := v.(float64) - if ok { - return res, true - } - return v, false - }, - reflect.Interface: func(v interface{}) (interface{}, bool) { - return v, true - }, - reflect.String: func(v interface{}) (interface{}, bool) { - res, ok := v.(string) - return res, ok - }, -} - -func assignValue(field reflect.Value, value interface{}) { - if value == nil { - return - } - reflectValue := reflect.ValueOf(value) - if reflectValue.Type().AssignableTo(field.Type()) { - field.Set(reflectValue) - } -} - -func isValidValue(v interface{}) bool { - value := reflect.ValueOf(v) - return value.Kind() == reflect.Ptr && value.Elem().Kind() == reflect.Struct && !value.IsNil() -} - -func safeReflectValue(t reflect.Type, v interface{}) reflect.Value { - if v == nil { - return reflect.Zero(t) - } - return reflect.ValueOf(v) -} diff --git a/vendor/github.com/perimeterx/marshmallow/unmarshal.go b/vendor/github.com/perimeterx/marshmallow/unmarshal.go deleted file mode 100644 index 160ea30..0000000 --- a/vendor/github.com/perimeterx/marshmallow/unmarshal.go +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -import ( - "encoding/json" - "github.com/mailru/easyjson/jlexer" - "reflect" -) - -// Unmarshal parses the JSON-encoded object in data and stores the values -// in the struct pointed to by v and in the returned map. -// If v is nil or not a pointer to a struct, Unmarshal returns an ErrInvalidValue. -// If data is not a valid JSON or not a JSON object Unmarshal returns an ErrInvalidInput. -// -// Unmarshal follows the rules of json.Unmarshal with the following exceptions: -// - All input fields are stored in the resulting map, including fields that do not exist in the -// struct pointed by v. -// - Unmarshal only operates on JSON object inputs. It will reject all other types of input -// by returning ErrInvalidInput. -// - Unmarshal only operates on struct values. It will reject all other types of v by -// returning ErrInvalidValue. -// - Unmarshal supports three types of Mode values. Each mode is self documented and affects -// how Unmarshal behaves. -func Unmarshal(data []byte, v interface{}, options ...UnmarshalOption) (map[string]interface{}, error) { - if !isValidValue(v) { - return nil, ErrInvalidValue - } - opts := buildUnmarshalOptions(options) - useMultipleErrors := opts.mode == ModeAllowMultipleErrors || opts.mode == ModeFailOverToOriginalValue - d := &decoder{options: opts, lexer: &jlexer.Lexer{Data: data, UseMultipleErrors: useMultipleErrors}} - result := make(map[string]interface{}) - if d.lexer.IsNull() { - d.lexer.Skip() - } else if !d.lexer.IsDelim('{') { - return nil, ErrInvalidInput - } else { - d.populateStruct(false, v, result) - } - d.lexer.Consumed() - if useMultipleErrors { - errors := d.lexer.GetNonFatalErrors() - if len(errors) == 0 { - return result, nil - } - return result, &MultipleLexerError{Errors: errors} - } - err := d.lexer.Error() - if err != nil { - return nil, err - } - return result, nil -} - -type decoder struct { - options *unmarshalOptions - lexer *jlexer.Lexer -} - -func (d *decoder) populateStruct(forcePopulate bool, structInstance interface{}, result map[string]interface{}) (interface{}, bool) { - doPopulate := !d.options.skipPopulateStruct || forcePopulate - var structValue reflect.Value - if doPopulate { - structValue = reflectStructValue(structInstance) - } - fields := mapStructFields(structInstance) - var clone map[string]interface{} - if d.options.mode == ModeFailOverToOriginalValue { - clone = make(map[string]interface{}, len(fields)) - } - d.lexer.Delim('{') - for !d.lexer.IsDelim('}') { - key := d.lexer.UnsafeFieldName(false) - d.lexer.WantColon() - refInfo, exists := fields[key] - if exists { - value, isValidType := d.valueByReflectType(refInfo.t) - if isValidType { - if value != nil && doPopulate { - field := refInfo.field(structValue) - assignValue(field, value) - } - if !d.options.excludeKnownFieldsFromMap { - if result != nil { - result[key] = value - } - if clone != nil { - clone[key] = value - } - } - } else { - switch d.options.mode { - case ModeFailOnFirstError: - return nil, false - case ModeFailOverToOriginalValue: - if !forcePopulate { - result[key] = value - } else { - clone[key] = value - d.lexer.WantComma() - d.drainLexerMap(clone) - return clone, false - } - } - } - } else { - value := d.lexer.Interface() - if result != nil { - result[key] = value - } - if clone != nil { - clone[key] = value - } - } - d.lexer.WantComma() - } - d.lexer.Delim('}') - return structInstance, true -} - -func (d *decoder) valueByReflectType(t reflect.Type) (interface{}, bool) { - if t.Implements(unmarshalerType) { - result := reflect.New(t.Elem()).Interface() - d.valueFromCustomUnmarshaler(result.(json.Unmarshaler)) - return result, true - } - if reflect.PtrTo(t).Implements(unmarshalerType) { - value := reflect.New(t) - d.valueFromCustomUnmarshaler(value.Interface().(json.Unmarshaler)) - return value.Elem().Interface(), true - } - kind := t.Kind() - if converter := primitiveConverters[kind]; converter != nil { - v := d.lexer.Interface() - if v == nil { - return nil, true - } - converted, ok := converter(v) - if !ok { - addUnexpectedTypeLexerError(d.lexer, t) - return v, false - } - return converted, true - } - switch kind { - case reflect.Slice: - return d.buildSlice(t) - case reflect.Array: - return d.buildArray(t) - case reflect.Map: - return d.buildMap(t) - case reflect.Struct: - value, valid := d.buildStruct(t) - if value == nil { - return nil, valid - } - if !valid { - return value, false - } - return reflect.ValueOf(value).Elem().Interface(), valid - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct { - return d.buildStruct(t.Elem()) - } - value, valid := d.valueByReflectType(t.Elem()) - if value == nil { - return nil, valid - } - if !valid { - return value, false - } - result := reflect.New(reflect.TypeOf(value)) - result.Elem().Set(reflect.ValueOf(value)) - return result.Interface(), valid - } - addUnsupportedTypeLexerError(d.lexer, t) - return nil, false -} - -func (d *decoder) buildSlice(sliceType reflect.Type) (interface{}, bool) { - if d.lexer.IsNull() { - d.lexer.Skip() - return nil, true - } - if !d.lexer.IsDelim('[') { - addUnexpectedTypeLexerError(d.lexer, sliceType) - return d.lexer.Interface(), false - } - elemType := sliceType.Elem() - d.lexer.Delim('[') - var sliceValue reflect.Value - if !d.lexer.IsDelim(']') { - sliceValue = reflect.MakeSlice(sliceType, 0, 4) - } else { - sliceValue = reflect.MakeSlice(sliceType, 0, 0) - } - for !d.lexer.IsDelim(']') { - current, valid := d.valueByReflectType(elemType) - if !valid { - if d.options.mode != ModeFailOverToOriginalValue { - d.drainLexerArray(nil) - return nil, true - } - result := d.cloneReflectArray(sliceValue, -1) - result = append(result, current) - return d.drainLexerArray(result), true - } - sliceValue = reflect.Append(sliceValue, safeReflectValue(elemType, current)) - d.lexer.WantComma() - } - d.lexer.Delim(']') - return sliceValue.Interface(), true -} - -func (d *decoder) buildArray(arrayType reflect.Type) (interface{}, bool) { - if d.lexer.IsNull() { - d.lexer.Skip() - return nil, true - } - if !d.lexer.IsDelim('[') { - addUnexpectedTypeLexerError(d.lexer, arrayType) - return d.lexer.Interface(), false - } - elemType := arrayType.Elem() - arrayValue := reflect.New(arrayType).Elem() - d.lexer.Delim('[') - for i := 0; !d.lexer.IsDelim(']'); i++ { - current, valid := d.valueByReflectType(elemType) - if !valid { - if d.options.mode != ModeFailOverToOriginalValue { - d.drainLexerArray(nil) - return nil, true - } - result := d.cloneReflectArray(arrayValue, i) - result = append(result, current) - return d.drainLexerArray(result), true - } - if current != nil { - arrayValue.Index(i).Set(reflect.ValueOf(current)) - } - d.lexer.WantComma() - } - d.lexer.Delim(']') - return arrayValue.Interface(), true -} - -func (d *decoder) buildMap(mapType reflect.Type) (interface{}, bool) { - if d.lexer.IsNull() { - d.lexer.Skip() - return nil, true - } - if !d.lexer.IsDelim('{') { - addUnexpectedTypeLexerError(d.lexer, mapType) - return d.lexer.Interface(), false - } - d.lexer.Delim('{') - keyType := mapType.Key() - valueType := mapType.Elem() - mapValue := reflect.MakeMap(mapType) - for !d.lexer.IsDelim('}') { - key, valid := d.valueByReflectType(keyType) - if !valid { - if d.options.mode != ModeFailOverToOriginalValue { - d.lexer.WantColon() - d.lexer.Interface() - d.lexer.WantComma() - d.drainLexerMap(make(map[string]interface{})) - return nil, true - } - strKey, _ := key.(string) - d.lexer.WantColon() - value := d.lexer.Interface() - result := d.cloneReflectMap(mapValue) - result[strKey] = value - d.lexer.WantComma() - d.drainLexerMap(result) - return result, true - } - d.lexer.WantColon() - value, valid := d.valueByReflectType(valueType) - if !valid { - if d.options.mode != ModeFailOverToOriginalValue { - d.lexer.WantComma() - d.drainLexerMap(make(map[string]interface{})) - return nil, true - } - strKey, _ := key.(string) - result := d.cloneReflectMap(mapValue) - result[strKey] = value - d.lexer.WantComma() - d.drainLexerMap(result) - return result, true - } - mapValue.SetMapIndex(safeReflectValue(keyType, key), safeReflectValue(valueType, value)) - d.lexer.WantComma() - } - d.lexer.Delim('}') - return mapValue.Interface(), true -} - -func (d *decoder) buildStruct(structType reflect.Type) (interface{}, bool) { - if d.lexer.IsNull() { - d.lexer.Skip() - return nil, true - } - if !d.lexer.IsDelim('{') { - addUnexpectedTypeLexerError(d.lexer, structType) - return d.lexer.Interface(), false - } - value := reflect.New(structType).Interface() - handler, ok := asJSONDataHandler(value) - if !ok { - return d.populateStruct(true, value, nil) - } - data := make(map[string]interface{}) - result, valid := d.populateStruct(true, value, data) - if !valid { - return result, false - } - err := handler(data) - if err != nil { - d.lexer.AddNonFatalError(err) - return result, false - } - return result, true -} - -func (d *decoder) valueFromCustomUnmarshaler(unmarshaler json.Unmarshaler) { - data := d.lexer.Raw() - if !d.lexer.Ok() { - return - } - err := unmarshaler.UnmarshalJSON(data) - if err != nil { - d.lexer.AddNonFatalError(err) - } -} - -func (d *decoder) cloneReflectArray(value reflect.Value, length int) []interface{} { - if length == -1 { - length = value.Len() - } - result := make([]interface{}, length) - for i := 0; i < length; i++ { - result[i] = value.Index(i).Interface() - } - return result -} - -func (d *decoder) cloneReflectMap(mapValue reflect.Value) map[string]interface{} { - l := mapValue.Len() - result := make(map[string]interface{}, l) - for _, key := range mapValue.MapKeys() { - value := mapValue.MapIndex(key) - strKey, _ := key.Interface().(string) - result[strKey] = value.Interface() - } - return result -} - -func (d *decoder) drainLexerArray(target []interface{}) interface{} { - d.lexer.WantComma() - for !d.lexer.IsDelim(']') { - current := d.lexer.Interface() - target = append(target, current) - d.lexer.WantComma() - } - d.lexer.Delim(']') - return target -} - -func (d *decoder) drainLexerMap(target map[string]interface{}) { - for !d.lexer.IsDelim('}') { - key := d.lexer.String() - d.lexer.WantColon() - value := d.lexer.Interface() - target[key] = value - d.lexer.WantComma() - } - d.lexer.Delim('}') -} diff --git a/vendor/github.com/perimeterx/marshmallow/unmarshal_from_json_map.go b/vendor/github.com/perimeterx/marshmallow/unmarshal_from_json_map.go deleted file mode 100644 index 0907f8f..0000000 --- a/vendor/github.com/perimeterx/marshmallow/unmarshal_from_json_map.go +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright 2022 PerimeterX. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package marshmallow - -import ( - "reflect" -) - -// UnmarshalerFromJSONMap is the interface implemented by types -// that can unmarshal a JSON description of themselves. -// In case you want to implement custom unmarshalling, json.Unmarshaler only supports -// receiving the data as []byte. However, while unmarshalling from JSON map, -// the data is not available as a raw []byte and converting to it will significantly -// hurt performance. Thus, if you wish to implement a custom unmarshalling on a type -// that is being unmarshalled from a JSON map, you need to implement -// UnmarshalerFromJSONMap interface. -type UnmarshalerFromJSONMap interface { - UnmarshalJSONFromMap(data interface{}) error -} - -// UnmarshalFromJSONMap parses the JSON map data and stores the values -// in the struct pointed to by v and in the returned map. -// If v is nil or not a pointer to a struct, UnmarshalFromJSONMap returns an ErrInvalidValue. -// -// UnmarshalFromJSONMap follows the rules of json.Unmarshal with the following exceptions: -// - All input fields are stored in the resulting map, including fields that do not exist in the -// struct pointed by v. -// - UnmarshalFromJSONMap receive a JSON map instead of raw bytes. The given input map is assumed -// to be a JSON map, meaning it should only contain the following types: bool, string, float64, -// []interface, and map[string]interface{}. Other types will cause decoding to return unexpected results. -// - UnmarshalFromJSONMap only operates on struct values. It will reject all other types of v by -// returning ErrInvalidValue. -// - UnmarshalFromJSONMap supports three types of Mode values. Each mode is self documented and affects -// how UnmarshalFromJSONMap behaves. -func UnmarshalFromJSONMap(data map[string]interface{}, v interface{}, options ...UnmarshalOption) (map[string]interface{}, error) { - if !isValidValue(v) { - return nil, ErrInvalidValue - } - opts := buildUnmarshalOptions(options) - d := &mapDecoder{options: opts} - result := make(map[string]interface{}) - if data != nil { - d.populateStruct(false, nil, data, v, result) - } - if opts.mode == ModeAllowMultipleErrors || opts.mode == ModeFailOverToOriginalValue { - if len(d.errs) == 0 { - return result, nil - } - return result, &MultipleError{Errors: d.errs} - } - if d.err != nil { - return nil, d.err - } - return result, nil -} - -var unmarshalerFromJSONMapType = reflect.TypeOf((*UnmarshalerFromJSONMap)(nil)).Elem() - -type mapDecoder struct { - options *unmarshalOptions - err error - errs []error -} - -func (m *mapDecoder) populateStruct(forcePopulate bool, path []string, data map[string]interface{}, structInstance interface{}, result map[string]interface{}) (interface{}, bool) { - doPopulate := !m.options.skipPopulateStruct || forcePopulate - var structValue reflect.Value - if doPopulate { - structValue = reflectStructValue(structInstance) - } - fields := mapStructFields(structInstance) - for key, inputValue := range data { - refInfo, exists := fields[key] - if exists { - value, isValidType := m.valueByReflectType(append(path, key), inputValue, refInfo.t) - if isValidType { - if value != nil && doPopulate { - field := refInfo.field(structValue) - assignValue(field, value) - } - if !m.options.excludeKnownFieldsFromMap { - if result != nil { - result[key] = value - } - } - } else { - switch m.options.mode { - case ModeFailOnFirstError: - return nil, false - case ModeFailOverToOriginalValue: - if !forcePopulate { - result[key] = value - } else { - return data, false - } - } - } - } else { - if result != nil { - result[key] = inputValue - } - } - } - return structInstance, true -} - -func (m *mapDecoder) valueByReflectType(path []string, v interface{}, t reflect.Type) (interface{}, bool) { - if t.Implements(unmarshalerFromJSONMapType) { - result := reflect.New(t.Elem()).Interface() - m.valueFromCustomUnmarshaler(v, result.(UnmarshalerFromJSONMap)) - return result, true - } - if reflect.PtrTo(t).Implements(unmarshalerFromJSONMapType) { - value := reflect.New(t) - m.valueFromCustomUnmarshaler(v, value.Interface().(UnmarshalerFromJSONMap)) - return value.Elem().Interface(), true - } - kind := t.Kind() - if converter := primitiveConverters[kind]; converter != nil { - if v == nil { - return nil, true - } - converted, ok := converter(v) - if !ok { - m.addError(newUnexpectedTypeParseError(t, path)) - return v, false - } - return converted, true - } - switch kind { - case reflect.Slice: - return m.buildSlice(path, v, t) - case reflect.Array: - return m.buildArray(path, v, t) - case reflect.Map: - return m.buildMap(path, v, t) - case reflect.Struct: - value, valid := m.buildStruct(path, v, t) - if value == nil { - return nil, valid - } - if !valid { - return value, false - } - return reflect.ValueOf(value).Elem().Interface(), valid - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct { - return m.buildStruct(path, v, t.Elem()) - } - value, valid := m.valueByReflectType(path, v, t.Elem()) - if value == nil { - return nil, valid - } - if !valid { - return value, false - } - result := reflect.New(reflect.TypeOf(value)) - result.Elem().Set(reflect.ValueOf(value)) - return result.Interface(), valid - } - m.addError(newUnsupportedTypeParseError(t, path)) - return nil, false -} - -func (m *mapDecoder) buildSlice(path []string, v interface{}, sliceType reflect.Type) (interface{}, bool) { - if v == nil { - return nil, true - } - arr, ok := v.([]interface{}) - if !ok { - m.addError(newUnexpectedTypeParseError(sliceType, path)) - return v, false - } - elemType := sliceType.Elem() - var sliceValue reflect.Value - if len(arr) > 0 { - sliceValue = reflect.MakeSlice(sliceType, 0, 4) - } else { - sliceValue = reflect.MakeSlice(sliceType, 0, 0) - } - for _, element := range arr { - current, valid := m.valueByReflectType(path, element, elemType) - if !valid { - if m.options.mode != ModeFailOverToOriginalValue { - return nil, true - } - return v, true - } - sliceValue = reflect.Append(sliceValue, safeReflectValue(elemType, current)) - } - return sliceValue.Interface(), true -} - -func (m *mapDecoder) buildArray(path []string, v interface{}, arrayType reflect.Type) (interface{}, bool) { - if v == nil { - return nil, true - } - arr, ok := v.([]interface{}) - if !ok { - m.addError(newUnexpectedTypeParseError(arrayType, path)) - return v, false - } - elemType := arrayType.Elem() - arrayValue := reflect.New(arrayType).Elem() - for i, element := range arr { - current, valid := m.valueByReflectType(path, element, elemType) - if !valid { - if m.options.mode != ModeFailOverToOriginalValue { - return nil, true - } - return v, true - } - if current != nil { - arrayValue.Index(i).Set(reflect.ValueOf(current)) - } - } - return arrayValue.Interface(), true -} - -func (m *mapDecoder) buildMap(path []string, v interface{}, mapType reflect.Type) (interface{}, bool) { - if v == nil { - return nil, true - } - mp, ok := v.(map[string]interface{}) - if !ok { - m.addError(newUnexpectedTypeParseError(mapType, path)) - return v, false - } - keyType := mapType.Key() - valueType := mapType.Elem() - mapValue := reflect.MakeMap(mapType) - for inputKey, inputValue := range mp { - keyPath := append(path, inputKey) - key, valid := m.valueByReflectType(keyPath, inputKey, keyType) - if !valid { - if m.options.mode != ModeFailOverToOriginalValue { - return nil, true - } - return v, true - } - value, valid := m.valueByReflectType(keyPath, inputValue, valueType) - if !valid { - if m.options.mode != ModeFailOverToOriginalValue { - return nil, true - } - return v, true - } - mapValue.SetMapIndex(safeReflectValue(keyType, key), safeReflectValue(valueType, value)) - } - return mapValue.Interface(), true -} - -func (m *mapDecoder) buildStruct(path []string, v interface{}, structType reflect.Type) (interface{}, bool) { - if v == nil { - return nil, true - } - mp, ok := v.(map[string]interface{}) - if !ok { - m.addError(newUnexpectedTypeParseError(structType, path)) - return v, false - } - value := reflect.New(structType).Interface() - handler, ok := asJSONDataHandler(value) - if !ok { - return m.populateStruct(true, path, mp, value, nil) - } - data := make(map[string]interface{}) - result, valid := m.populateStruct(true, path, mp, value, data) - if !valid { - return result, false - } - err := handler(data) - if err != nil { - m.addError(err) - return result, false - } - return result, true -} - -func (m *mapDecoder) valueFromCustomUnmarshaler(data interface{}, unmarshaler UnmarshalerFromJSONMap) { - err := unmarshaler.UnmarshalJSONFromMap(data) - if err != nil { - m.addError(err) - } -} - -func (m *mapDecoder) addError(err error) { - if m.options.mode == ModeFailOnFirstError { - m.err = err - } else { - m.errs = append(m.errs, err) - } -} diff --git a/vendor/github.com/woodsbury/decimal128/LICENCE b/vendor/github.com/woodsbury/decimal128/LICENCE deleted file mode 100644 index fe64715..0000000 --- a/vendor/github.com/woodsbury/decimal128/LICENCE +++ /dev/null @@ -1,14 +0,0 @@ -BSD Zero Clause License - -Copyright (c) 2022 Wade Smith - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/woodsbury/decimal128/arith.go b/vendor/github.com/woodsbury/decimal128/arith.go deleted file mode 100644 index e87be63..0000000 --- a/vendor/github.com/woodsbury/decimal128/arith.go +++ /dev/null @@ -1,1178 +0,0 @@ -package decimal128 - -import "math/bits" - -// Add adds d and o, rounded using the [DefaultRoundingMode], and returns the -// result. -func (d Decimal) Add(o Decimal) Decimal { - return d.AddWithMode(o, DefaultRoundingMode) -} - -// AddWithMode adds d and o, rounding using the provided rounding mode, and -// returns the result. -func (d Decimal) AddWithMode(o Decimal, mode RoundingMode) Decimal { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if d.isInf() { - neg := d.Signbit() - - if o.isInf() && neg != o.Signbit() { - lhs := payloadValPosInfinite - rhs := payloadValNegInfinite - if neg { - lhs = payloadValNegInfinite - rhs = payloadValPosInfinite - } - - return nan(payloadOpAdd, lhs, rhs) - } - - return inf(neg) - } - - return inf(o.Signbit()) - } - - return d.add(o, mode, false) -} - -// Mul multiplies d and o, rounding using the [DefaultRoundingMode], and -// returns the result. -func (d Decimal) Mul(o Decimal) Decimal { - return d.MulWithMode(o, DefaultRoundingMode) -} - -// MulWithMode multiplies d and o, rounding using the provided rounding mode, -// and returns the result. -func (d Decimal) MulWithMode(o Decimal, mode RoundingMode) Decimal { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if !d.isSpecial() { - sig, _ := d.decompose() - if sig[0]|sig[1] == 0 { - lhs := payloadValPosZero - if d.Signbit() { - lhs = payloadValNegZero - } - - rhs := payloadValPosInfinite - if o.Signbit() { - rhs = payloadValNegInfinite - } - - return nan(payloadOpMul, lhs, rhs) - } - } else if !o.isSpecial() { - sig, _ := o.decompose() - if sig[0]|sig[1] == 0 { - lhs := payloadValPosInfinite - if d.Signbit() { - lhs = payloadValNegInfinite - } - - rhs := payloadValPosZero - if o.Signbit() { - rhs = payloadValNegZero - } - - return nan(payloadOpMul, lhs, rhs) - } - } - - return inf(d.Signbit() != o.Signbit()) - } - - dSig, dExp := d.decompose() - oSig, oExp := o.decompose() - - exp := (dExp - exponentBias) + (oExp - exponentBias) + exponentBias - neg := d.Signbit() != o.Signbit() - - var sig uint128 - if dSig[1]|oSig[1] == 0 { - sig1, sig0 := bits.Mul64(dSig[0], oSig[0]) - - if sig0|sig1 == 0 { - return zero(neg) - } - - sig, exp = mode.reduce128(neg, uint128{sig0, sig1}, exp, 0) - } else { - sig256 := dSig.mul(oSig) - - if sig256[0]|sig256[1]|sig256[2]|sig256[3] == 0 { - return zero(neg) - } - - sig, exp = mode.reduce256(neg, sig256, exp, 0) - } - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Pow raises d to the power of o, rounding using the [DefaultRoundingMode], -// and returns the result. -func (d Decimal) Pow(o Decimal) Decimal { - return d.PowWithMode(o, DefaultRoundingMode) -} - -// PowWithMode raises d to the power of o, rounding using the provided rounding -// mode, and returns the result. -func (d Decimal) PowWithMode(o Decimal, mode RoundingMode) Decimal { - if o.IsZero() { - return one(false) - } - - if d.isOne() { - if !d.Signbit() || o.isInf() { - return one(false) - } - } - - if o.isOne() { - if o.Signbit() { - return one(false).QuoWithMode(d, mode) - } - - return d - } - - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - dNeg := d.Signbit() - oNeg := o.Signbit() - - if o.isInf() { - if d.IsZero() { - if oNeg { - return inf(false) - } - - return zero(false) - } - - if d.isInf() { - if oNeg { - return zero(false) - } - - return inf(false) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - - if dExp > 0 { - if oNeg { - return zero(false) - } - - return inf(false) - } - - if dExp > -maxDigits { - l10 := int16(dSig.log10()) - if l10 >= -dExp { - if oNeg { - return zero(false) - } - - return inf(false) - } - } - - if oNeg { - return inf(false) - } - - return zero(false) - } - - oSig, oExp := o.decompose() - - for { - sig, rem := oSig.div10() - if rem != 0 { - break - } - - oSig = sig - oExp++ - } - - if d.IsZero() { - neg := false - - if d.Signbit() && oExp == exponentBias { - _, digit := oSig.div10() - if digit&1 != 0 { - neg = true - } - } - - if oNeg { - return inf(neg) - } - - return zero(neg) - } - - if d.isInf() { - if dNeg { - neg := false - - if oExp == exponentBias { - _, digit := oSig.div10() - if digit&1 != 0 { - neg = true - } - } - - if oNeg { - return zero(neg) - } - - return inf(neg) - } - - if oNeg { - return zero(false) - } - - return inf(false) - } - - dSig, dExp := d.decompose() - - for { - sig, rem := dSig.div10() - if rem != 0 { - break - } - - dSig = sig - dExp++ - } - - neg := false - - if dNeg { - if oExp < exponentBias { - rhs := payloadValPosFinite - if oNeg { - rhs = payloadValNegFinite - } - - return nan(payloadOpPow, payloadValNegFinite, rhs) - } - - if oExp == exponentBias { - _, digit := oSig.div10() - if digit&1 != 0 { - neg = true - } - } - } - - if !oNeg && oExp >= exponentBias && dSig == (uint128{1, 0}) { - if oSig[1] != 0 || oSig[0] > maxUnbiasedExponent { - if dExp == exponentBias { - return one(neg) - } - - if dExp < exponentBias { - return zero(neg) - } - - return inf(neg) - } - - var p10 int64 - switch oExp { - case exponentBias: - p10 = 1 - case 1 + exponentBias: - p10 = 10 - case 2 + exponentBias: - p10 = 100 - case 3 + exponentBias: - p10 = 1_000 - case 4 + exponentBias: - p10 = 10_000 - case 5 + exponentBias: - p10 = 100_000 - case 6 + exponentBias: - p10 = 1_000_000 - case 7 + exponentBias: - p10 = 10_000_000 - default: - if dExp == exponentBias { - return one(neg) - } - - if dExp < exponentBias { - return zero(neg) - } - - return inf(neg) - } - - exp64 := int64(dExp-exponentBias)*p10*int64(oSig[0]) + exponentBias - - if exp64 < minBiasedExponent-maxDigits { - return zero(neg) - } - - if exp64 > maxBiasedExponent+maxDigits { - return inf(neg) - } - - sig, exp := mode.reduce128(dNeg, dSig, int16(exp64), 0) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) - } - - if dExp&1 == 0 && oExp == exponentBias-1 && dSig == (uint128{1, 0}) && oSig == (uint128{5, 0}) { - exp := (dExp - exponentBias) / 2 - - if oNeg { - exp *= -1 - } - - return compose(neg, dSig, exp+exponentBias) - } - - inv, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp - exponentBias, - }.log() - - if res.sig[0]|res.sig[1]|res.sig[2] == 0 { - return one(neg) - } - - if int64(res.exp)+int64(oExp) > maxBiasedExponent+maxDigits { - if oNeg != inv { - return zero(neg) - } - - return inf(neg) - } - - res, trunc = res.mul(decomposed192{ - sig: uint192{oSig[0], oSig[1], 0}, - exp: oExp - exponentBias, - }, trunc) - - if res.sig[0]|res.sig[1]|res.sig[2] == 0 { - return one(neg) - } - - l10 := res.sig.log10() - - if int(res.exp) > 5-l10 { - if oNeg != inv { - return zero(neg) - } - - return inf(neg) - } - - if res.sig[0]|res.sig[1]|res.sig[2] == 0 { - return one(neg) - } - - res, trunc = res.epow(int16(l10), trunc) - - if res.exp > maxUnbiasedExponent+58 { - if oNeg != inv { - return zero(neg) - } - - return inf(neg) - } - - if oNeg != inv { - res, trunc = res.rcp(trunc) - trunc *= -1 - } - - sig, exp := mode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Quo divides d by o, rounding using the [DefaultRoundingMode], and returns -// the result. -func (d Decimal) Quo(o Decimal) Decimal { - return d.QuoWithMode(o, DefaultRoundingMode) -} - -// QuoWithMode divides d by o, rounding using the provided rounding mode, and -// returns the result. -func (d Decimal) QuoWithMode(o Decimal, mode RoundingMode) Decimal { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if d.isInf() { - if o.isInf() { - lhs := payloadValPosInfinite - if d.Signbit() { - lhs = payloadValNegInfinite - } - - rhs := payloadValPosInfinite - if o.Signbit() { - rhs = payloadValNegInfinite - } - - return nan(payloadOpQuo, lhs, rhs) - } - - return inf(d.Signbit() != o.Signbit()) - } - - if o.isInf() { - return zero(d.Signbit() != o.Signbit()) - } - } - - dSig, dExp := d.decompose() - oSig, oExp := o.decompose() - - if oSig[0]|oSig[1] == 0 { - if dSig[0]|dSig[1] == 0 { - lhs := payloadValPosZero - if d.Signbit() { - lhs = payloadValNegZero - } - - rhs := payloadValPosZero - if o.Signbit() { - rhs = payloadValNegZero - } - - return nan(payloadOpQuo, lhs, rhs) - } - - return inf(d.Signbit() != o.Signbit()) - } - - if dSig[0]|dSig[1] == 0 { - return zero(d.Signbit() != o.Signbit()) - } - - exp := (dExp - exponentBias) - (oExp - exponentBias) + exponentBias - - var sig uint128 - var rem uint128 - if dSig[1]|oSig[1] == 0 { - dSig64 := dSig[0] - - for dSig64 <= 0x0002_7fff_ffff_ffff { - dSig64 *= 10_000 - exp -= 4 - } - - for dSig64 <= 0x18ff_ffff_ffff_ffff { - dSig64 *= 10 - exp-- - } - - sig64, rem64 := bits.Div64(0, dSig64, oSig[0]) - - var carry uint64 - for rem64 != 0 && sig64 <= 0x18ff_ffff_ffff_ffff { - for rem64 <= 0x0002_7fff_ffff_ffff && sig64 <= 0x0002_7fff_ffff_ffff { - rem64 *= 10_000 - sig64 *= 10_000 - exp -= 4 - } - - for rem64 <= 0x18ff_ffff_ffff_ffff && sig64 <= 0x18ff_ffff_ffff_ffff { - rem64 *= 10 - sig64 *= 10 - exp-- - } - - if rem64 < oSig[0] { - break - } - - var tmp uint64 - tmp, rem64 = bits.Div64(0, rem64, oSig[0]) - sig64, carry = bits.Add64(sig64, tmp, 0) - - if carry != 0 { - break - } - } - - sig = uint128{sig64, carry} - rem = uint128{rem64, 0} - } else { - if dSig[1] == 0 { - dSig = dSig.mul64(10_000_000_000_000_000_000) - exp -= 19 - } - - for dSig[1] <= 0x0002_7fff_ffff_ffff { - dSig = dSig.mul64(10_000) - exp -= 4 - } - - for dSig[1] <= 0x18ff_ffff_ffff_ffff { - dSig = dSig.mul64(10) - exp-- - } - - sig, rem = dSig.div(oSig) - } - - trunc := int8(0) - - for rem[0]|rem[1] != 0 && sig[1] <= 0x0002_7fff_ffff_ffff { - for rem[1] <= 0x0002_7fff_ffff_ffff && sig[1] <= 0x0002_7fff_ffff_ffff { - rem = rem.mul64(10_000) - sig = sig.mul64(10_000) - exp -= 4 - } - - for rem[1] <= 0x18ff_ffff_ffff_ffff && sig[1] <= 0x18ff_ffff_ffff_ffff { - rem = rem.mul64(10) - sig = sig.mul64(10) - exp-- - } - - var tmp uint128 - tmp, rem = rem.div(oSig) - sig192 := sig.add(tmp) - - for sig192[2] != 0 { - var rem192 uint64 - sig192, rem192 = sig192.div10() - exp++ - - if rem192 != 0 { - trunc = 1 - } - } - - sig = uint128{sig192[0], sig192[1]} - } - - if rem[0]|rem[1] != 0 { - trunc = 1 - } - - neg := d.Signbit() != o.Signbit() - sig, exp = mode.reduce128(neg, sig, exp, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// QuoRem divides d by o, rounding using the [DefaultRoundingMode], and returns -// the result as an integer quotient and a remainder. -func (d Decimal) QuoRem(o Decimal) (Decimal, Decimal) { - return d.QuoRemWithMode(o, DefaultRoundingMode) -} - -// QuoRem divides d by o, rounding using the provided rounding mode, and -// returns the result as an integer quotient and a remainder. -func (d Decimal) QuoRemWithMode(o Decimal, mode RoundingMode) (Decimal, Decimal) { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() { - return d, d - } - - if o.IsNaN() { - return o, o - } - - if d.isInf() { - lhs := payloadValPosInfinite - if d.Signbit() { - lhs = payloadValNegInfinite - } - - if o.isInf() { - rhs := payloadValPosInfinite - if o.Signbit() { - rhs = payloadValNegInfinite - } - - res := nan(payloadOpQuoRem, lhs, rhs) - return res, res - } - - rhs := payloadValPosFinite - if o.IsZero() { - if o.Signbit() { - rhs = payloadValNegZero - } else { - rhs = payloadValPosZero - } - } else if o.Signbit() { - rhs = payloadValNegFinite - } - - return inf(d.Signbit() != o.Signbit()), nan(payloadOpQuoRem, lhs, rhs) - } - - if o.isInf() { - return zero(d.Signbit() != o.Signbit()), d - } - } - - dSig, dExp := d.decompose() - oSig, oExp := o.decompose() - - if oSig[0]|oSig[1] == 0 { - rhs := payloadValPosZero - if o.Signbit() { - rhs = payloadValNegZero - } - - if dSig[0]|dSig[1] == 0 { - lhs := payloadValPosZero - if d.Signbit() { - lhs = payloadValNegZero - } - - res := nan(payloadOpQuoRem, lhs, rhs) - return res, res - } - - lhs := payloadValPosFinite - if d.Signbit() { - lhs = payloadValNegFinite - } - - return inf(d.Signbit() != o.Signbit()), nan(payloadOpQuoRem, lhs, rhs) - } - - if dSig[0]|dSig[1] == 0 { - return zero(d.Signbit() != o.Signbit()), zero(d.Signbit()) - } - - exp := (dExp - exponentBias) - (oExp - exponentBias) - - if exp < 0 { - if exp <= -19 && oSig[1] == 0 { - oSig = oSig.mul64(10_000_000_000_000_000_000) - exp += 19 - } - - for exp <= -4 && oSig[1] <= 0x0002_7fff_ffff_ffff { - oSig = oSig.mul64(10_000) - exp += 4 - } - - for exp < 0 && oSig[1] <= 0x18ff_ffff_ffff_ffff { - oSig = oSig.mul64(10) - exp++ - } - - if exp < 0 || oSig.cmp(dSig) > 0 { - return zero(d.Signbit() != o.Signbit()), d - } - } else if exp > 0 { - if exp >= 19 && dSig[1] == 0 { - dSig = dSig.mul64(10_000_000_000_000_000_000) - dExp -= 19 - exp -= 19 - } - - for exp >= 4 && dSig[1] <= 0x0002_7fff_ffff_ffff { - dSig = dSig.mul64(10_000) - dExp -= 4 - exp -= 4 - } - - for exp > 0 && dSig[1] <= 0x18ff_ffff_ffff_ffff { - dSig = dSig.mul64(10) - dExp-- - exp-- - } - } - - qexp := exp + exponentBias - rexp := dExp - - var sig uint128 - var rem uint128 - if dSig[1]|oSig[1] == 0 { - sig64, rem64 := bits.Div64(0, dSig[0], oSig[0]) - - var carry uint64 - for exp > 0 && rem64 != 0 && sig64 <= 0x18ff_ffff_ffff_ffff { - for exp >= 4 && rem64 <= 0x0002_7fff_ffff_ffff && sig64 <= 0x0002_7fff_ffff_ffff { - rem64 *= 10_000 - sig64 *= 10_000 - exp -= 4 - qexp -= 4 - rexp -= 4 - } - - for exp > 0 && rem64 <= 0x18ff_ffff_ffff_ffff && sig64 <= 0x18ff_ffff_ffff_ffff { - rem64 *= 10 - sig64 *= 10 - exp-- - qexp-- - rexp-- - } - - if rem64 < oSig[0] { - break - } - - var tmp uint64 - tmp, rem64 = bits.Div64(0, rem64, oSig[0]) - sig64, carry = bits.Add64(sig64, tmp, 0) - - if carry != 0 { - break - } - } - - sig = uint128{sig64, carry} - rem = uint128{rem64, 0} - } else { - sig, rem = dSig.div(oSig) - } - - trunc := int8(0) - - for exp > 0 && rem[0]|rem[1] != 0 && sig[1] <= 0x0002_7fff_ffff_ffff { - for exp >= 4 && rem[1] <= 0x0002_7fff_ffff_ffff && sig[1] <= 0x0002_7fff_ffff_ffff { - rem = rem.mul64(10_000) - sig = sig.mul64(10_000) - exp -= 4 - qexp -= 4 - rexp -= 4 - } - - for exp > 0 && rem[1] <= 0x18ff_ffff_ffff_ffff && sig[1] <= 0x18ff_ffff_ffff_ffff { - rem = rem.mul64(10) - sig = sig.mul64(10) - exp-- - qexp-- - rexp-- - } - - var tmp uint128 - tmp, rem = rem.div(oSig) - sig192 := sig.add(tmp) - - for sig192[2] != 0 { - var rem192 uint64 - sig192, rem192 = sig192.div10() - qexp++ - - if rem192 != 0 { - trunc = 1 - } - } - - sig = uint128{sig192[0], sig192[1]} - } - - for exp > 0 && rem[0]|rem[1] != 0 { - for exp >= 4 && rem[1] <= 0x0002_7fff_ffff_ffff { - rem = rem.mul64(10_000) - exp -= 4 - rexp -= 4 - } - - for exp > 0 && rem[1] <= 0x18ff_ffff_ffff_ffff { - rem = rem.mul64(10) - exp-- - rexp-- - } - - var tmp uint128 - tmp, rem = rem.div(oSig) - - if tmp[0]|tmp[1] != 0 { - trunc = 1 - } - } - - qneg := d.Signbit() != o.Signbit() - qsig, qexp := mode.reduce128(qneg, sig, qexp, trunc) - - rneg := d.Signbit() - rsig, rexp := mode.reduce128(rneg, rem, rexp, 0) - - quo := compose(qneg, qsig, qexp) - - if qexp > maxBiasedExponent { - quo = inf(qneg) - } - - if rexp > maxBiasedExponent { - return quo, inf(rneg) - } - - return quo, compose(rneg, rsig, rexp) -} - -// Sub subtracts o from d, rounding using the [DefaultRoundingMode], and -// returns the result. -func (d Decimal) Sub(o Decimal) Decimal { - return d.SubWithMode(o, DefaultRoundingMode) -} - -// SubWithMode subtracts o from d, rounding using the provided rounding mode, -// and returns the result. -func (d Decimal) SubWithMode(o Decimal, mode RoundingMode) Decimal { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if d.isInf() { - neg := d.Signbit() - - if o.isInf() && neg == o.Signbit() { - lhs := payloadValPosInfinite - rhs := payloadValPosInfinite - if neg { - lhs = payloadValNegInfinite - rhs = payloadValNegInfinite - } - - return nan(payloadOpSub, lhs, rhs) - } - - return inf(neg) - } - - return inf(!o.Signbit()) - } - - return d.add(o, mode, true) -} - -func (d Decimal) add(o Decimal, mode RoundingMode, subtract bool) Decimal { - dSig, dExp := d.decompose() - oSig, oExp := o.decompose() - - if dSig[0]|dSig[1] == 0 { - if oSig[0]|oSig[1] == 0 { - if subtract { - return zero(d.Signbit() && !o.Signbit()) - } else { - return zero(d.Signbit() && o.Signbit()) - } - } - - if subtract { - return compose(!o.Signbit(), oSig, oExp) - } - - return o - } - - if oSig[0]|oSig[1] == 0 { - return d - } - - exp := dExp - oExp - trunc := int8(0) - - if exp < 0 { - if exp <= -19 && oSig[1] == 0 { - oSig = oSig.mul64(10_000_000_000_000_000_000) - oExp -= 19 - exp += 19 - } - - for exp <= -4 && oSig[1] <= 0x0002_7fff_ffff_ffff { - oSig = oSig.mul64(10_000) - oExp -= 4 - exp += 4 - } - - for exp < 0 && oSig[1] <= 0x18ff_ffff_ffff_ffff { - oSig = oSig.mul64(10) - oExp-- - exp++ - } - - if exp < -maxDigits { - if dSig[0]|dSig[1] != 0 { - dSig = uint128{} - trunc = 1 - } - - dExp = oExp - exp = 0 - } - - if exp <= -8 { - var rem uint64 - dSig, rem = dSig.div1e8() - if rem != 0 { - trunc = 1 - } - - if dSig[0]|dSig[1] == 0 { - dExp = oExp - exp = 0 - } else { - dExp += 8 - exp += 8 - } - } - - if exp <= -4 { - var rem uint64 - dSig, rem = dSig.div10000() - if rem != 0 { - trunc = 1 - } - - if dSig[0]|dSig[1] == 0 { - dExp = oExp - exp = 0 - } else { - dExp += 4 - exp += 4 - } - } - - if exp <= -3 { - var rem uint64 - dSig, rem = dSig.div1000() - if rem != 0 { - trunc = 1 - } - - if dSig[0]|dSig[1] == 0 { - dExp = oExp - exp = 0 - } else { - dExp += 3 - exp += 3 - } - } - - if exp <= -2 { - var rem uint64 - dSig, rem = dSig.div100() - if rem != 0 { - trunc = 1 - } - - if dSig[0]|dSig[1] == 0 { - dExp = oExp - exp = 0 - } else { - dExp += 2 - exp += 2 - } - } - - for exp < 0 { - var rem uint64 - dSig, rem = dSig.div10() - if rem != 0 { - trunc = 1 - } - - if dSig[0]|dSig[1] == 0 { - dExp = oExp - break - } - - dExp++ - exp++ - } - } else if exp > 0 { - if exp >= 19 && dSig[1] == 0 { - dSig = dSig.mul64(10_000_000_000_000_000_000) - dExp -= 19 - exp -= 19 - } - - for exp >= 4 && dSig[1] <= 0x0002_7fff_ffff_ffff { - dSig = dSig.mul64(10_000) - dExp -= 4 - exp -= 4 - } - - for exp > 0 && dSig[1] <= 0x18ff_ffff_ffff_ffff { - dSig = dSig.mul64(10) - dExp-- - exp-- - } - - if exp > maxDigits { - if oSig[0]|oSig[1] != 0 { - oSig = uint128{} - trunc = -1 - } - - exp = 0 - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if rem != 0 { - trunc = -1 - } - - if oSig[0]|oSig[1] == 0 { - exp = 0 - } else { - exp -= 8 - } - } - - if exp >= 4 { - var rem uint64 - oSig, rem = oSig.div10000() - if rem != 0 { - trunc = -1 - } - - if oSig[0]|oSig[1] == 0 { - exp = 0 - } else { - exp -= 4 - } - } - - if exp >= 3 { - var rem uint64 - oSig, rem = oSig.div1000() - if rem != 0 { - trunc = -1 - } - - if oSig[0]|oSig[1] == 0 { - exp = 0 - } else { - exp -= 3 - } - } - - if exp >= 2 { - var rem uint64 - oSig, rem = oSig.div100() - if rem != 0 { - trunc = -1 - } - - if oSig[0]|oSig[1] == 0 { - exp = 0 - } else { - exp -= 2 - } - } - - for exp > 0 { - var rem uint64 - oSig, rem = oSig.div10() - if rem != 0 { - trunc = -1 - } - - if oSig[0]|oSig[1] == 0 { - break - } - - exp-- - } - } - - dNeg := d.Signbit() - oNeg := o.Signbit() - if subtract { - oNeg = !oNeg - } - - neg := dNeg - - var sig uint128 - if dNeg == oNeg { - sig192 := dSig.add(oSig) - - if sig192[0]|sig192[1]|sig192[2] == 0 { - return zero(mode == ToNegativeInf) - } - - if trunc == -1 { - trunc = 1 - } - - sig, exp = mode.reduce192(neg, sig192, dExp, trunc) - } else { - var brw uint - sig, brw = dSig.sub(oSig) - - if brw != 0 { - sig = sig.twos() - neg = !neg - trunc *= -1 - } else if sig[0]|sig[1] == 0 { - return zero(mode == ToNegativeInf) - } - - sig, exp = mode.reduce128(neg, sig, dExp, trunc) - } - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} diff --git a/vendor/github.com/woodsbury/decimal128/binary.go b/vendor/github.com/woodsbury/decimal128/binary.go deleted file mode 100644 index be681a2..0000000 --- a/vendor/github.com/woodsbury/decimal128/binary.go +++ /dev/null @@ -1,59 +0,0 @@ -package decimal128 - -import "errors" - -// MarshalBinary implements the [encoding.BinaryMarshaler] interface. It -// marshals the Decimal into IEEE 754 format. -func (d Decimal) MarshalBinary() ([]byte, error) { - data := make([]byte, 16) - - data[0] = byte(d.hi >> 56) - data[1] = byte(d.hi >> 48) - data[2] = byte(d.hi >> 40) - data[3] = byte(d.hi >> 32) - data[4] = byte(d.hi >> 24) - data[5] = byte(d.hi >> 16) - data[6] = byte(d.hi >> 8) - data[7] = byte(d.hi) - - data[8] = byte(d.lo >> 56) - data[9] = byte(d.lo >> 48) - data[10] = byte(d.lo >> 40) - data[11] = byte(d.lo >> 32) - data[12] = byte(d.lo >> 24) - data[13] = byte(d.lo >> 16) - data[14] = byte(d.lo >> 8) - data[15] = byte(d.lo) - - return data, nil -} - -// UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface. It -// unmarshals a Decimal in IEEE 754 format. -func (d *Decimal) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return errors.New("Decimal.UnmarshalBinary: invalid length") - } - - lo := uint64(data[15]) - lo |= uint64(data[14]) << 8 - lo |= uint64(data[13]) << 16 - lo |= uint64(data[12]) << 24 - lo |= uint64(data[11]) << 32 - lo |= uint64(data[10]) << 40 - lo |= uint64(data[9]) << 48 - lo |= uint64(data[8]) << 56 - - hi := uint64(data[7]) - hi |= uint64(data[6]) << 8 - hi |= uint64(data[5]) << 16 - hi |= uint64(data[4]) << 24 - hi |= uint64(data[3]) << 32 - hi |= uint64(data[2]) << 40 - hi |= uint64(data[1]) << 48 - hi |= uint64(data[0]) << 56 - - *d = Decimal{lo, hi} - - return nil -} diff --git a/vendor/github.com/woodsbury/decimal128/compare.go b/vendor/github.com/woodsbury/decimal128/compare.go deleted file mode 100644 index f720f90..0000000 --- a/vendor/github.com/woodsbury/decimal128/compare.go +++ /dev/null @@ -1,1054 +0,0 @@ -package decimal128 - -// Compare returns: -// -// -1 if d < o -// 0 if d == o -// +1 if d > o -// -// Unlike [Decimal.Cmp], Compare considers NaN values to be less than any other -// values. -func Compare(d, o Decimal) int { - if d.IsNaN() { - if o.IsNaN() { - return 0 - } - - return -1 - } - - if o.IsNaN() { - return 1 - } - - return int(d.Cmp(o)) -} - -// Max returns the larger of d or o. If either value is NaN the result is NaN. -func Max(d, o Decimal) Decimal { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if d.IsZero() && o.IsZero() { - if !d.Signbit() || !o.Signbit() { - return zero(false) - } - - return zero(true) - } - - if o.Cmp(d).Greater() { - return o - } - - return d -} - -// Min returns the smaller of d or o. If either value is NaN the result is NaN. -func Min(d, o Decimal) Decimal { - if d.IsNaN() { - return d - } - - if o.IsNaN() { - return o - } - - if d.IsZero() && o.IsZero() { - if d.Signbit() || o.Signbit() { - return zero(true) - } - - return zero(false) - } - - if o.Cmp(d).Less() { - return o - } - - return d -} - -// CmpResult represents the result from comparing two Decimals. When the values -// being compared aren't NaNs, the integer value of the CmpResult will be: -// -// -1 if lhs < rhs -// 0 if lhs == rhs -// +1 if lhs > rhs -// -// The Equal, Greater, GreaterOrEqual, Less, and LessOrEqual methods can also -// be used to determine the result. If either value is a NaN, then these -// methods will still behave correctly. -type CmpResult int8 - -const ( - cmpNaN CmpResult = -2 - cmpLess CmpResult = -1 - cmpEqual CmpResult = 0 - cmpGreater CmpResult = 1 -) - -// Equal returns whether this CmpResult represents that the two Decimals were -// equal to each other. This method will handle when one of the values being -// compared was a NaN. -func (cr CmpResult) Equal() bool { - return cr == cmpEqual -} - -// Greater returns whether this CmpResult represents that the value on the -// left-hand side of the comparison was greater than the value on the -// right-hand side. This method will handle when one of the values being -// compared was a NaN. -func (cr CmpResult) Greater() bool { - return cr == cmpGreater -} - -// GreaterOrEqual returns whether this CmpResult represents that the value on -// the left-hand side of the comparison was greater than or equal to the value -// on the right-hand side. This method will handle when one of the values being -// compared was a NaN. -func (cr CmpResult) GreaterOrEqual() bool { - return cr == cmpGreater || cr == cmpEqual -} - -// Less returns whether this CmpResult represents that the value on the -// left-hand side of the comparison was less than the value on the right-hand -// side. This method will handle when one of the values being compared was a -// NaN. -func (cr CmpResult) Less() bool { - return cr == cmpLess -} - -// LessOrEqual returns whether this CmpResult represents that the value on the -// left-hand side of the comparison was less than or equal to the value on the -// right-hand side. This method will handle when one of the values being -// compared was a NaN. -func (cr CmpResult) LessOrEqual() bool { - return cr == cmpLess || cr == cmpEqual -} - -// Cmp compares two Decimals and returns a CmpResult representing whether the -// two values were equal, the left-hand side was greater than the right-hand -// side, or the left-hand side was less than the right-hand side. -func (d Decimal) Cmp(o Decimal) CmpResult { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() || o.IsNaN() { - return cmpNaN - } - - if d.isInf() { - neg := d.Signbit() - - if o.isInf() && neg == o.Signbit() { - return cmpEqual - } - - if neg { - return cmpLess - } - - return cmpGreater - } - - if o.isInf() { - if o.Signbit() { - return cmpGreater - } - - return cmpLess - } - } - - if d == o { - return cmpEqual - } - - dSig, dExp := d.decompose() - - if dSig[0]|dSig[1] == 0 { - if o.IsZero() { - return cmpEqual - } - - if o.Signbit() { - return cmpGreater - } - - return cmpLess - } - - oSig, oExp := o.decompose() - - if oSig[0]|oSig[1] == 0 { - if d.Signbit() { - return cmpLess - } - - return cmpGreater - } - - neg := d.Signbit() - - if neg != o.Signbit() { - if neg { - return cmpLess - } - - return cmpGreater - } - - exp := dExp - oExp - trunc := false - - var res CmpResult - if neg { - res = cmpLess - } else { - res = cmpGreater - } - - if exp < 0 { - if oSig.cmp(dSig) >= 0 { - return res * -1 - } - - if exp <= -19 { - if exp < -maxDigits { - return res * -1 - } - - var rem uint64 - dSig, rem = dSig.div1e19() - if dSig[0]|dSig[1] == 0 { - return res * -1 - } - - if rem != 0 { - trunc = true - } - - exp += 19 - } - - exp *= -1 - dSig, oSig = oSig, dSig - res *= -1 - } else if exp > 0 { - if dSig.cmp(oSig) >= 0 { - return res - } - - if exp >= 19 { - if exp > maxDigits { - return res - } - - var rem uint64 - oSig, rem = oSig.div1e19() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - exp -= 19 - } - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - exp -= 8 - } - - if oSig[1] == 0 { - if dSig[1] != 0 { - return res - } - - oSig64 := oSig[0] - - if exp >= 8 { - if oSig64%100_000_000 != 0 { - trunc = true - } - - oSig64 /= 100_000_000 - if oSig64 == 0 { - return res - } - - exp -= 8 - } - - switch exp { - case 7: - if oSig64%10_000_000 != 0 { - trunc = true - } - - oSig64 /= 10_000_000 - if oSig64 == 0 { - return res - } - case 6: - if oSig64%1_000_000 != 0 { - trunc = true - } - - oSig64 /= 1_000_000 - if oSig64 == 0 { - return res - } - case 5: - if oSig64%100_000 != 0 { - trunc = true - } - - oSig64 /= 100_000 - if oSig64 == 0 { - return res - } - case 4: - if oSig64%10_000 != 0 { - trunc = true - } - - oSig64 /= 10_000 - if oSig64 == 0 { - return res - } - case 3: - if oSig64%1000 != 0 { - trunc = true - } - - oSig64 /= 1000 - if oSig64 == 0 { - return res - } - case 2: - if oSig64%100 != 0 { - trunc = true - } - - oSig64 /= 100 - if oSig64 == 0 { - return res - } - case 1: - if oSig64%10 != 0 { - trunc = true - } - - oSig64 /= 10 - if oSig64 == 0 { - return res - } - } - - if dSig[0] == oSig64 { - if trunc { - return res * -1 - } - - return cmpEqual - } - - if dSig[0] < oSig64 { - return res * -1 - } - - return res - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - exp -= 8 - } - - var rem uint64 - switch exp { - case 7: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 6: - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 5: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 4: - oSig, rem = oSig.div10000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 3: - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 2: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 1: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - } - - sres := dSig.cmp(oSig) - if sres == 0 { - if trunc { - return res * -1 - } - - return cmpEqual - } - - if res == cmpLess { - return CmpResult(sres * -1) - } - - return CmpResult(sres) -} - -// CmpAbs compares the absolute value of two Decimals and returns a CmpResult -// representing whether the two values were equal, the left-hand side was -// greater than the right-hand side, or the left-hand side was less than the -// right-hand side. -func (d Decimal) CmpAbs(o Decimal) CmpResult { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() || o.IsNaN() { - return cmpNaN - } - - if d.isInf() { - if o.isInf() { - return cmpEqual - } - - return cmpGreater - } - - if o.isInf() { - return cmpLess - } - } - - if d == o { - return cmpEqual - } - - dSig, dExp := d.decompose() - - if dSig[0]|dSig[1] == 0 { - if o.IsZero() { - return cmpEqual - } - - return cmpLess - } - - oSig, oExp := o.decompose() - - if oSig[0]|oSig[1] == 0 { - return cmpGreater - } - - exp := dExp - oExp - trunc := false - res := cmpGreater - - if exp < 0 { - if oSig.cmp(dSig) >= 0 { - return cmpLess - } - - if exp <= -19 { - if exp < -maxDigits { - return cmpLess - } - - var rem uint64 - dSig, rem = dSig.div1e19() - if dSig[0]|dSig[1] == 0 { - return cmpLess - } - - if rem != 0 { - trunc = true - } - - exp += 19 - } - - exp *= -1 - dSig, oSig = oSig, dSig - res = cmpLess - } else if exp > 0 { - if dSig.cmp(oSig) >= 0 { - return cmpGreater - } - - if exp >= 19 { - if exp > maxDigits { - return cmpGreater - } - - var rem uint64 - oSig, rem = oSig.div1e19() - if oSig[0]|oSig[1] == 0 { - return cmpGreater - } - - if rem != 0 { - trunc = true - } - - exp -= 19 - } - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - exp -= 8 - } - - if oSig[1] == 0 { - if dSig[1] != 0 { - return res - } - - oSig64 := oSig[0] - - if exp >= 8 { - if oSig64%100_000_000 != 0 { - trunc = true - } - - oSig64 /= 100_000_000 - if oSig64 == 0 { - return res - } - - exp -= 8 - } - - switch exp { - case 7: - if oSig64%10_000_000 != 0 { - trunc = true - } - - oSig64 /= 10_000_000 - if oSig64 == 0 { - return res - } - case 6: - if oSig64%1_000_000 != 0 { - trunc = true - } - - oSig64 /= 1_000_000 - if oSig64 == 0 { - return res - } - case 5: - if oSig64%100_000 != 0 { - trunc = true - } - - oSig64 /= 100_000 - if oSig64 == 0 { - return res - } - case 4: - if oSig64%10_000 != 0 { - trunc = true - } - - oSig64 /= 10_000 - if oSig64 == 0 { - return res - } - case 3: - if oSig64%1000 != 0 { - trunc = true - } - - oSig64 /= 1000 - if oSig64 == 0 { - return res - } - case 2: - if oSig64%100 != 0 { - trunc = true - } - - oSig64 /= 100 - if oSig64 == 0 { - return res - } - case 1: - if oSig64%10 != 0 { - trunc = true - } - - oSig64 /= 10 - if oSig64 == 0 { - return res - } - } - - if dSig[0] == oSig64 { - if trunc { - return res * -1 - } - - return cmpEqual - } - - if dSig[0] < oSig64 { - return res * -1 - } - - return res - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - exp -= 8 - } - - var rem uint64 - switch exp { - case 7: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 6: - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 5: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 4: - oSig, rem = oSig.div10000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 3: - oSig, rem = oSig.div1000() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - case 2: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - - fallthrough - case 1: - oSig, rem = oSig.div10() - if oSig[0]|oSig[1] == 0 { - return res - } - - if rem != 0 { - trunc = true - } - } - - sres := dSig.cmp(oSig) - if sres == 0 { - if trunc { - return res * -1 - } - - return cmpEqual - } - - if res == cmpLess { - return CmpResult(sres * -1) - } - - return CmpResult(sres) -} - -// Equal compares two Decimals and reports whether they are equal. -func (d Decimal) Equal(o Decimal) bool { - if d.isSpecial() || o.isSpecial() { - if d.IsNaN() || o.IsNaN() { - return false - } - - if d.isInf() { - return o.isInf() && d.Signbit() == o.Signbit() - } - - if o.isInf() { - return false - } - } - - if d == o { - return true - } - - dSig, dExp := d.decompose() - - if dSig[0]|dSig[1] == 0 { - return o.IsZero() - } - - oSig, oExp := o.decompose() - - if oSig[0]|oSig[1] == 0 { - return false - } - - if d.Signbit() != o.Signbit() { - return false - } - - exp := dExp - oExp - - if exp < 0 { - if oSig.cmp(dSig) >= 0 { - return false - } - - if exp <= -19 { - if exp < -maxDigits { - return false - } - - var rem uint64 - dSig, rem = dSig.div1e19() - if rem != 0 { - return false - } - - exp += 19 - } - - exp *= -1 - dSig, oSig = oSig, dSig - } else if exp > 0 { - if dSig.cmp(oSig) >= 0 { - return false - } - - if exp >= 19 { - if exp > maxDigits { - return false - } - - var rem uint64 - oSig, rem = oSig.div1e19() - if rem != 0 { - return false - } - - exp -= 19 - } - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if rem != 0 { - return false - } - - exp -= 8 - } - - if oSig[1] == 0 { - if dSig[1] != 0 { - return false - } - - oSig64 := oSig[0] - - if exp >= 8 { - if oSig64%100_000_000 != 0 { - return false - } - - oSig64 /= 100_000_000 - exp -= 8 - } - - switch exp { - case 7: - if oSig64%10_000_000 != 0 { - return false - } - - oSig64 /= 10_000_000 - case 6: - if oSig64%1_000_000 != 0 { - return false - } - - oSig64 /= 1_000_000 - case 5: - if oSig64%100_000 != 0 { - return false - } - - oSig64 /= 100_000 - case 4: - if oSig64%10_000 != 0 { - return false - } - - oSig64 /= 10_000 - case 3: - if oSig64%1000 != 0 { - return false - } - - oSig64 /= 1000 - case 2: - if oSig64%100 != 0 { - return false - } - - oSig64 /= 100 - case 1: - if oSig64%10 != 0 { - return false - } - - oSig64 /= 10 - } - - return dSig[0] == oSig64 - } - - if exp >= 8 { - var rem uint64 - oSig, rem = oSig.div1e8() - if rem != 0 { - return false - } - - exp -= 8 - } - - var rem uint64 - switch exp { - case 7: - oSig, rem = oSig.div10() - if rem != 0 { - return false - } - - fallthrough - case 6: - oSig, rem = oSig.div1000() - if rem != 0 { - return false - } - - oSig, rem = oSig.div1000() - if rem != 0 { - return false - } - case 5: - oSig, rem = oSig.div10() - if rem != 0 { - return false - } - - fallthrough - case 4: - oSig, rem = oSig.div10000() - if rem != 0 { - return false - } - case 3: - oSig, rem = oSig.div1000() - if rem != 0 { - return false - } - case 2: - oSig, rem = oSig.div10() - if rem != 0 { - return false - } - - fallthrough - case 1: - oSig, rem = oSig.div10() - if rem != 0 { - return false - } - } - - return dSig == oSig -} - -// IsZero reports whether the Decimal is equal to zero. This method will return -// true for both positive and negative zero. -func (d Decimal) IsZero() bool { - if d.hi&0x6000_0000_0000_0000 == 0x6000_0000_0000_0000 { - return false - } else { - return d.lo == 0 && d.hi&0x0001_ffff_ffff_ffff == 0 - } -} - -func (d Decimal) isOne() bool { - if d.isSpecial() { - return false - } - - sig, exp := d.decompose() - - if exp <= int16(-len(uint128PowersOf10)+exponentBias) || exp > exponentBias { - return false - } - - return sig == uint128PowersOf10[-(exp-exponentBias)] -} diff --git a/vendor/github.com/woodsbury/decimal128/compose.go b/vendor/github.com/woodsbury/decimal128/compose.go deleted file mode 100644 index d21f117..0000000 --- a/vendor/github.com/woodsbury/decimal128/compose.go +++ /dev/null @@ -1,252 +0,0 @@ -package decimal128 - -import ( - "math/big" - "strconv" -) - -// Compose sets d to the value represented by the parts provided as arguments. -// The arguments consist of: -// - a byte form value that should be set to 0 for finite values, 1 for -// infinite values, or 2 for values which are NaN -// - a bool value that should be set to true when the value is negative, -// false otherwise -// - a byte slice that should be set to the significand of the value as a big -// endian integer -// - an int32 exponent -// -// If the value represented by the parts in the arguments are outside the range -// of a Decimal an error is returned. Compose implements the composer interface -// used by the [database/sql] package to read and write decimal values. -func (d *Decimal) Compose(form byte, neg bool, sig []byte, exp int32) error { - switch form { - case 0: // finite - i := 0 - l := len(sig) - for ; i < l; i++ { - if sig[i] != 0 { - break - } - } - - if i == l { - *d = zero(neg) - return nil - } - - sig = sig[i:] - - if len(sig) > 32 { - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - - bigsig := new(big.Int) - bigsig.SetBytes(sig) - - den := new(big.Int).SetUint64(10_000_000_000_000_000_000) - rem := new(big.Int) - - for bigsig.BitLen() > 32*8 { - bigsig.QuoRem(bigsig, den, rem) - - if rem.BitLen() != 0 { - return &composeRangeError{} - } - - exp += 19 - - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - } - - sig = bigsig.Bytes() - } - - var sig128 uint128 - if l := len(sig); l > 16 { - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - - var sig256 uint256 - sig256[0] = uint64(sig[0]) - - for i := 1; i < l; i++ { - sig256 = sig256.lsh(8) - sig256[0] |= uint64(sig[i]) - } - - for sig256[3] > 0 { - var rem uint64 - sig256, rem = sig256.div1e19() - - if rem != 0 { - return &composeRangeError{} - } - - exp += 19 - - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - } - - sig192 := uint192{sig256[0], sig256[1], sig256[2]} - - for sig192[2] > 0 { - var rem uint64 - sig192, rem = sig192.div10000() - - if rem != 0 { - return &composeRangeError{} - } - - exp += 4 - - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - } - - sig128 = uint128{sig192[0], sig192[1]} - } else { - sig128[0] = uint64(sig[0]) - - for i := 1; i < len(sig); i++ { - sig128 = sig128.lsh(8) - sig128[0] |= uint64(sig[i]) - } - } - - for sig128[1] > 0x0002_7fff_ffff_ffff { - var rem uint64 - sig128, rem = sig128.div10() - - if rem != 0 { - return &composeRangeError{} - } - - exp++ - - if exp > maxUnbiasedExponent { - return &composeRangeError{} - } - } - - if exp < minUnbiasedExponent-maxDigits { - return &composeRangeError{} - } - - for exp < minUnbiasedExponent { - var rem uint64 - sig128, rem = sig128.div10() - - if rem != 0 { - return &composeRangeError{} - } - - exp++ - } - - for exp > maxUnbiasedExponent { - sig128 = sig128.mul64(10) - - if sig128[1] > 0x0002_7fff_ffff_ffff { - return &composeRangeError{} - } - - exp-- - } - - *d = compose(neg, sig128, int16(exp+exponentBias)) - return nil - case 1: // infinite - *d = inf(neg) - return nil - case 2: // NaN - *d = nan(payloadOpCompose, 0, 0) - return nil - } - - return &composeFormError{form} -} - -// Decompose returns the state of d in parts. The returned values consist of: -// - a byte form value set to 0 when the value is finite, 1 when the value is -// infinite, or 2 when the value is NaN -// - a bool value set to true if the value is negative, false otherwise -// - a byte slice containing the significand of the value as a big endian -// integer -// - an int32 exponent -// -// If the provided buf has sufficient capacity, it may be returned as the -// significand with the correct value and length set. Decompose implements the -// decomposer interface used by the [database/sql] package to read and write -// decimal values. -func (d Decimal) Decompose(buf []byte) (byte, bool, []byte, int32) { - if d.IsNaN() { - return 2, d.Signbit(), nil, 0 - } - - if d.isInf() { - return 1, d.Signbit(), nil, 0 - } - - sig128, exp := d.decompose() - - if sig128[0]|sig128[1] == 0 { - return 0, d.Signbit(), nil, 0 - } - - var sig []byte - if cap(buf) >= 16 { - sig = buf[:16] - } else { - sig = make([]byte, 16) - } - - sig[0] = byte(sig128[1] >> 56) - sig[1] = byte(sig128[1] >> 48) - sig[2] = byte(sig128[1] >> 40) - sig[3] = byte(sig128[1] >> 32) - sig[4] = byte(sig128[1] >> 24) - sig[5] = byte(sig128[1] >> 16) - sig[6] = byte(sig128[1] >> 8) - sig[7] = byte(sig128[1]) - - sig[8] = byte(sig128[0] >> 56) - sig[9] = byte(sig128[0] >> 48) - sig[10] = byte(sig128[0] >> 40) - sig[11] = byte(sig128[0] >> 32) - sig[12] = byte(sig128[0] >> 24) - sig[13] = byte(sig128[0] >> 16) - sig[14] = byte(sig128[0] >> 8) - sig[15] = byte(sig128[0]) - - i := 0 - for ; i < len(sig); i++ { - if sig[i] != 0 { - break - } - } - - sig = sig[i:] - - return 0, d.Signbit(), sig, int32(exp) - exponentBias -} - -type composeFormError struct { - form byte -} - -func (err *composeFormError) Error() string { - return "unknown form " + strconv.FormatUint(uint64(err.form), 10) -} - -type composeRangeError struct{} - -func (err *composeRangeError) Error() string { - return "value out of range" -} diff --git a/vendor/github.com/woodsbury/decimal128/constants.go b/vendor/github.com/woodsbury/decimal128/constants.go deleted file mode 100644 index 037662e..0000000 --- a/vendor/github.com/woodsbury/decimal128/constants.go +++ /dev/null @@ -1,22 +0,0 @@ -package decimal128 - -var e = Decimal{0x4e90_6acc_b26a_bb56, 0x2ffe_8605_8a4b_f4de} - -// E returns the mathematical constant e. -func E() Decimal { - return e -} - -var phi = Decimal{0x1c9c_005e_9476_8cc6, 0x2ffe_4fc6_75c9_f21d} - -// Phi returns the golden ratio. -func Phi() Decimal { - return phi -} - -var pi = Decimal{0xbabe_5564_e6f3_9f8f, 0x2ffe_9ae4_7957_96a7} - -// Pi returns the mathematical constant π. -func Pi() Decimal { - return pi -} diff --git a/vendor/github.com/woodsbury/decimal128/convert.go b/vendor/github.com/woodsbury/decimal128/convert.go deleted file mode 100644 index d1e16c6..0000000 --- a/vendor/github.com/woodsbury/decimal128/convert.go +++ /dev/null @@ -1,799 +0,0 @@ -package decimal128 - -import ( - "math" - "math/big" - "math/bits" -) - -// FromFloat converts f into a Decimal. -func FromFloat(f *big.Float) Decimal { - if f.IsInf() { - return inf(f.Signbit()) - } - - if f.Sign() == 0 { - return zero(f.Signbit()) - } - - r, _ := f.Rat(nil) - return FromRat(r) -} - -// FromFloat32 converts f into a Decimal. -func FromFloat32(f float32) Decimal { - if math.IsNaN(float64(f)) { - return nan(payloadOpFromFloat32, 0, 0) - } - - return FromFloat64(float64(f)) -} - -// FromFloat64 converts f into a Decimal. -func FromFloat64(f float64) Decimal { - if math.IsNaN(f) { - return nan(payloadOpFromFloat64, 0, 0) - } - - if math.IsInf(f, 0) { - return inf(math.Signbit(f)) - } - - if f == 0.0 { - return zero(math.Signbit(f)) - } - - fbits := math.Float64bits(f) - mant := fbits & 0x000f_ffff_ffff_ffff - exp := int16(fbits >> 52 & 0x07ff) - neg := fbits&0x8000_0000_0000_0000 != 0 - - if exp == 0 { - exp = -1022 - } else { - mant |= 0x0010_0000_0000_0000 - exp -= 1023 - } - - shift := int(52 - exp) - - if shift == 0 { - return compose(neg, uint128{mant, 0}, exponentBias) - } - - var sig256 uint256 - exp = exponentBias - trunc := int8(0) - - if shift < 0 { - shift *= -1 - zeros := bits.LeadingZeros64(mant) - - if zeros > shift { - zeros = shift - } - - mant <<= zeros - shift -= zeros - - sig256 = uint256{mant, 0, 0, 0} - - if shift <= 192 { - sig256 = sig256.lsh(uint(shift)) - } else { - sig256 = sig256.lsh(192) - shift -= 192 - - for shift != 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - - if rem != 0 { - trunc = 1 - } - - zeros = bits.LeadingZeros64(sig256[3]) - if shift > zeros { - sig256 = sig256.lsh(uint(zeros)) - shift -= zeros - } else { - sig256 = sig256.lsh(uint(shift)) - break - } - } - } - } else { - zeros := bits.TrailingZeros64(mant) - - if zeros > shift { - zeros = shift - } - - mant >>= zeros - shift -= zeros - - if shift == 0 { - sig256 = uint256{mant, 0, 0, 0} - } else { - sig := uint128{mant, 0} - sig256 = sig.mul1e38() - exp -= 38 - - for shift != 0 { - zeros = bits.LeadingZeros64(sig256[3]) - for zeros >= 4 { - sig256 = sig256.mul64(10) - exp-- - zeros = bits.LeadingZeros64(sig256[3]) - } - - max := 4 - zeros - if shift < max { - max = shift - } - - zeros = bits.TrailingZeros64(sig256[0]) - - if zeros < max { - trunc = 1 - } - - sig256 = sig256.rsh(uint(max)) - shift -= max - } - } - } - - sig, exp := DefaultRoundingMode.reduce256(neg, sig256, exp, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// FromInt converts i into a Decimal. -func FromInt(i *big.Int) Decimal { - neg := false - if sgn := i.Sign(); sgn == 0 { - return zero(false) - } else if sgn < 0 { - neg = true - } - - exp := int16(exponentBias) - trunc := int8(0) - - if bl := i.BitLen(); bl > 128 { - i = new(big.Int).Set(i) - r := new(big.Int) - - if bl > 256 { - e18 := big.NewInt(1_000_000_000_000_000_000) - - for bl > 256 { - i.QuoRem(i, e18, r) - exp += 18 - - if exp > maxBiasedExponent { - return inf(neg) - } - - bl = i.BitLen() - - if r.Sign() != 0 { - trunc = 1 - } - } - } - - ten := big.NewInt(10) - - for bl > 128 { - i.QuoRem(i, ten, r) - exp++ - - if exp > maxBiasedExponent { - return inf(neg) - } - - bl = i.BitLen() - - if r.Sign() != 0 { - trunc = 1 - } - } - } - - var sig uint128 - - b := i.Bits() - for i := len(b) - 1; i >= 0; i-- { - sig = sig.lsh(bits.UintSize) - sig = sig.or64(uint64(b[i])) - } - - sig, exp = DefaultRoundingMode.reduce128(neg, sig, exp, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// FromInt32 converts i into a Decimal. -func FromInt32(i int32) Decimal { - return FromInt64(int64(i)) -} - -// FromInt64 converts i into a Decimal. -func FromInt64(i int64) Decimal { - if i == 0 { - return zero(false) - } - - neg := false - if i < 0 { - neg = true - i *= -1 - } - - return compose(neg, uint128{uint64(i), 0}, exponentBias) -} - -// FromRat converts r into a Decimal. -func FromRat(r *big.Rat) Decimal { - num := r.Num() - - if num.Sign() == 0 { - return zero(false) - } - - denom := r.Denom() - - return FromInt(num).Quo(FromInt(denom)) -} - -// FromUint32 converts i into a Decimal. -func FromUint32(i uint32) Decimal { - return FromUint64(uint64(i)) -} - -// FromUint64 converts i into a Decimal. -func FromUint64(i uint64) Decimal { - if i == 0 { - return zero(false) - } - - return compose(false, uint128{i, 0}, exponentBias) -} - -// Float converts d into a big.Float. If a non-nil argument f is provided, -// Float stores the result in f instead of allocating a new big.Float. It -// panics if d is NaN. -func (d Decimal) Float(f *big.Float) *big.Float { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Float()") - } - - if f == nil { - f = new(big.Float) - } else if f.Prec() == 0 { - f.SetPrec(128) - } - - return f.SetInf(d.Signbit()) - } - - sig, exp := d.decompose() - exp -= exponentBias - - if f == nil { - f = new(big.Float).SetPrec(128) - } else if f.Prec() == 0 { - f.SetPrec(128) - } - - if sig[1] == 0 { - f.SetUint64(sig[0]) - } else { - bigsig := new(big.Int).SetUint64(sig[1]) - bigsig.Lsh(bigsig, 64).Or(bigsig, new(big.Int).SetUint64(sig[0])) - - f.SetInt(bigsig) - } - - if d.Signbit() { - f.Neg(f) - } - - if exp == 0 { - return f - } - - var bigexp *big.Int - if exp > 0 { - bigexp = big.NewInt(int64(exp)) - } else { - bigexp = big.NewInt(int64(exp * -1)) - } - - bigexp.Exp(big.NewInt(10), bigexp, nil) - - if exp > 0 { - f.Mul(f, new(big.Float).SetInt(bigexp)) - } else { - f.Quo(f, new(big.Float).SetInt(bigexp)) - } - - return f -} - -// Float32 converts d into a float32. -func (d Decimal) Float32() float32 { - return float32(d.Float64()) -} - -// Float64 converts d into a float64. -func (d Decimal) Float64() float64 { - if d.isSpecial() { - if d.IsNaN() { - return math.NaN() - } - - if d.Signbit() { - return math.Inf(-1) - } - - return math.Inf(1) - } - - sig, exp := d.decompose() - - if sig[0]|sig[1] == 0 { - f := 0.0 - if d.Signbit() { - f = math.Copysign(f, -1.0) - } - - return f - } - - exp -= exponentBias - - if exp < -358 { - f := 0.0 - if d.Signbit() { - f = math.Copysign(f, -1.0) - } - - return f - } - - if exp > 308 { - if d.Signbit() { - return math.Inf(-1) - } - - return math.Inf(1) - } - - var sig256 uint256 - shift := int(exp) - exp = 0 - - if shift < 0 { - shift *= -1 - sig256 = uint256{0, 0, sig[0], sig[1]} - exp = -128 - - for shift != 0 { - zeros := bits.LeadingZeros64(sig256[3]) - sig256 = sig256.lsh(uint(zeros)) - exp -= int16(zeros) - - sig256, _ = sig256.div10() - shift-- - } - } else { - sig256 = uint256{sig[0], sig[1], 0, 0} - - for shift > 19 && sig256[3] == 0 { - sig256 = sig256.mul64(10_000_000_000_000_000_000) - shift -= 19 - } - - for shift != 0 && sig256[3] <= 0x18ff_ffff_ffff_ffff { - sig256 = sig256.mul64(10) - shift-- - } - - for shift != 0 { - sig256 = sig256.rsh(4) - exp += 4 - - for shift != 0 && sig256[3] <= 0x18ff_ffff_ffff_ffff { - sig256 = sig256.mul64(10) - shift-- - } - } - } - - zeros := bits.LeadingZeros64(sig256[3]) - for zeros != 0 { - sig256 = sig256.lsh(uint(zeros)) - exp -= int16(zeros) - zeros = bits.LeadingZeros64(sig256[3]) - } - - exp += 192 - f := float64(sig256[3]) - f = math.Ldexp(f, int(exp)) - - if d.Signbit() { - f = math.Copysign(f, -1.0) - } - - return f -} - -// Int converts d into a big.Int, truncating towards zero. If a non-nil -// argument i is provided, Int stores the result in i instead of allocating a -// new big.Int. It panics if d is NaN or infinite. -func (d Decimal) Int(i *big.Int) *big.Int { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Int()") - } - - if d.Signbit() { - panic("Decimal(-Inf).Int()") - } - - panic("Decimal(+Inf).Int()") - } - - sig, exp := d.decompose() - exp -= exponentBias - - if i == nil { - i = new(big.Int) - } - - if exp < -maxDigits { - return i - } - - if sig[1] == 0 { - i.SetUint64(sig[0]) - } else { - i.SetUint64(sig[1]) - i.Lsh(i, 64).Or(i, new(big.Int).SetUint64(sig[0])) - } - - if d.Signbit() { - i.Neg(i) - } - - if exp == 0 { - return i - } - - var bigexp *big.Int - if exp > 0 { - bigexp = big.NewInt(int64(exp)) - } else { - bigexp = big.NewInt(int64(exp * -1)) - } - - bigexp.Exp(big.NewInt(10), bigexp, nil) - - if exp > 0 { - i.Mul(i, bigexp) - } else { - i.Quo(i, bigexp) - } - - return i -} - -// Int32 converts d into an int32, truncating towards zero. If the result is -// outside the range of an int32 the returned value will be either -// [math.MinInt32] or [math.MaxInt32] depending on the sign of the result and -// the boolean value will be false. Otherwise the boolean value will be true. -// It panics if d is NaN. -func (d Decimal) Int32() (int32, bool) { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Int32()") - } - - if d.Signbit() { - return math.MinInt32, false - } - - return math.MaxInt32, false - } - - sig, exp := d.decompose() - exp -= exponentBias - - if exp < -maxDigits { - return 0, true - } - - for exp < 0 { - sig, _ = sig.div10() - exp++ - - if sig[0]|sig[1] == 0 { - exp = 0 - break - } - } - - for sig[1] == 0 && exp > 0 { - sig = sig.mul64(10) - exp-- - } - - if sig[1] != 0 || exp != 0 { - if d.Signbit() { - return math.MinInt32, false - } - - return math.MaxInt32, false - } - - neg := d.Signbit() - - if neg { - if sig[0] > math.MinInt32*-1 { - return math.MinInt32, false - } - } else { - if sig[0] > math.MaxInt32 { - return math.MaxInt32, false - } - } - - i := int32(sig[0]) - - if neg { - i *= -1 - } - - return i, true -} - -// Int64 converts d into an int64, truncating towards zero. If the result is -// outside the range of an int64 the returned value will be either -// [math.MinInt64] or [math.MaxInt64] depending on the sign of the result and -// the boolean value will be false. Otherwise the boolean value will be true. -// It panics if d is NaN. -func (d Decimal) Int64() (int64, bool) { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Int64()") - } - - if d.Signbit() { - return math.MinInt64, false - } - - return math.MaxInt64, false - } - - sig, exp := d.decompose() - exp -= exponentBias - - if exp < -maxDigits { - return 0, true - } - - for exp < 0 { - sig, _ = sig.div10() - exp++ - - if sig[0]|sig[1] == 0 { - exp = 0 - break - } - } - - for sig[1] == 0 && exp > 0 { - sig = sig.mul64(10) - exp-- - } - - if sig[1] != 0 || exp != 0 { - if d.Signbit() { - return math.MinInt64, false - } - - return math.MaxInt64, false - } - - neg := d.Signbit() - - if neg { - if sig[0] > math.MinInt64*-1 { - return math.MinInt64, false - } - } else { - if sig[0] > math.MaxInt64 { - return math.MaxInt64, false - } - } - - i := int64(sig[0]) - - if neg { - i *= -1 - } - - return i, true -} - -// Rat converts d into a big.Rat. If a non-nil argument r is provided, Rat -// stores the result in r instead of allocating a new big.Rat. It panics if d -// is NaN or infinite. -func (d Decimal) Rat(r *big.Rat) *big.Rat { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Rat()") - } - - if d.Signbit() { - panic("Decimal(-Inf).Rat()") - } - - panic("Decimal(+Inf).Rat()") - } - - sig, exp := d.decompose() - exp -= exponentBias - - if r == nil { - r = new(big.Rat) - } - - if exp == 0 && sig[1] == 0 { - r.SetUint64(sig[0]) - } else { - bigsig := new(big.Int).SetUint64(sig[1]) - bigsig.Lsh(bigsig, 64).Or(bigsig, new(big.Int).SetUint64(sig[0])) - - var bigexp *big.Int - if exp > 0 { - bigexp = big.NewInt(int64(exp)) - } else { - bigexp = big.NewInt(int64(exp * -1)) - } - - bigexp.Exp(big.NewInt(10), bigexp, nil) - - if exp > 0 { - bigsig.Mul(bigsig, bigexp) - r.SetInt(bigsig) - } else { - r.SetFrac(bigsig, bigexp) - } - } - - if d.Signbit() { - r.Neg(r) - } - - return r -} - -// Uint32 converts d into a uint32, truncating towards zero. If the result is -// outside the range of a uint32 the returned value will be either 0 or -// [math.MaxUint32] depending on the sign of the result and the boolean value -// will be false. Otherwise the boolean value will be true. It panics if d is -// NaN. -func (d Decimal) Uint32() (uint32, bool) { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Uint32()") - } - - if d.Signbit() { - return 0, false - } - - return math.MaxUint32, false - } - - if d.Signbit() { - return 0, false - } - - sig, exp := d.decompose() - exp -= exponentBias - - if exp < -maxDigits { - return 0, true - } - - for exp < 0 { - sig, _ = sig.div10() - exp++ - - if sig[0]|sig[1] == 0 { - exp = 0 - break - } - } - - for sig[1] == 0 && exp > 0 { - sig = sig.mul64(10) - exp-- - } - - if sig[1] != 0 || exp != 0 { - return math.MaxUint32, false - } - - if sig[0] > math.MaxUint32 { - return math.MaxUint32, false - } - - return uint32(sig[0]), true -} - -// Uint64 converts d into a uint64, truncating towards zero. If the result is -// outside the range of a uint64 the returned value will be either 0 or -// [math.MaxUint64] depending on the sign of the result and the boolean value -// will be false. Otherwise the boolean value will be true. It panics if d is -// NaN. -func (d Decimal) Uint64() (uint64, bool) { - if d.isSpecial() { - if d.IsNaN() { - panic("Decimal(NaN).Uint64()") - } - - if d.Signbit() { - return 0, false - } - - return math.MaxUint64, false - } - - if d.Signbit() { - return 0, false - } - - sig, exp := d.decompose() - exp -= exponentBias - - if exp < -maxDigits { - return 0, true - } - - for exp < 0 { - sig, _ = sig.div10() - exp++ - - if sig[0]|sig[1] == 0 { - exp = 0 - break - } - } - - for sig[1] == 0 && exp > 0 { - sig = sig.mul64(10) - exp-- - } - - if sig[1] != 0 || exp != 0 { - return math.MaxUint64, false - } - - return sig[0], true -} diff --git a/vendor/github.com/woodsbury/decimal128/decimal.go b/vendor/github.com/woodsbury/decimal128/decimal.go deleted file mode 100644 index 7cf9175..0000000 --- a/vendor/github.com/woodsbury/decimal128/decimal.go +++ /dev/null @@ -1,284 +0,0 @@ -// Package decimal128 provides a 128-bit decimal floating point type. -package decimal128 - -const ( - exponentBias = 6176 - maxBiasedExponent = 12287 - maxUnbiasedExponent = maxBiasedExponent - exponentBias - minBiasedExponent = 0 - minUnbiasedExponent = minBiasedExponent - exponentBias - maxDigits = 35 -) - -// Decimal represents a 128-bit decimal floating point value. The zero value -// for Decimal is the number +0.0. -type Decimal struct { - lo, hi uint64 -} - -// Abs returns a new Decimal set to the absolute value of d. -func Abs(d Decimal) Decimal { - return Decimal{d.lo, d.hi & 0x7fff_ffff_ffff_ffff} -} - -// Frexp breaks a finite, non-zero d into a fraction and an integral power of -// ten. The absolute value of the fraction will be in the interval [0.1, 1). -// -// If d is ±Inf, NaN, or zero the value is returned unchanged and the returned -// power of ten is zero. -func Frexp(d Decimal) (Decimal, int) { - if d.isSpecial() || d.IsZero() { - return d, 0 - } - - sig, exp := d.decompose() - rexp := int(exp) - exponentBias + sig.log10() + 1 - exp -= int16(rexp) - - return compose(d.Signbit(), sig, exp), rexp -} - -// Inf returns a new Decimal set to positive infinity if sign >= 0, or negative -// infinity if sign < 0. -func Inf(sign int) Decimal { - return inf(sign < 0) -} - -// Ldexp is the inverse of [Frexp], returning frac × 10**exp. -func Ldexp(frac Decimal, exp int) Decimal { - if frac.isSpecial() || frac.IsZero() { - return frac - } - - if exp < minUnbiasedExponent { - return zero(frac.Signbit()) - } - - if exp > maxUnbiasedExponent+39 { - return inf(frac.Signbit()) - } - - neg := frac.Signbit() - fsig, fexp := frac.decompose() - fexp += int16(exp) - - sig, exp16 := DefaultRoundingMode.reduce128(neg, fsig, fexp, 0) - - if exp16 > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp16) -} - -// NaN returns a new Decimal set to the "not-a-number" value. -func NaN() Decimal { - return nan(payloadOpNaN, 0, 0) -} - -// New returns a new Decimal with the provided significand and exponent. -func New(sig int64, exp int) Decimal { - if sig == 0 { - return zero(false) - } - - neg := false - if sig < 0 { - neg = true - sig *= -1 - } - - if exp < minUnbiasedExponent+19 { - return zero(neg) - } - - if exp > maxUnbiasedExponent+39 { - return inf(neg) - } - - sig128, exp16 := DefaultRoundingMode.reduce64(neg, uint64(sig), int16(exp+exponentBias)) - - if exp16 > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig128, exp16) -} - -func compose(neg bool, sig uint128, exp int16) Decimal { - var hi uint64 - if sig[1] > 0x0001_ffff_ffff_ffff { - hi = 0x6000_0000_0000_0000 | uint64(exp)<<47 | sig[1]&0x7fff_ffff_ffff - } else { - hi = uint64(exp)<<49 | sig[1] - } - - if neg { - hi |= 0x8000_0000_0000_0000 - } - - return Decimal{sig[0], hi} -} - -func inf(neg bool) Decimal { - if neg { - return Decimal{0, 0xf800_0000_0000_0000} - } - - return Decimal{0, 0x7800_0000_0000_0000} -} - -func nan(op, lhs, rhs Payload) Decimal { - return Decimal{uint64(op | lhs<<8 | rhs<<16), 0x7c00_0000_0000_0000} -} - -func one(neg bool) Decimal { - if neg { - return Decimal{1, 0xb040_0000_0000_0000} - } - - return Decimal{1, 0x3040_0000_0000_0000} -} - -func zero(neg bool) Decimal { - if neg { - return Decimal{0, 0x8000_0000_0000_0000} - } - - return Decimal{} -} - -// Canonical returns the result of converting d into its canonical -// representation. Many values have multiple possible ways of being represented -// as a Decimal. Canonical converts each of these into a single representation. -// -// If d is ±Inf or NaN, the canonical representation consists of only the bits -// required to represent the respective special floating point value with all -// other bits set to 0. For NaN values this also removes any payload it may -// have had. -// -// If d is ±0, the canonical representation consists of only the sign bit set -// based on the sign of the value with all other bits set to 0. -// -// If d is finite and non-zero, the canonical representation is calculated as -// the representation with an exponent closest to zero that still accurately -// stores all non-zero digits the value has. -func (d Decimal) Canonical() Decimal { - if d.isSpecial() { - if d.IsNaN() { - return nan(0, 0, 0) - } - - return inf(d.Signbit()) - } - - sig, exp := d.decompose() - - if sig[0]|sig[1] == 0 { - return zero(d.Signbit()) - } - - for exp > exponentBias { - tmp := sig.mul64(10) - - if tmp[1] > 0x0002_7fff_ffff_ffff { - break - } - - sig = tmp - exp-- - } - - for exp < exponentBias { - tmp, rem := sig.div10() - - if rem != 0 { - break - } - - sig = tmp - exp++ - } - - return compose(d.Signbit(), sig, exp) -} - -// IsInf reports whether d is an infinity. If sign > 0, IsInf reports whether -// d is positive infinity. If sign < 0, IsInf reports whether d is negative -// infinity. If sign == 0, IsInf reports whether d is either infinity. -func (d Decimal) IsInf(sign int) bool { - if !d.isInf() { - return false - } - - if sign == 0 { - return true - } - - if sign > 0 { - return !d.Signbit() - } - - return d.Signbit() -} - -// IsNaN reports whether d is a "not-a-number" value. -func (d Decimal) IsNaN() bool { - return d.hi&0x7c00_0000_0000_0000 == 0x7c00_0000_0000_0000 -} - -// Neg returns d with its sign negated. -func (d Decimal) Neg() Decimal { - return Decimal{d.lo, d.hi ^ 0x8000_0000_0000_0000} -} - -// Sign returns: -// -// -1 if d < 0 -// 0 if d is ±0 -// +1 if d > 0 -// -// It panics if d is NaN. -func (d Decimal) Sign() int { - if d.IsNaN() { - panic("Decimal(NaN).Sign()") - } - - if d.IsZero() { - return 0 - } - - if d.Signbit() { - return -1 - } - - return 1 -} - -// Signbit reports whether d is negative or negative zero. -func (d Decimal) Signbit() bool { - return d.hi&0x8000_0000_0000_0000 == 0x8000_0000_0000_0000 -} - -func (d Decimal) decompose() (uint128, int16) { - var sig uint128 - var exp int16 - - if d.hi&0x6000_0000_0000_0000 == 0x6000_0000_0000_0000 { - sig = uint128{d.lo, d.hi&0x7fff_ffff_ffff | 0x0002_0000_0000_0000} - exp = int16(d.hi & 0x1fff_8000_0000_0000 >> 47) - } else { - sig = uint128{d.lo, d.hi & 0x0001_ffff_ffff_ffff} - exp = int16(d.hi & 0x7ffe_0000_0000_0000 >> 49) - } - - return sig, exp -} - -func (d Decimal) isInf() bool { - return d.hi&0x7c00_0000_0000_0000 == 0x7800_0000_0000_0000 -} - -func (d Decimal) isSpecial() bool { - return d.hi&0x7800_0000_0000_0000 == 0x7800_0000_0000_0000 -} diff --git a/vendor/github.com/woodsbury/decimal128/decomposed.go b/vendor/github.com/woodsbury/decimal128/decomposed.go deleted file mode 100644 index ef74588..0000000 --- a/vendor/github.com/woodsbury/decimal128/decomposed.go +++ /dev/null @@ -1,1199 +0,0 @@ -package decimal128 - -import ( - "math" - "strconv" -) - -const expln = -57 - -var ( - dinf = decomposed192{ - sig: uint192{math.MaxUint64, math.MaxUint64, math.MaxUint64}, - exp: math.MaxInt16, - } - - ln10 = decomposed192{ - sig: uint192{0x0193_5df2_0be5_35a1, 0x05cd_f4ae_1bee_93d0, 0x5de8_1c2d_b4b8_b6e0}, - exp: -57, - } - - ln2 = decomposed192{ - sig: uint192{0x858a_b5e3_0047_4e69, 0x37c6_e47a_55a3_5374, 0x1c44_cb52_b6b7_4c42}, - exp: -57, - } - - invLn10 = decomposed192{ - sig: uint192{0x225c_04d6_a014_36d9, 0xff32_111e_97d1_0db8, 0xb11e_75a6_72b6_07b7}, - exp: -58, - } - - invLn2 = decomposed192{ - sig: uint192{0xf291_3320_09f2_3937, 0x9975_90b2_7010_b870, 0x3ad6_7064_88d7_799b}, - exp: -57, - } - - ln = [...]uint192{ - {0xce06_052e_ed85_0b11, 0xf432_4af7_5d64_cfcb, 0x03e3_15af_624a_52e7}, // ln(1.1) - {0xb352_8e25_962a_8d07, 0xa21f_990f_44a0_1c4d, 0x076f_869f_7595_b691}, // ln(1.2) - {0x1a25_cea3_d4a1_52e2, 0xe179_b27c_1d59_58e7, 0x0ab3_35f2_7f80_2c14}, // ln(1.3) - {0xc29b_26c7_4da3_cc33, 0x447d_92a8_ae23_ba16, 0x0db8_ef1e_b627_bfbd}, // ln(1.4) - {0x2445_ca6e_a139_d76e, 0x0098_e04e_5fa4_b5c0, 0x1089_40d5_0628_88ab}, // ln(1.5) - {0x1497_7999_f538_0401, 0xd94d_9d3b_3a9e_ba02, 0x132b_111d_2624_7a28}, // ln(1.6) - {0xbe13_49be_566b_31c0, 0x53f1_7e04_1b66_c1da, 0x15a4_0476_af99_0d2e}, // ln(1.7) - {0xd798_5894_3764_6475, 0xa2b8_795d_a444_d20d, 0x17f8_c774_7bbe_3f3c}, // ln(1.8) - {0x3ebb_a665_59ef_25c9, 0x3825_0832_751f_5f0a, 0x1a2d_446a_7ec9_5e1c}, // ln(1.9) - {0x858a_b5e3_0047_4e69, 0x37c6_e47a_55a3_5374, 0x1c44_cb52_b6b7_4c42}, // ln(2.0) - {0xe6e0_f135_eedd_a3a1, 0x4516_72f7_0dc8_6fd6, 0x1e42_2ff3_bc50_4868}, // ln(2.1) - {0x5390_bb11_edcc_597a, 0x2bf9_2f71_b308_2340, 0x2027_e102_1901_9f2a}, // ln(2.2) - {0xaef4_f891_bf7e_1f8d, 0x4361_9f46_37f4_3cb8, 0x21f7_fa1c_4962_edb7}, // ln(2.3) - {0x38dd_4408_9671_db6f, 0xd9e6_7d89_9a43_6fc2, 0x23b4_51f2_2c4d_02d3}, // ln(2.4) - {0xf67d_f22c_0b56_98d0, 0x9640_2bb9_70a7_ece6, 0x255e_8588_474a_1e5b}, // ln(2.5) - {0x9fb0_8486_d4e8_a14a, 0x1940_96f6_72fc_ac5b, 0x26f8_0145_3637_7857}, // ln(2.6) - {0xfbde_2302_d89e_3be3, 0xa351_59ac_03e9_87cd, 0x2882_0849_81e6_c7e7}, // ln(2.7) - {0x4825_dcaa_4deb_1a9b, 0x7c44_7723_03c7_0d8b, 0x29fd_ba71_6cdf_0bff}, // ln(2.8) - {0xb3e9_e533_f3b6_1ca8, 0xffd0_5b4b_98de_4ef8, 0x2b6c_1948_c734_4a0d}, // ln(2.9) - {0xa9d0_8051_a181_25d7, 0x385f_c4c8_b548_0934, 0x2cce_0c27_bcdf_d4ed}, // ln(3.0) - {0xc27d_4089_0337_700b, 0x7146_7807_969e_299d, 0x2e24_63a2_f2ca_b5c1}, // ln(3.1) - {0x9a22_2f7c_f57f_526a, 0x1114_81b5_9042_0d76, 0x2f6f_dc6f_dcdb_c66b}, // ln(3.2) - {0x77d6_8580_8f06_30e8, 0x2c92_0fc0_12ac_d900, 0x30b1_21d7_1f2a_27d5}, // ln(3.3) - {0x439d_ffa1_56b2_8029, 0x8bb8_627e_710a_154f, 0x31e8_cfc9_6650_5970}, // ln(3.4) - {0xb919_18f3_58fa_6503, 0xdabd_be62_1ecb_a6fd, 0x3317_74a6_fd71_de18}, // ln(3.5) - {0x5d23_0e77_37ab_b2dd, 0xda7f_5dd7_f9e8_2582, 0x343d_92c7_3275_8b7e}, // ln(3.6) - {0x69d0_a4c1_549f_d69c, 0xdd0f_8e01_8b1e_e9c9, 0x355b_a1ca_1731_b507}, // ln(3.7) - {0xc446_5c48_5a36_7431, 0x6feb_ecac_cac2_b27e, 0x3672_0fbd_3580_aa5e}, // ln(3.8) - {0xc3f6_4ef5_7622_78b8, 0x19d9_7744_d2a1_621b, 0x3781_421a_3c60_0102}, // ln(3.9) - {0x0b15_6bc6_008e_9cd1, 0x6f8d_c8f4_ab46_a6e9, 0x3889_96a5_6d6e_9884}, // ln(4.0) - {0xe28e_8b7b_5605_80b2, 0x397b_4431_992e_98ee, 0x398b_6430_9250_5cf1}, // ln(4.1) - {0x6c6b_a718_ef24_f209, 0x7cdd_5771_636b_c34b, 0x3a86_fb46_7307_94aa}, // ln(4.2) - {0xd8b1_0e6e_1f3a_6af6, 0xa701_96a9_626a_a2b9, 0x3b7c_a6c2_1ebe_1cab}, // ln(4.3) - {0xd91b_70f4_ee13_a7e3, 0x63c0_13ec_08ab_76b4, 0x3c6c_ac54_cfb8_eb6c}, // ln(4.4) - {0xce16_4ac0_42ba_fd45, 0x38f8_a517_14ec_bef4, 0x3d57_4cfc_c308_5d98}, // ln(4.5) - {0x347f_ae74_bfc5_6df6, 0x7b28_83c0_8d97_902d, 0x3e3c_c56f_001a_39f9}, // ln(4.6) - {0x43e8_ca2c_117f_6c0f, 0x398b_8628_b08d_cde8, 0x3f1d_4e75_bfcd_2079}, // ln(4.7) - {0xbe67_f9eb_96b9_29d8, 0x11ad_6203_efe6_c336, 0x3ff9_1d44_e304_4f16}, // ln(4.8) - {0x7bb4_3fba_a69e_3135, 0x1f3b_510a_ccef_6114, 0x40d0_63c5_b399_9dd6}, // ln(4.9) - {0x7c08_a80f_0b9d_e739, 0xce07_1033_c64b_405b, 0x41a3_50da_fe01_6a9d}, // ln(5.0) - {0x67e3_ca0f_f7ec_5797, 0x8c51_42cc_d0ae_cb0f, 0x4272_109e_6c78_e21b}, // ln(5.1) - {0x253b_3a69_d52f_efb3, 0x5107_7b70_c89f_ffd0, 0x433c_cc97_ecee_c499}, // ln(5.2) - {0xab7a_5b8e_d6d1_7c47, 0x1b42_3605_7910_936c, 0x4403_abef_d001_c5a5}, // ln(5.3) - {0x8168_d8e5_d8e5_8a4b, 0xdb18_3e26_598c_db42, 0x44c6_d39c_389e_1429}, // ln(5.4) - {0x4a0e_ad3d_f922_f24a, 0xc239_5b2b_23b0_1027, 0x4586_668a_604b_bd85}, // ln(5.5) - {0xcdb0_928d_4e32_6904, 0xb40b_5b9d_596a_60ff, 0x4642_85c4_2396_5841}, // ln(5.6) - {0xe88c_26b6_fb70_4b9f, 0x7084_ccfb_2a67_683e, 0x46fb_5092_3ba9_3309}, // ln(5.7) - {0x3974_9b16_f3fd_6b11, 0x3797_3fc5_ee81_a26d, 0x47b0_e49b_7deb_9650}, // ln(5.8) - {0xd2c2_8970_025a_1047, 0xaf22_6b1b_a088_567d, 0x4863_5e01_6fc8_129d}, // ln(5.9) - {0x2f5b_3634_a1c8_743f, 0x7026_a943_0aeb_5ca9, 0x4912_d77a_7397_212f}, // ln(6.0) - {0x9b3c_dbdf_230c_2578, 0x9616_fdb5_2530_20ba, 0x49bf_6a69_cbaa_177b}, // ln(6.1) - {0x4807_f66c_037e_be74, 0xa90d_5c81_ec41_7d12, 0x4a69_2ef5_a982_0203}, // ln(6.2) - {0x90b1_7187_905e_c977, 0x7d76_37bf_c310_790b, 0x4b10_3c1b_7930_1d55}, // ln(6.3) - {0x1fac_e55f_f5c6_a0d3, 0x48db_662f_e5e5_60eb, 0x4bb4_a7c2_9393_12ad}, // ln(6.4) - {0x962e_76b2_e03f_3a1a, 0xaf80_c2af_e3a4_9942, 0x4c56_86cd_7d81_96b2}, // ln(6.5) - {0xfd61_3b63_8f4d_7f51, 0x6458_f43a_6850_2c74, 0x4cf5_ed29_d5e1_7417}, // ln(6.6) - {0x4d02_0691_ecd6_5f10, 0xdef9_cc6c_3618_5eca, 0x4d92_eddf_1115_ca85}, // ln(6.7) - {0xc928_b584_56f9_ce91, 0xc37f_46f8_c6ad_68c3, 0x4e2d_9b1c_1d07_a5b2}, // ln(6.8) - {0x58c5_78e3_60ff_4564, 0x7bc1_640e_ed3c_45ed, 0x4ec6_0644_0642_c2a4}, // ln(6.9) - {0x3ea3_ced6_5941_b36b, 0x1284_a2dc_746e_fa72, 0x4f5c_3ff9_b429_2a5b}, // ln(7.0) - {0xf07c_9f19_1e68_0638, 0x3b1b_d0da_b4d3_d782, 0x4ff0_582a_d010_bcaf}, // ln(7.1) - {0xe2ad_c45a_37f3_0146, 0x1246_4252_4f8b_78f6, 0x5082_5e19_e92c_d7c1}, // ln(7.2) - {0x7083_fc6a_d208_73b2, 0x5445_67d2_67ad_ca0f, 0x5112_6067_e56c_3166}, // ln(7.3) - {0xef5b_5aa4_54e7_2504, 0x14d6_727b_e0c2_3d3d, 0x51a0_6d1c_cde9_014a}, // ln(7.4) - {0xa04e_727d_acd7_bea7, 0xce9f_f082_25ef_f61b, 0x522c_91b0_0429_f348}, // ln(7.5) - {0x49d1_122b_5a7d_c29a, 0xa7b2_d127_2066_05f3, 0x52b6_db0f_ec37_f6a0}, // ln(7.6) - {0x0ca9_d405_46c6_be7d, 0x06b6_edd3_d1d3_ca3e, 0x533f_55a9_1673_7d43}, // ln(7.7) - {0x4981_04d8_7669_c721, 0x51a0_5bbf_2844_b590, 0x53c6_0d6c_f317_4d44}, // ln(7.8) - {0x5e09_218f_8e58_6ba3, 0xcf83_91e4_317a_22d1, 0x544b_0dd8_1874_4ff3}, // ln(7.9) - {0x90a0_21a9_00d5_eb3a, 0xa754_ad6f_00e9_fa5d, 0x54ce_61f8_2425_e4c6}, // ln(8.0) - {0xa5ae_a354_7a1f_61b9, 0xdbb1_1e74_b931_9102, 0x5550_1471_3ec6_9cd4}, // ln(8.1) - {0x6819_415e_564c_cf1b, 0x7142_28ab_eed1_ec63, 0x55d0_2f83_4907_a933}, // ln(8.2) - {0x8db3_4b47_6c54_a96b, 0x62b0_75c1_2fb5_6287, 0x564e_bd0e_b877_bb77}, // ln(8.3) - {0xf1f6_5cfb_ef6c_4072, 0xb4a4_3beb_b90f_16bf, 0x56cb_c699_29be_e0ec}, // ln(8.4) - {0x3a1b_f1cd_6209_18f9, 0x21f8_8e37_e1b2_0236, 0x5747_5551_ad9a_77cc}, // ln(8.5) - {0x5e3b_c451_1f81_b95f, 0xdec8_7b23_b80d_f62e, 0x57c1_7214_d575_68ed}, // ln(8.6) - {0x5dba_6585_9537_427f, 0x3830_2014_4e26_582d, 0x583a_2570_8414_1efb}, // ln(8.7) - {0x5ea6_26d7_ee5a_f64b, 0x9b86_f866_5e4e_ca29, 0x58b1_77a7_8670_37ae}, // ln(8.8) - {0x0068_a073_0412_de69, 0xf885_50ee_b461_f78d, 0x5927_70b4_f88c_b48f}, // ln(8.9) - {0x53a1_00a3_4302_4bad, 0x70bf_8991_6a90_1269, 0x599c_184f_79bf_a9da}, // ln(9.0) - {0x58c9_9d7a_2de3_064d, 0xf3fe_5558_91c8_5359, 0x5a0f_75ec_33a9_566f}, // ln(9.1) - {0xba0a_6457_c00c_bc5f, 0xb2ef_683a_e33a_e3a1, 0x5a81_90c1_b6d1_863b}, // ln(9.2) - {0x6c4d_c0da_a4b8_95e2, 0xa9a6_3cd0_4be6_32d2, 0x5af2_6fca_afaa_8aae}, // ln(9.3) - {0xc973_800f_11c6_ba78, 0x7152_6aa3_0631_215c, 0x5b62_19c8_7684_6cbb}, // ln(9.4) - {0xbac4_4e74_658d_0d01, 0x062c_1866_3b6a_9f65, 0x5bd0_9545_7cca_c8ba}, // ln(9.5) - {0x43f2_afce_9700_7841, 0x4974_467e_458a_16ab, 0x5c3d_e897_99bb_9b58}, // ln(9.6) - {0x933f_0a3f_f913_ea27, 0xaada_8272_21d0_0c36, 0x5caa_19e2_389c_c6c5}, // ln(9.7) - {0x013e_f59d_a6e5_7f9e, 0x5702_3585_2292_b489, 0x5d15_2f18_6a50_ea18}, // ln(9.8) - {0x21a7_05d2_3087_56bf, 0x64f1_d488_c7f4_e235, 0x5d7f_2dfe_dc09_fcc2}, // ln(9.9) - } -) - -type decomposed192 struct { - sig uint192 - exp int16 -} - -func (d decomposed192) String() string { - return d.sig.String() + "e" + strconv.FormatInt(int64(d.exp), 10) -} - -func (d decomposed192) add(o decomposed192, trunc int8) (decomposed192, int8) { - exp := d.exp - o.exp - - if exp < 0 { - for exp <= -19 && o.sig[2] == 0 { - o.sig = o.sig.mul64(10_000_000_000_000_000_000) - o.exp -= 19 - exp += 19 - } - - for exp <= -4 && o.sig[2] <= 0x0002_7fff_ffff_ffff { - o.sig = o.sig.mul64(10_000) - o.exp -= 4 - exp += 4 - } - - for exp < 0 && o.sig[2] <= 0x18ff_ffff_ffff_ffff { - o.sig = o.sig.mul64(10) - o.exp-- - exp++ - } - - if exp < -57 { - if d.sig[0]|d.sig[1]|d.sig[2] != 0 { - d.sig = uint192{} - trunc = 1 - } - - d.exp = o.exp - exp = 0 - } - - for exp <= -4 { - var rem uint64 - d.sig, rem = d.sig.div10000() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - d.exp = o.exp - exp = 0 - } else { - d.exp += 4 - exp += 4 - } - } - - for exp < 0 { - var rem uint64 - d.sig, rem = d.sig.div10() - d.exp++ - exp++ - if rem != 0 { - trunc = 1 - } - } - } else if exp > 0 { - for exp >= 19 && d.sig[2] == 0 { - d.sig = d.sig.mul64(10_000_000_000_000_000_000) - d.exp -= 19 - exp -= 19 - } - - for exp >= 4 && d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - exp -= 4 - } - - for exp > 0 && d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - exp-- - } - - if exp > 57 { - if o.sig[0]|o.sig[1]|o.sig[2] != 0 { - o.sig = uint192{} - trunc = -1 - } - - exp = 0 - } - - for exp >= 4 { - var rem uint64 - o.sig, rem = o.sig.div10000() - if rem != 0 { - trunc = -1 - } - - if o.sig[0]|o.sig[1]|o.sig[2] == 0 { - exp = 0 - } else { - exp -= 4 - } - } - - for exp > 0 { - var rem uint64 - o.sig, rem = o.sig.div10() - exp-- - if rem != 0 { - trunc = 1 - } - } - } - - sig256 := d.sig.add(o.sig) - exp = d.exp - - for sig256[3] >= 0x0000_0000_0000_ffff { - var rem uint64 - sig256, rem = sig256.div10000() - exp += 4 - - if rem != 0 { - trunc = 1 - } - } - - for sig256[3] > 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - if rem != 0 { - trunc = 1 - } - } - - return decomposed192{ - sig: uint192{sig256[0], sig256[1], sig256[2]}, - exp: exp, - }, trunc -} - -func (d decomposed192) add1(trunc int8) (decomposed192, int8) { - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - if d.exp < -116 { - return decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, 1 - } - - if d.exp > 58 { - return d, 1 - } - - var sig256 uint256 - - if d.exp <= 0 { - for d.exp < -62 { - var rem uint64 - d.sig, rem = d.sig.div10000() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - d.exp += 4 - } - - for d.exp < -57 { - var rem uint64 - d.sig, rem = d.sig.div10() - d.exp++ - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - } - - sig256 = d.sig.add(uint192PowersOf10[-d.exp]) - } else { - for d.exp > 4 && d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.exp > 0 && d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - if d.exp != 0 { - return d, 1 - } - - sig256 = d.sig.add(uint192{1, 0, 0}) - } - - if sig256[3] != 0 { - var rem uint64 - sig256, rem = sig256.div10() - d.exp++ - - if rem != 0 { - trunc = 1 - } - } - - return decomposed192{ - sig: uint192{sig256[0], sig256[1], sig256[2]}, - exp: d.exp, - }, trunc -} - -func (d decomposed192) add1neg(trunc int8) (bool, decomposed192, int8) { - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return false, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - if d.exp < -116 { - return false, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - if d.exp > 58 { - return true, d, 1 - } - - var sig uint192 - var brw uint - - if d.exp <= 0 { - for d.exp < -62 { - var rem uint64 - d.sig, rem = d.sig.div10000() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return false, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - d.exp += 4 - } - - for d.exp < -57 { - var rem uint64 - d.sig, rem = d.sig.div10() - d.exp++ - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return false, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - } - - sig, brw = uint192PowersOf10[-d.exp].sub(d.sig) - } else { - for d.exp > 4 && d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.exp > 0 && d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - if d.exp != 0 { - return true, d, 1 - } - - sig, brw = uint192{1, 0, 0}.sub(d.sig) - } - - neg := false - - if brw != 0 { - sig = sig.twos() - neg = true - trunc *= -1 - } - - return neg, decomposed192{ - sig: sig, - exp: d.exp, - }, trunc -} - -func (d decomposed192) epow(l10 int16, trunc int8) (decomposed192, int8) { - exp := d.exp + l10 + 1 - if exp < 0 { - exp = 0 - } else { - d.exp = -l10 - 1 - } - - for d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - res, trunc := d.quo(decomposed192{ - sig: uint192{40, 0, 0}, - exp: 0, - }, trunc) - - for i := uint64(39); i > 1; i-- { - tmp, _ := d.quo(decomposed192{ - sig: uint192{i, 0, 0}, - exp: 0, - }, int8(0)) - - res, trunc = res.mul(tmp, trunc) - res, trunc = res.add1(trunc) - } - - res, trunc = res.mul(d, trunc) - res, trunc = res.add1(trunc) - - return res.powexp10(exp, trunc) -} - -func (d decomposed192) epowm1(neg bool, l10 int16, trunc int8) (bool, decomposed192, int8) { - exp := d.exp + l10 + 1 - if exp < 0 { - exp = 0 - } else { - d.exp = -l10 - 1 - } - - for d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - res, trunc := d.quo(decomposed192{ - sig: uint192{40, 0, 0}, - exp: 0, - }, trunc) - - for i := uint64(39); i > 1; i-- { - tmp, _ := d.quo(decomposed192{ - sig: uint192{i, 0, 0}, - exp: 0, - }, int8(0)) - - res, trunc = res.mul(tmp, trunc) - res, trunc = res.add1(trunc) - } - - res, trunc = res.mul(d, trunc) - - if res.exp > maxUnbiasedExponent+58 { - if neg { - return true, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, 0 - } - - return false, dinf, 0 - } - - if exp == 0 { - if neg { - res, trunc = res.add1(trunc) - res, trunc = res.rcp(trunc) - return res.sub1(trunc) - } - - return false, res, trunc - } - - res, trunc = res.add1(trunc) - res, trunc = res.powexp10(exp, trunc) - - if neg { - res, trunc = res.rcp(trunc) - } - - return res.sub1(trunc) -} - -func (d decomposed192) log() (bool, decomposed192, int8) { - l10 := int16(d.sig.log10()) - exp := d.exp + l10 - d.exp = -l10 - - msd := d.sig.msd2() - - for d.sig[2] == 0 { - d.sig = d.sig.mul64(10_000_000_000_000_000_000) - d.exp -= 19 - } - - for d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - if msd < 10 { - msd *= 10 - } - - var trunc int8 - if msd > 10 { - d, trunc = d.quo(decomposed192{ - sig: uint192{uint64(msd), 0, 0}, - exp: -1, - }, 0) - } - - _, num, _ := d.sub1(int8(0)) - den, _ := d.add1(int8(0)) - frc, trunc := num.quo(den, trunc) - sqr, _ := frc.pow2(int8(0)) - - res := frc - - for i := uint64(3); i <= 25; i += 2 { - // res += frc^i / i - frc, _ = frc.mul(sqr, int8(0)) - tmp, _ := frc.quo(decomposed192{ - sig: uint192{i, 0, 0}, - exp: 0, - }, int8(0)) - - res, trunc = res.add(tmp, trunc) - } - - expNeg := false - if exp < 0 { - exp *= -1 - expNeg = true - } - - lnExp, _ := ln10.mul(decomposed192{ - sig: uint192{uint64(exp), 0, 0}, - exp: 0, - }, int8(0)) - - res, trunc = res.mul(decomposed192{ - sig: uint192{2, 0, 0}, - exp: 0, - }, trunc) - - neg := false - if expNeg { - neg, res, trunc = res.sub(lnExp, trunc) - } else { - res, trunc = res.add(lnExp, trunc) - } - - if msd > 10 { - lnMSD := decomposed192{ - sig: ln[msd-11], - exp: expln, - } - - if expNeg { - _, res, trunc = res.sub(lnMSD, trunc) - } else { - res, trunc = res.add(lnMSD, trunc) - } - } - - return neg, res, trunc -} - -func (d decomposed192) log1p(neg bool) (bool, decomposed192, int8) { - num := d - res := d - - var trunc int8 - for i := uint64(2); i <= 10; i++ { - num, trunc = num.mul(d, trunc) - tmp, _ := num.quo(decomposed192{ - sig: uint192{i, 0, 0}, - exp: 0, - }, int8(0)) - - if i%2 == 0 { - if neg { - res, trunc = res.add(tmp, trunc) - } else { - _, res, trunc = res.sub(tmp, trunc) - } - } else { - res, trunc = res.add(tmp, trunc) - } - } - - return neg, res, trunc -} - -func (d decomposed192) mul(o decomposed192, trunc int8) (decomposed192, int8) { - sig384 := d.sig.mul(o.sig) - exp := d.exp + o.exp - - for sig384[5] > 0 { - var rem uint64 - sig384, rem = sig384.div1e19() - exp += 19 - - if rem != 0 { - trunc = 1 - } - } - - for sig384[4] > 0 { - var rem uint64 - sig384, rem = sig384.div1e19() - exp += 19 - - if rem != 0 { - trunc = 1 - } - } - - sig256 := uint256{sig384[0], sig384[1], sig384[2], sig384[3]} - - for sig256[3] >= 0x0000_0000_0fff_ffff { - var rem uint64 - sig256, rem = sig256.div1e8() - exp += 8 - - if rem != 0 { - trunc = 1 - } - } - - for sig256[3] >= 0x0000_0000_0000_ffff { - var rem uint64 - sig256, rem = sig256.div10000() - exp += 4 - - if rem != 0 { - trunc = 1 - } - } - - for sig256[3] > 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - - if rem != 0 { - trunc = 1 - } - } - - return decomposed192{ - sig: uint192{sig256[0], sig256[1], sig256[2]}, - exp: exp, - }, trunc -} - -func (d decomposed192) pow2(trunc int8) (decomposed192, int8) { - sig384 := d.sig.pow2() - exp := d.exp * 2 - - for sig384[5] > 0 { - var rem uint64 - sig384, rem = sig384.div1e19() - exp += 19 - - if rem != 0 { - trunc = 1 - } - } - - for sig384[4] > 0 { - var rem uint64 - sig384, rem = sig384.div1e19() - exp += 19 - - if rem != 0 { - trunc = 1 - } - } - - sig256 := uint256{sig384[0], sig384[1], sig384[2], sig384[3]} - - for sig256[3] >= 0x0000_0000_0000_ffff { - var rem uint64 - sig256, rem = sig256.div10000() - exp += 4 - - if rem != 0 { - trunc = 1 - } - } - - for sig256[3] > 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - - if rem != 0 { - trunc = 1 - } - } - - return decomposed192{ - sig: uint192{sig256[0], sig256[1], sig256[2]}, - exp: exp, - }, trunc -} - -func (d decomposed192) powexp10(o int16, trunc int8) (decomposed192, int8) { - var p10 int64 - switch o { - case 0: - return d, trunc - case 1: - p10 = 10 - case 2: - p10 = 100 - case 3: - p10 = 1_000 - case 4: - p10 = 10_000 - case 5: - p10 = 100_000 - case 6: - p10 = 1_000_000 - case 7: - p10 = 10_000_000 - case 8: - return dinf, trunc - } - - rtrunc := trunc - r := decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - } - - for p10 > 1 { - if int64(d.exp)*2 > math.MaxInt16-58*2 { - return dinf, trunc - } - - if p10&1 != 0 { - r, rtrunc = d.mul(r, rtrunc) - p10-- - } - - d, trunc = d.mul(d, trunc) - p10 /= 2 - } - - if int64(d.exp)+int64(r.exp) > math.MaxInt16 { - return dinf, trunc - } - - if rtrunc != 0 { - trunc = 1 - } - - return d.mul(r, trunc) -} - -func (d decomposed192) quo(o decomposed192, trunc int8) (decomposed192, int8) { - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return decomposed192{ - sig: uint192{}, - exp: 0, - }, trunc - } - - for d.sig[2] == 0 { - d.sig = d.sig.mul64(10_000_000_000_000_000_000) - d.exp -= 19 - } - - for d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - for o.sig[2] >= 0x18ff_ffff_ffff_ffff { - var rem uint64 - o.sig, rem = o.sig.div10() - o.exp++ - - if rem != 0 { - trunc = 1 - } - } - - sig, rem := d.sig.div(o.sig) - exp := d.exp - o.exp - - for rem[0]|rem[1]|rem[2] != 0 && sig[2] <= 0x18ff_ffff_ffff_ffff { - for rem[2] <= 0x0002_7fff_ffff_ffff && sig[2] <= 0x0002_7fff_ffff_ffff { - rem = rem.mul64(10_000) - sig = sig.mul64(10_000) - exp -= 4 - } - - for rem[2] <= 0x18ff_ffff_ffff_ffff && sig[2] <= 0x18ff_ffff_ffff_ffff { - rem = rem.mul64(10) - sig = sig.mul64(10) - exp-- - } - - var tmp uint192 - tmp, rem = rem.div(o.sig) - sig256 := sig.add(tmp) - - for sig256[3] != 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - - if rem != 0 { - trunc = 1 - } - } - - sig = uint192{sig256[0], sig256[1], sig256[2]} - } - - if rem[0]|rem[1]|rem[2] != 0 { - trunc = 1 - } - - return decomposed192{ - sig: sig, - exp: exp, - }, trunc -} - -func (d decomposed192) rcp(trunc int8) (decomposed192, int8) { - oneSig := uint192{0x4a00_0000_0000_0000, 0xebfd_cb54_864a_da83, 0x28c8_7cb5_c89a_2571} - - for d.sig[2] >= 0x18ff_ffff_ffff_ffff { - var rem uint64 - d.sig, rem = d.sig.div10() - d.exp++ - - if rem != 0 { - trunc = 1 - } - } - - sig, rem := oneSig.div(d.sig) - exp := -57 - d.exp - - for rem[0]|rem[1]|rem[2] != 0 && sig[2] <= 0x18ff_ffff_ffff_ffff { - for rem[2] <= 0x0002_7fff_ffff_ffff && sig[2] <= 0x0002_7fff_ffff_ffff { - rem = rem.mul64(10_000) - sig = sig.mul64(10_000) - exp -= 4 - } - - for rem[2] <= 0x18ff_ffff_ffff_ffff && sig[2] <= 0x18ff_ffff_ffff_ffff { - rem = rem.mul64(10) - sig = sig.mul64(10) - exp-- - } - - var tmp uint192 - tmp, rem = rem.div(d.sig) - sig256 := sig.add(tmp) - - for sig256[3] != 0 { - var rem uint64 - sig256, rem = sig256.div10() - exp++ - - if rem != 0 { - trunc = 1 - } - } - - sig = uint192{sig256[0], sig256[1], sig256[2]} - } - - if rem[0]|rem[1]|rem[2] != 0 { - trunc = 1 - } - - return decomposed192{ - sig: sig, - exp: exp, - }, trunc -} - -func (d decomposed192) sub(o decomposed192, trunc int8) (bool, decomposed192, int8) { - exp := d.exp - o.exp - - if exp < 0 { - for exp <= -19 && o.sig[2] == 0 { - o.sig = o.sig.mul64(10_000_000_000_000_000_000) - o.exp -= 19 - exp += 19 - } - - for exp <= -4 && o.sig[2] <= 0x0002_7fff_ffff_ffff { - o.sig = o.sig.mul64(10_000) - o.exp -= 4 - exp += 4 - } - - for exp < 0 && o.sig[2] <= 0x18ff_ffff_ffff_ffff { - o.sig = o.sig.mul64(10) - o.exp-- - exp++ - } - - if exp < -57 { - if d.sig[0]|d.sig[1]|d.sig[2] != 0 { - d.sig = uint192{} - trunc = 1 - } - - d.exp = o.exp - exp = 0 - } - - for exp <= -4 { - var rem uint64 - d.sig, rem = d.sig.div10000() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - d.exp = o.exp - exp = 0 - } else { - d.exp += 4 - exp += 4 - } - } - - for exp < 0 { - var rem uint64 - d.sig, rem = d.sig.div10() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - d.exp = o.exp - break - } - - d.exp++ - exp++ - } - } else if exp > 0 { - for exp >= 19 && d.sig[2] == 0 { - d.sig = d.sig.mul64(10_000_000_000_000_000_000) - d.exp -= 19 - exp -= 19 - } - - for exp >= 4 && d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - exp -= 4 - } - - for exp > 0 && d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - exp-- - } - - if exp > 57 { - if o.sig[0]|o.sig[1]|o.sig[2] != 0 { - o.sig = uint192{} - trunc = -1 - } - - exp = 0 - } - - for exp >= 4 { - var rem uint64 - o.sig, rem = o.sig.div10000() - if rem != 0 { - trunc = -1 - } - - if o.sig[0]|o.sig[1]|o.sig[2] == 0 { - exp = 0 - } else { - exp -= 4 - } - } - - for exp > 0 { - var rem uint64 - o.sig, rem = o.sig.div10() - if rem != 0 { - trunc = -1 - } - - if o.sig[0]|o.sig[1]|o.sig[2] == 0 { - break - } - - exp-- - } - } - - neg := false - sig, brw := d.sig.sub(o.sig) - exp = d.exp - - if brw != 0 { - sig = sig.twos() - neg = true - trunc *= -1 - } - - return neg, decomposed192{ - sig: sig, - exp: exp, - }, trunc -} - -func (d decomposed192) sub1(trunc int8) (bool, decomposed192, int8) { - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return true, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - if d.exp < -116 { - return true, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, 1 - } - - if d.exp > 58 { - return false, d, 1 - } - - var sig uint192 - var brw uint - - if d.exp <= 0 { - for d.exp < -62 { - var rem uint64 - d.sig, rem = d.sig.div10000() - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return true, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - - d.exp += 4 - } - - for d.exp < -57 { - var rem uint64 - d.sig, rem = d.sig.div10() - d.exp++ - if rem != 0 { - trunc = 1 - } - - if d.sig[0]|d.sig[1]|d.sig[2] == 0 { - return true, decomposed192{ - sig: uint192{1, 0, 0}, - exp: 0, - }, trunc - } - } - - sig, brw = d.sig.sub(uint192PowersOf10[-d.exp]) - } else { - for d.exp > 4 && d.sig[2] <= 0x0002_7fff_ffff_ffff { - d.sig = d.sig.mul64(10_000) - d.exp -= 4 - } - - for d.exp > 0 && d.sig[2] <= 0x18ff_ffff_ffff_ffff { - d.sig = d.sig.mul64(10) - d.exp-- - } - - if d.exp != 0 { - return false, d, 1 - } - - sig, brw = d.sig.sub(uint192{1, 0, 0}) - } - - neg := false - - if brw != 0 { - sig = sig.twos() - neg = true - trunc *= -1 - } - - return neg, decomposed192{ - sig: sig, - exp: d.exp, - }, trunc -} diff --git a/vendor/github.com/woodsbury/decimal128/exp.go b/vendor/github.com/woodsbury/decimal128/exp.go deleted file mode 100644 index 3ee67c1..0000000 --- a/vendor/github.com/woodsbury/decimal128/exp.go +++ /dev/null @@ -1,783 +0,0 @@ -package decimal128 - -import "math/bits" - -// Cbrt returns the cube root of d. -func Cbrt(d Decimal) Decimal { - if d.isSpecial() || d.IsZero() { - return d - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - l10 := int16(dSig.log10()) - - d192 := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - } - - d192x2 := decomposed192{ - sig: d192.sig.lsh(1), - exp: dExp, - } - - exp := dExp + l10 - if exp < 0 { - exp++ - } - - dExp -= exp - exp/3 - - res := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - } - - var trunc int8 - for i := 0; i < 7; i++ { - cub, _ := res.mul(res, int8(0)) - cub, _ = cub.mul(res, int8(0)) - - num, _ := cub.add(d192x2, int8(0)) - den, _ := cub.add(cub, int8(0)) - den, _ = den.add(d192, int8(0)) - frc, _ := num.quo(den, int8(0)) - res, trunc = res.mul(frc, trunc) - } - - neg := d.Signbit() - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Exp returns e**d, the base-e exponential of d. -func Exp(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.IsZero() { - return one(false) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - l10 := dSig.log10() - - if int(dExp) > 5-l10 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - }.epow(int16(l10), int8(0)) - - if res.exp > maxUnbiasedExponent+58 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.Signbit() { - res, trunc = res.rcp(trunc) - } - - sig, exp := DefaultRoundingMode.reduce192(false, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - return compose(false, sig, exp) -} - -// Exp10 returns 10**d, the base-10 exponential of d. -func Exp10(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.IsZero() { - return one(false) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - l10 := dSig.log10() - - if int(dExp) > 4-l10 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - var dSigInt uint - if l10+int(dExp) >= 0 { - sig := dSig - exp := dExp - dSig = uint128{} - - for exp < 0 { - var rem uint64 - sig, rem = sig.div10() - - dSig = dSig.mul64(10) - dSig = dSig.add64(rem) - exp++ - } - - dSigInt = uint(sig[0]) - - for exp > 0 { - dSigInt *= 10 - exp-- - } - - if dSigInt > maxUnbiasedExponent+58 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - sig = dSig - dSig = uint128{} - dExp = 0 - - for sig[0]|sig[1] != 0 { - var rem uint64 - sig, rem = sig.div10() - - dSig = dSig.mul64(10) - dSig = dSig.add64(rem) - dExp-- - } - } - - var res decomposed192 - var trunc int8 - - var sigInt uint128 - var expInt int16 - - if dSigInt != 0 { - sigInt = uint128{1, 0} - - for dSigInt > maxUnbiasedExponent { - sigInt = sigInt.mul64(10) - dSigInt-- - } - - expInt = int16(dSigInt) - } - - if dSig[0]|dSig[1] != 0 { - res, trunc = decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - }.mul(ln10, int8(0)) - - res, trunc = res.epow(int16(res.sig.log10()), trunc) - - if res.exp > maxUnbiasedExponent+58 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if expInt != 0 { - res.exp += expInt - } - } else { - res = decomposed192{ - sig: uint192{1, 0, 0}, - exp: expInt, - } - } - - if res.exp > maxUnbiasedExponent+58 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.Signbit() { - res, trunc = res.rcp(trunc) - } - - sig, exp := DefaultRoundingMode.reduce192(false, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - return compose(false, sig, exp) -} - -// Exp2 returns 2**d, the base-2 exponential of d. -func Exp2(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.IsZero() { - return one(false) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - l10 := dSig.log10() - - if int(dExp) > 5-l10 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - var dSigInt uint - if l10+int(dExp) >= 0 { - sig := dSig - exp := dExp - dSig = uint128{} - - for exp < 0 { - var rem uint64 - sig, rem = sig.div10() - - dSig = dSig.mul64(10) - dSig = dSig.add64(rem) - exp++ - } - - dSigInt = uint(sig[0]) - - for exp > 0 { - dSigInt *= 10 - exp-- - } - - sig = dSig - dSig = uint128{} - dExp = 0 - - for sig[0]|sig[1] != 0 { - var rem uint64 - sig, rem = sig.div10() - - dSig = dSig.mul64(10) - dSig = dSig.add64(rem) - dExp-- - } - } - - var res decomposed192 - var trunc int8 - - var sigInt uint192 - var expInt int16 - - if dSigInt != 0 { - if dSigInt > exponentBias+maxDigits { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - shift := dSigInt - - if shift < 64 { - sigInt[0] = 1 << shift - } else if shift < 128 { - sigInt[1] = 1 << (shift - 64) - } else { - var sigInt256 uint256 - if shift < 192 { - sigInt256[2] = 1 << (shift - 128) - } else if shift < 256 { - sigInt256[3] = 1 << (shift - 192) - } else { - sigInt256[3] = 0x8000_0000_0000_0000 - shift -= 255 - - for shift > 0 { - var rem uint64 - sigInt256, rem = sigInt256.div10() - expInt++ - - if rem != 0 { - trunc = 1 - } - - zeros := uint(bits.LeadingZeros64(sigInt256[3])) - if shift > zeros { - sigInt256 = sigInt256.lsh(zeros) - shift -= zeros - } else { - sigInt256 = sigInt256.lsh(shift) - break - } - } - } - - for sigInt256[3] > 0 { - var rem uint64 - sigInt256, rem = sigInt256.div1e19() - expInt += 19 - - if rem != 0 { - trunc = 1 - } - } - - sigInt = uint192{sigInt256[0], sigInt256[1], sigInt256[2]} - } - } - - if dSig[0]|dSig[1] != 0 { - res, trunc = decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - }.mul(ln2, int8(0)) - - res, trunc = res.epow(int16(res.sig.log10()), trunc) - - if res.exp > maxUnbiasedExponent+58 { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if dSigInt != 0 { - res, trunc = decomposed192{ - sig: sigInt, - exp: expInt, - }.mul(res, trunc) - } - } else { - res = decomposed192{ - sig: sigInt, - exp: expInt, - } - } - - if res.exp > maxUnbiasedExponent+maxDigits { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - if d.Signbit() { - res, trunc = res.rcp(trunc) - } - - sig, exp := DefaultRoundingMode.reduce192(false, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - if d.Signbit() { - return zero(false) - } - - return inf(false) - } - - return compose(false, sig, exp) -} - -// Expm1 returns e**d - 1, the base-e exponential of d minus 1. It is more -// accurate than Exp(d) - 1 when d is near zero. -func Expm1(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return one(true) - } - - return inf(false) - } - - if d.IsZero() { - return zero(false) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - l10 := dSig.log10() - - if int(dExp) > 5-l10 { - if d.Signbit() { - return one(true) - } - - return inf(false) - } - - neg, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - }.epowm1(d.Signbit(), int16(l10), int8(0)) - - if res.exp > maxUnbiasedExponent+58 { - if d.Signbit() { - return one(true) - } - - return inf(false) - } - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - if d.Signbit() { - return one(true) - } - - return inf(false) - } - - return compose(neg, sig, exp) -} - -// Log returns the natural logarithm of d. -func Log(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return nan(payloadOpLog, payloadValNegInfinite, 0) - } - - return inf(false) - } - - if d.IsZero() { - return inf(true) - } - - if d.Signbit() { - return nan(payloadOpLog, payloadValNegFinite, 0) - } - - dSig, dExp := d.decompose() - - neg, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp - exponentBias, - }.log() - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Log10 returns the decimal logarithm of d. -func Log10(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return nan(payloadOpLog10, payloadValNegInfinite, 0) - } - - return inf(false) - } - - if d.IsZero() { - return inf(true) - } - - if d.Signbit() { - return nan(payloadOpLog10, payloadValNegFinite, 0) - } - - dSig, dExp := d.decompose() - - neg, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp - exponentBias, - }.log() - - res, trunc = res.mul(invLn10, trunc) - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Log1p returns the natural logarithm 1 plus d. It is more accurate than -// Log(1 + d) when d is near zero. -func Log1p(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return nan(payloadOpLog1p, payloadValNegInfinite, 0) - } - - return inf(false) - } - - if d.IsZero() { - return zero(d.Signbit()) - } - - dSig, dExp := d.decompose() - dExp -= exponentBias - dNeg := d.Signbit() - - if dNeg { - if dExp > 0 { - return nan(payloadOpLog1p, payloadValNegFinite, 0) - } - - if dExp > int16(-len(uint128PowersOf10)) { - if cmp := dSig.cmp(uint128PowersOf10[-dExp]); cmp == 0 { - return inf(true) - } else if cmp > 0 { - return nan(payloadOpLog1p, payloadValNegFinite, 0) - } - } - } - - l10 := int16(dSig.log10()) + dExp - - if l10 > -10 { - res := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - } - - if dNeg { - _, res, _ = res.add1neg(0) - } else { - res, _ = res.add1(0) - } - - neg, res, trunc := res.log() - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) - } - - neg, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp, - }.log1p(d.Signbit()) - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Log2 returns the binary logarithm of d. -func Log2(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return nan(payloadOpLog2, payloadValNegInfinite, 0) - } - - return inf(false) - } - - if d.IsZero() { - return inf(true) - } - - if d.Signbit() { - return nan(payloadOpLog2, payloadValNegFinite, 0) - } - - dSig, dExp := d.decompose() - - neg, res, trunc := decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: dExp - exponentBias, - }.log() - - res, trunc = res.mul(invLn2, trunc) - - sig, exp := DefaultRoundingMode.reduce192(neg, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Sqrt returns the square root of d. -func Sqrt(d Decimal) Decimal { - if d.isSpecial() { - if d.IsNaN() { - return d - } - - if d.Signbit() { - return nan(payloadOpSqrt, payloadValNegInfinite, 0) - } - - return d - } - - if d.IsZero() { - return d - } - - if d.Signbit() { - return nan(payloadOpSqrt, payloadValNegFinite, 0) - } - - dSig, dExp := d.decompose() - l10 := int16(dSig.log10()) - dExp = (dExp - exponentBias) + l10 - - var add decomposed192 - var mul decomposed192 - var nrm decomposed192 - if dExp&1 == 0 { - add = decomposed192{ - sig: uint192{259, 0, 0}, - exp: -3, - } - - mul = decomposed192{ - sig: uint192{819, 0, 0}, - exp: -3, - } - - nrm = decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: -l10, - } - } else { - add = decomposed192{ - sig: uint192{819, 0, 0}, - exp: -4, - } - - mul = decomposed192{ - sig: uint192{259, 0, 0}, - exp: -2, - } - - nrm = decomposed192{ - sig: uint192{dSig[0], dSig[1], 0}, - exp: -l10 - 1, - } - - dExp++ - } - - res, trunc := nrm.mul(mul, int8(0)) - res, trunc = res.add(add, trunc) - - var tmp decomposed192 - half := decomposed192{ - sig: uint192{5, 0, 0}, - exp: -1, - } - - for i := 0; i < 8; i++ { - tmp, trunc = nrm.quo(res, trunc) - res, trunc = res.add(tmp, trunc) - res, trunc = half.mul(res, trunc) - } - - res.exp += dExp / 2 - sig, exp := DefaultRoundingMode.reduce192(false, res.sig, res.exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(false) - } - - return compose(false, sig, exp) -} diff --git a/vendor/github.com/woodsbury/decimal128/format.go b/vendor/github.com/woodsbury/decimal128/format.go deleted file mode 100644 index ed48ed5..0000000 --- a/vendor/github.com/woodsbury/decimal128/format.go +++ /dev/null @@ -1,929 +0,0 @@ -package decimal128 - -import ( - "fmt" - "unsafe" -) - -var ( - nanText = []byte("NaN") - padNaNText = []byte(" NaN") - posNaNText = []byte("+NaN") - negInfText = []byte("-Inf") - padInfText = []byte(" Inf") - posInfText = []byte("+Inf") - spaceText = []byte{' ', ' ', ' '} - - digitPairs = [...][2]byte{ - {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, - {'0', '5'}, {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, - {'1', '0'}, {'1', '1'}, {'1', '2'}, {'1', '3'}, {'1', '4'}, - {'1', '5'}, {'1', '6'}, {'1', '7'}, {'1', '8'}, {'1', '9'}, - {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'}, {'2', '4'}, - {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'}, - {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, - {'3', '5'}, {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, - {'4', '0'}, {'4', '1'}, {'4', '2'}, {'4', '3'}, {'4', '4'}, - {'4', '5'}, {'4', '6'}, {'4', '7'}, {'4', '8'}, {'4', '9'}, - {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'}, {'5', '4'}, - {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'}, - {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, - {'6', '5'}, {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, - {'7', '0'}, {'7', '1'}, {'7', '2'}, {'7', '3'}, {'7', '4'}, - {'7', '5'}, {'7', '6'}, {'7', '7'}, {'7', '8'}, {'7', '9'}, - {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'}, {'8', '4'}, - {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'}, - {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, - {'9', '5'}, {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}, - } -) - -// Append appends the string representation of the Decimal to the provided byte -// slice, as generated by [Format], and returns the updated byte slice. -func Append(buf []byte, d Decimal, fmt byte, prec int) []byte { - if d.isSpecial() { - return d.appendSpecial(buf, 0, false, false, false) - } - - var digs digits - d.digits(&digs) - - switch fmt { - case 'e', 'E': - if prec < 0 { - if digs.ndig != 0 { - prec = digs.ndig - 1 - } else { - prec = 0 - } - } else { - digs.round(prec + 1) - } - - return digs.fmtE(buf, prec, 0, false, false, false, true, false, false, fmt) - case 'f': - if prec < 0 { - if digs.exp < 0 { - prec = -digs.exp - } else { - prec = 0 - } - } else if digs.exp < 0 { - digs.round(digs.ndig + digs.exp + prec) - } - - return digs.fmtF(buf, prec, 0, false, false, false, false, false) - case 'g', 'G': - var maxprec int - if prec < 0 { - maxprec = 6 - prec = digs.ndig - } else { - if prec == 0 { - prec = 1 - } - - digs.round(prec) - maxprec = prec - prec = digs.ndig - } - - eprec := 0 - if digs.ndig != 0 { - eprec = digs.ndig - 1 - } - - exp := digs.exp + eprec - - if exp < -4 || exp >= maxprec { - e := byte('e') - if fmt == 'G' { - e = byte('E') - } - - return digs.fmtE(buf, prec-1, 0, false, false, false, true, false, false, e) - } else { - prec = 0 - if digs.exp < 0 { - prec -= digs.exp - } - - return digs.fmtF(buf, prec, 0, false, false, false, false, false) - } - default: - return append(buf, '%', fmt) - } -} - -// Format converts the Decimal to a string according to the provided format and -// precision. -// -// The format is one of 'e', 'E', 'f', 'g', or 'G'. -// -// The precision controls the number of digits in the resulting string. For -// 'e', 'E', and 'f' it is the number of digits after the decimal point. For -// 'g' and 'G' it is the maximum number of significant digits. The special -// precision -1 uses the smallest number of digits necessary to represent the -// Decimal. -func Format(d Decimal, fmt byte, prec int) string { - return string(Append(nil, d, fmt, prec)) -} - -// Append formats the Decimal according to the provided format specifier and -// appends the result to the provided byte slice, returning the updated byte -// slice. The format specifier can be any value supported by [Decimal.Format], -// without the leading %. -func (d Decimal) Append(buf []byte, format string) []byte { - var args formatArgs - parseFormat(format, &args) - - if args.verb == 0 { - return append(buf, "%!(NOVERB)"...) - } - - if d.isSpecial() { - width := 0 - padSign := false - printSign := false - if args.verb != 'v' { - printSign = args.printSign - padSign = args.padSign - - width = args.width() - } - - return d.appendSpecial(buf, width, printSign, padSign, args.padRight) - } - - return d.format(buf, &args) -} - -// Format implements the [fmt.Formatter] interface. It supports the verbs 'e', -// 'E', 'f', 'F', 'g', 'G', and 'v', along with the format flags '+', '-', '#', -// ' ', and '0' and custom width and precision values. Decimal values interpret -// the format value the same way float32 and float64 does. -func (d Decimal) Format(f fmt.State, verb rune) { - if d.isSpecial() { - width := 0 - padSign := false - printSign := false - if verb != 'v' { - printSign = f.Flag('+') - padSign = f.Flag(' ') - - w, hasWidth := f.Width() - if hasWidth { - width = w - } - } - - d.writeSpecial(f, width, printSign, padSign, f.Flag('-')) - return - } - - prec, hasPrec := f.Precision() - if !hasPrec { - prec = -1 - } - - width, hasWidth := f.Width() - if !hasWidth { - width = 0 - } - - args := formatArgs{ - forceDP: f.Flag('#'), - printSign: f.Flag('+'), - padSign: f.Flag(' '), - padRight: f.Flag('-'), - padZero: f.Flag('0'), - verb: byte(verb), - prec: prec, - wid: width, - } - - f.Write(d.format(nil, &args)) -} - -// MarshalText implements the [encoding.TextMarshaler] interface. -func (d Decimal) MarshalText() ([]byte, error) { - if d.isSpecial() { - return d.appendSpecial(nil, 0, false, false, false), nil - } - - var digs digits - d.digits(&digs) - - prec := 0 - if digs.ndig != 0 { - prec = digs.ndig - 1 - } - - exp := digs.exp + prec - - if exp < -4 || exp >= 6 { - return digs.fmtE(nil, prec, 0, false, false, false, true, false, false, 'e'), nil - } - - prec = 0 - if digs.exp < 0 { - prec = -digs.exp - } - - return digs.fmtF(nil, prec, 0, false, false, false, false, false), nil -} - -// String returns a string representation of the Decimal value. -func (d Decimal) String() string { - var buf []byte - if d.isSpecial() { - buf = d.appendSpecial(buf, 0, false, false, false) - } else { - var digs digits - d.digits(&digs) - - prec := 0 - if digs.ndig != 0 { - prec = digs.ndig - 1 - } - - exp := digs.exp + prec - - if exp < -4 || exp >= 6 { - buf = digs.fmtE(buf, prec, 0, false, false, false, true, false, false, 'e') - } else { - prec = 0 - if digs.exp < 0 { - prec = -digs.exp - } - - buf = digs.fmtF(buf, prec, 0, false, false, false, false, false) - } - } - - return unsafe.String(unsafe.SliceData(buf), len(buf)) -} - -func (d Decimal) appendSpecial(buf []byte, width int, printSign, padSign, padRight bool) []byte { - var value []byte - if d.IsNaN() { - if printSign { - value = posNaNText - } else if padSign { - value = padNaNText - } else { - value = nanText - } - } else { - if d.Signbit() { - value = negInfText - } else { - if padSign && !printSign { - value = padInfText - } else { - value = posInfText - } - } - } - - if cap(buf) == 0 { - sizeHint := len(value) - if width > sizeHint { - sizeHint = width - } - - buf = make([]byte, 0, sizeHint) - } - - n := len(value) - if p := width - n; p > 0 { - if padRight { - buf = append(buf, value...) - - for i := n; i < width; i++ { - buf = append(buf, ' ') - } - } else { - for i := 0; i < p; i++ { - buf = append(buf, ' ') - } - - buf = append(buf, value...) - } - } else { - buf = append(buf, value...) - } - - return buf -} - -func (d Decimal) digits(digs *digits) { - *digs = digits{} - digs.neg = d.Signbit() - - sig, exp := d.decompose() - - if sig[0]|sig[1] != 0 { - digs.exp = int(exp - exponentBias) - - n := 0 - for sig[1] != 0 { - var rem uint64 - sig, rem = sig.div100() - - if n == 0 && rem == 0 { - digs.exp += 2 - continue - } - - pair := digitPairs[rem] - - if n == 0 && pair[1] == '0' { - digs.exp++ - digs.dig[n] = pair[0] - n++ - continue - } - - if pair[0] == '0' && sig[0]|sig[1] == 0 { - digs.dig[n] = pair[1] - n++ - } else { - digs.dig[n], digs.dig[n+1] = pair[1], pair[0] - n += 2 - } - } - - sig64 := sig[0] - - for sig64 != 0 { - rem := sig64 % 100 - sig64 /= 100 - - if n == 0 && rem == 0 { - digs.exp += 2 - continue - } - - pair := digitPairs[rem] - - if n == 0 && pair[1] == '0' { - digs.exp++ - digs.dig[n] = pair[0] - n++ - continue - } - - if pair[0] == '0' && sig64 == 0 { - digs.dig[n] = pair[1] - n++ - } else { - digs.dig[n], digs.dig[n+1] = pair[1], pair[0] - n += 2 - } - } - - for i, j := 0, n-1; i < j; i, j = i+1, j-1 { - digs.dig[i], digs.dig[j] = digs.dig[j], digs.dig[i] - } - - digs.ndig = n - } -} - -func (d Decimal) format(buf []byte, args *formatArgs) []byte { - var digs digits - d.digits(&digs) - - prec, hasPrec := args.precision() - width := args.width() - - switch args.verb { - case 'e', 'E': - if !hasPrec { - prec = 6 - } - - digs.round(prec + 1) - return digs.fmtE(buf, prec, width, args.forceDP, args.printSign, args.padSign, true, args.padRight, args.padZero, args.verb) - case 'f', 'F': - if !hasPrec { - prec = 6 - } - - if digs.exp < 0 { - digs.round(digs.ndig + digs.exp + prec) - } - - return digs.fmtF(buf, prec, width, args.forceDP, args.printSign, args.padSign, args.padRight, args.padZero) - case 'g', 'G': - var maxprec int - if args.forceDP { - if !hasPrec { - if digs.ndig < 6 { - prec = 6 - } else { - prec = digs.ndig - } - - maxprec = 6 - } else { - if prec == 0 { - prec = 1 - } - - maxprec = prec - } - - digs.round(prec) - } else { - if hasPrec { - if prec == 0 { - prec = 1 - } - - digs.round(prec) - maxprec = prec - prec = digs.ndig - } else if digs.ndig != 0 { - maxprec = 6 - prec = digs.ndig - } else { - maxprec = 6 - } - } - - eprec := 0 - if digs.ndig != 0 { - eprec = digs.ndig - 1 - } - - exp := digs.exp + eprec - - if exp < -4 || exp >= maxprec { - e := byte('e') - if args.verb == 'G' { - e = byte('E') - } - - return digs.fmtE(buf, prec-1, width, args.forceDP, args.printSign, args.padSign, true, args.padRight, args.padZero, e) - } else { - if args.forceDP { - prec -= digs.exp - if digs.ndig == 0 { - prec-- - } else { - prec -= digs.ndig - } - } else { - prec = 0 - if digs.exp < 0 { - prec -= digs.exp - } - } - - return digs.fmtF(buf, prec, width, args.forceDP, args.printSign, args.padSign, args.padRight, args.padZero) - } - case 'v': - prec := 0 - if digs.ndig != 0 { - prec = digs.ndig - 1 - } - - exp := digs.exp + prec - - if exp < -4 || exp >= 6 { - return digs.fmtE(buf, prec, 0, false, false, false, true, false, false, 'e') - } else { - prec = 0 - if digs.exp < 0 { - prec = -digs.exp - } - } - - return digs.fmtF(buf, prec, 0, false, false, false, false, false) - default: - return fmt.Appendf(buf, "%%!%c(decimal128.Decimal=%s)", args.verb, d.String()) - } -} - -func (d Decimal) writeSpecial(f fmt.State, width int, printSign, padSign, padRight bool) { - var value []byte - if d.IsNaN() { - if printSign { - value = posNaNText - } else if padSign { - value = padNaNText - } else { - value = nanText - } - } else { - if d.Signbit() { - value = negInfText - } else { - if padSign && !printSign { - value = padInfText - } else { - value = posInfText - } - } - } - - n := len(value) - if p := width - n; p > 0 { - if padRight { - f.Write(value) - - i := n - for ; i < width-2; i += 3 { - f.Write(spaceText) - } - - if i < width-1 { - f.Write(spaceText[:2]) - } else if i < width { - f.Write(spaceText[:1]) - } - } else { - i := 0 - for ; i < p-2; i += 3 { - f.Write(spaceText) - } - - if i < p-1 { - f.Write(spaceText[:2]) - } else if i < p { - f.Write(spaceText[:1]) - } - - f.Write(value) - } - } else { - f.Write(value) - } -} - -type digits struct { - neg bool - dig [39]byte - exp int - ndig int -} - -func (d *digits) fmtE(buf []byte, prec, width int, forceDP, printSign, padSign, padExp, padRight, padZero bool, e byte) []byte { - if cap(buf) == 0 { - // Attempt to pre-size buffer to avoid multiple allocations. This might - // overshoot the actual needed size. Calculation is: - // sign + decimal point + 'e+/-' + exponent + zero + digits - sizeHint := 1 + 1 + 2 + 4 + 1 + d.ndig - if width > sizeHint { - sizeHint = width - } - - buf = make([]byte, 0, sizeHint) - } - - if d.neg { - buf = append(buf, '-') - } else if printSign { - buf = append(buf, '+') - } else if padSign { - buf = append(buf, ' ') - } - - if d.ndig == 0 { - buf = append(buf, '0') - } else { - buf = append(buf, d.dig[0]) - } - - if prec > 0 { - buf = append(buf, '.') - - i := 0 - if d.ndig > 1 { - buf = append(buf, d.dig[1:d.ndig]...) - i = d.ndig - 1 - } - - for ; i < prec; i++ { - buf = append(buf, '0') - } - } else if forceDP { - buf = append(buf, '.') - } - - buf = append(buf, e) - - exp := d.exp - if d.ndig > 1 { - exp += d.ndig - 1 - } - - if exp < 0 { - exp = -exp - buf = append(buf, '-') - } else { - buf = append(buf, '+') - } - - if exp < 10 { - if padExp { - buf = append(buf, '0', '0'+byte(exp)) - } else { - buf = append(buf, '0'+byte(exp)) - } - } else if exp < 100 { - buf = append(buf, '0'+byte(exp/10), '0'+byte(exp%10)) - } else if exp < 1000 { - buf = append(buf, '0'+byte(exp/100), '0'+byte(exp/10%10), '0'+byte(exp%10)) - } else { - buf = append(buf, '0'+byte(exp/1000), '0'+byte(exp/100%10), '0'+byte(exp/10%10), '0'+byte(exp%10)) - } - - buf = d.pad(buf, width, printSign, padSign, padRight, padZero) - return buf -} - -func (d *digits) fmtF(buf []byte, prec, width int, forceDP, printSign, padSign, padRight, padZero bool) []byte { - if cap(buf) == 0 { - // Attempt to pre-size buffer to avoid multiple allocations. This might - // overshoot the actual needed size. Calculation is: - // sign + decimal point + digits + zeros - sizeHint := 1 + 1 + d.ndig + d.exp - if width > sizeHint { - sizeHint = width - } - - buf = make([]byte, 0, sizeHint) - } - - if d.neg { - buf = append(buf, '-') - } else if printSign { - buf = append(buf, '+') - } else if padSign { - buf = append(buf, ' ') - } - - dp := 0 - if d.ndig == 0 { - buf = append(buf, '0') - } else { - dp = d.ndig + d.exp - - if dp > 0 { - if d.ndig > dp { - buf = append(buf, d.dig[:dp]...) - } else { - buf = append(buf, d.dig[:d.ndig]...) - - i := dp - d.ndig - for ; i > 2; i -= 3 { - buf = append(buf, '0', '0', '0') - } - - for ; i > 0; i-- { - buf = append(buf, '0') - } - } - } else { - buf = append(buf, '0') - } - } - - if prec > 0 { - buf = append(buf, '.') - - for ; dp < 0; dp++ { - prec-- - buf = append(buf, '0') - } - - i := 0 - if d.ndig > dp { - buf = append(buf, d.dig[dp:d.ndig]...) - i = d.ndig - dp - } - - for ; i < prec; i++ { - buf = append(buf, '0') - } - } else if forceDP { - buf = append(buf, '.') - } - - buf = d.pad(buf, width, printSign, padSign, padRight, padZero) - return buf -} - -func (d *digits) pad(buf []byte, width int, printSign, padSign, padRight, padZero bool) []byte { - p := width - len(buf) - if p <= 0 { - // No need for padding. - return buf - } - - padChar := byte(' ') - if padZero { - padChar = byte('0') - } - - if padRight { - for i := 0; i < p; i++ { - buf = append(buf, padChar) - } - } else { - // Determine where to keep the sign. - i := 0 - if padZero && (d.neg || printSign || padSign) { - i = 1 - p++ - } - - // Grow buf until it fits the nb + padding. - if len(buf) < width { - if cap(buf) < width { - tmp := make([]byte, width) - copy(tmp, buf) - buf = tmp - } else { - buf = buf[:width] - } - } - - // Move the existing number to the end of the buffer. - copy(buf[p:], buf[i:]) - - // Fill left-padding chars. - for ; i < p; i++ { - buf[i] = padChar - } - } - - return buf -} - -func (d *digits) round(prec int) { - if d.ndig <= prec { - return - } - - if prec < 0 { - d.exp += d.ndig - d.ndig = 0 - return - } - - up := false - if d.ndig > 1 && d.ndig == prec+1 && d.dig[prec] == '5' { - up = (d.dig[prec-1]-'0')%2 != 0 - } else { - up = d.dig[prec] >= '5' - } - - if up { - i := prec - 1 - for i >= 0 && d.dig[i] == '9' { - i-- - } - - if i == -1 { - d.dig[0] = '1' - d.exp += d.ndig - d.ndig = 1 - } else { - d.dig[i]++ - prec = i + 1 - d.exp += d.ndig - prec - d.ndig = prec - } - } else { - i := prec - 1 - for i >= 0 && d.dig[i] == '0' { - i-- - } - - prec = i + 1 - d.exp += d.ndig - prec - d.ndig = prec - } -} - -type formatArgs struct { - forceDP bool - printSign bool - padSign bool - padRight bool - padZero bool - verb byte - prec int - wid int -} - -func parseFormat(format string, args *formatArgs) { - *args = formatArgs{ - prec: -1, - } - - var c byte - i := 0 - end := len(format) - -parseFlags: - for ; i < end; i++ { - c = format[i] - switch c { - case ' ': - args.padSign = true - case '#': - args.forceDP = true - case '+': - args.printSign = true - case '-': - args.padRight = true - args.padZero = false - case '0': - args.padZero = !args.padRight - default: - break parseFlags - } - } - - if i >= end { - return - } - - if c >= '1' && c <= '9' { - args.wid = int(c - '0') - i++ - - for ; i < end; i++ { - c = format[i] - if c < '0' || c > '9' { - break - } - - if args.wid < 1e5 { - args.wid = args.wid*10 + int(c-'0') - } else { - args.wid = 0 - } - } - - if i >= end { - return - } - } - - if c == '.' { - i++ - if i >= end { - args.prec = 0 - return - } - - c = format[i] - if c < '0' || c > '9' { - args.prec = 0 - } else { - args.prec = int(c - '0') - i++ - - for ; i < end; i++ { - c = format[i] - if c < '0' || c > '9' { - break - } - - if args.prec < 1e5 { - args.prec = args.prec*10 + int(c-'0') - } else { - args.prec = -1 - } - } - - if i >= end { - return - } - } - } - - if i != end-1 { - return - } - - args.verb = c -} - -func (args formatArgs) precision() (int, bool) { - if args.prec < 0 { - return 0, false - } - - return args.prec, true -} - -func (args formatArgs) width() int { - return args.wid -} diff --git a/vendor/github.com/woodsbury/decimal128/int.go b/vendor/github.com/woodsbury/decimal128/int.go deleted file mode 100644 index 055449f..0000000 --- a/vendor/github.com/woodsbury/decimal128/int.go +++ /dev/null @@ -1,1017 +0,0 @@ -package decimal128 - -import ( - "math" - "math/bits" -) - -var ( - uint128PowersOf10 = [...]uint128{ - {0x0000_0000_0000_0001, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_000a, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_0064, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_03e8, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_2710, 0x0000_0000_0000_0000}, - {0x0000_0000_0001_86a0, 0x0000_0000_0000_0000}, - {0x0000_0000_000f_4240, 0x0000_0000_0000_0000}, - {0x0000_0000_0098_9680, 0x0000_0000_0000_0000}, - {0x0000_0000_05f5_e100, 0x0000_0000_0000_0000}, - {0x0000_0000_3b9a_ca00, 0x0000_0000_0000_0000}, - {0x0000_0002_540b_e400, 0x0000_0000_0000_0000}, - {0x0000_0017_4876_e800, 0x0000_0000_0000_0000}, - {0x0000_00e8_d4a5_1000, 0x0000_0000_0000_0000}, - {0x0000_0918_4e72_a000, 0x0000_0000_0000_0000}, - {0x0000_5af3_107a_4000, 0x0000_0000_0000_0000}, - {0x0003_8d7e_a4c6_8000, 0x0000_0000_0000_0000}, - {0x0023_86f2_6fc1_0000, 0x0000_0000_0000_0000}, - {0x0163_4578_5d8a_0000, 0x0000_0000_0000_0000}, - {0x0de0_b6b3_a764_0000, 0x0000_0000_0000_0000}, - {0x8ac7_2304_89e8_0000, 0x0000_0000_0000_0000}, - {0x6bc7_5e2d_6310_0000, 0x0000_0000_0000_0005}, - {0x35c9_adc5_dea0_0000, 0x0000_0000_0000_0036}, - {0x19e0_c9ba_b240_0000, 0x0000_0000_0000_021e}, - {0x02c7_e14a_f680_0000, 0x0000_0000_0000_152d}, - {0x1bce_cced_a100_0000, 0x0000_0000_0000_d3c2}, - {0x1614_0148_4a00_0000, 0x0000_0000_0008_4595}, - {0xdcc8_0cd2_e400_0000, 0x0000_0000_0052_b7d2}, - {0x9fd0_803c_e800_0000, 0x0000_0000_033b_2e3c}, - {0x3e25_0261_1000_0000, 0x0000_0000_204f_ce5e}, - {0x6d72_17ca_a000_0000, 0x0000_0001_431e_0fae}, - {0x4674_edea_4000_0000, 0x0000_000c_9f2c_9cd0}, - {0xc091_4b26_8000_0000, 0x0000_007e_37be_2022}, - {0x85ac_ef81_0000_0000, 0x0000_04ee_2d6d_415b}, - {0x38c1_5b0a_0000_0000, 0x0000_314d_c644_8d93}, - {0x378d_8e64_0000_0000, 0x0001_ed09_bead_87c0}, - {0x2b87_8fe8_0000_0000, 0x0013_4261_72c7_4d82}, - {0xb34b_9f10_0000_0000, 0x00c0_97ce_7bc9_0715}, - {0x00f4_36a0_0000_0000, 0x0785_ee10_d5da_46d9}, - {0x098a_2240_0000_0000, 0x4b3b_4ca8_5a86_c47a}, - } - - uint192PowersOf10 = [...]uint192{ - {0x0000_0000_0000_0001, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_000a, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_0064, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_03e8, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0000_2710, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0001_86a0, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_000f_4240, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_0098_9680, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_05f5_e100, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0000_3b9a_ca00, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0002_540b_e400, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0017_4876_e800, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_00e8_d4a5_1000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_0918_4e72_a000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0000_5af3_107a_4000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0003_8d7e_a4c6_8000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0023_86f2_6fc1_0000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0163_4578_5d8a_0000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x0de0_b6b3_a764_0000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x8ac7_2304_89e8_0000, 0x0000_0000_0000_0000, 0x0000_0000_0000_0000}, - {0x6bc7_5e2d_6310_0000, 0x0000_0000_0000_0005, 0x0000_0000_0000_0000}, - {0x35c9_adc5_dea0_0000, 0x0000_0000_0000_0036, 0x0000_0000_0000_0000}, - {0x19e0_c9ba_b240_0000, 0x0000_0000_0000_021e, 0x0000_0000_0000_0000}, - {0x02c7_e14a_f680_0000, 0x0000_0000_0000_152d, 0x0000_0000_0000_0000}, - {0x1bce_cced_a100_0000, 0x0000_0000_0000_d3c2, 0x0000_0000_0000_0000}, - {0x1614_0148_4a00_0000, 0x0000_0000_0008_4595, 0x0000_0000_0000_0000}, - {0xdcc8_0cd2_e400_0000, 0x0000_0000_0052_b7d2, 0x0000_0000_0000_0000}, - {0x9fd0_803c_e800_0000, 0x0000_0000_033b_2e3c, 0x0000_0000_0000_0000}, - {0x3e25_0261_1000_0000, 0x0000_0000_204f_ce5e, 0x0000_0000_0000_0000}, - {0x6d72_17ca_a000_0000, 0x0000_0001_431e_0fae, 0x0000_0000_0000_0000}, - {0x4674_edea_4000_0000, 0x0000_000c_9f2c_9cd0, 0x0000_0000_0000_0000}, - {0xc091_4b26_8000_0000, 0x0000_007e_37be_2022, 0x0000_0000_0000_0000}, - {0x85ac_ef81_0000_0000, 0x0000_04ee_2d6d_415b, 0x0000_0000_0000_0000}, - {0x38c1_5b0a_0000_0000, 0x0000_314d_c644_8d93, 0x0000_0000_0000_0000}, - {0x378d_8e64_0000_0000, 0x0001_ed09_bead_87c0, 0x0000_0000_0000_0000}, - {0x2b87_8fe8_0000_0000, 0x0013_4261_72c7_4d82, 0x0000_0000_0000_0000}, - {0xb34b_9f10_0000_0000, 0x00c0_97ce_7bc9_0715, 0x0000_0000_0000_0000}, - {0x00f4_36a0_0000_0000, 0x0785_ee10_d5da_46d9, 0x0000_0000_0000_0000}, - {0x098a_2240_0000_0000, 0x4b3b_4ca8_5a86_c47a, 0x0000_0000_0000_0000}, - {0x5f65_5680_0000_0000, 0xf050_fe93_8943_acc4, 0x0000_0000_0000_0002}, - {0xb9f5_6100_0000_0000, 0x6329_f1c3_5ca4_bfab, 0x0000_0000_0000_001d}, - {0x4395_ca00_0000_0000, 0xdfa3_71a1_9e6f_7cb5, 0x0000_0000_0000_0125}, - {0xa3d9_e400_0000_0000, 0xbc62_7050_305a_df14, 0x0000_0000_0000_0b7a}, - {0x6682_e800_0000_0000, 0x5bd8_6321_e38c_b6ce, 0x0000_0000_0000_72cb}, - {0x011d_1000_0000_0000, 0x9673_df52_e37f_2410, 0x0000_0000_0004_7bf1}, - {0x0b22_a000_0000_0000, 0xe086_b93c_e2f7_68a0, 0x0000_0000_002c_d76f}, - {0x6f5a_4000_0000_0000, 0xc543_3c60_ddaa_1640, 0x0000_0000_01c0_6a5e}, - {0x5986_8000_0000_0000, 0xb4a0_5bc8_a8a4_de84, 0x0000_0000_1184_27b3}, - {0x7f41_0000_0000_0000, 0x0e43_95d6_9670_b12b, 0x0000_0000_af29_8d05}, - {0xf88a_0000_0000_0000, 0x8ea3_da61_e066_ebb2, 0x0000_0006_d79f_8232}, - {0xb564_0000_0000_0000, 0x9266_87d2_c405_34fd, 0x0000_0044_6c3b_15f9}, - {0x15e8_0000_0000_0000, 0xb801_4e3b_a834_11e9, 0x0000_02ac_3a4e_dbbf}, - {0xdb10_0000_0000_0000, 0x300d_0e54_9208_b31a, 0x0000_1aba_4714_957d}, - {0x8ea0_0000_0000_0000, 0xe082_8f4d_b456_ff0c, 0x0001_0b46_c6cd_d6e3}, - {0x9240_0000_0000_0000, 0xc519_9909_0b65_f67d, 0x000a_70c3_c40a_64e6}, - {0xb680_0000_0000_0000, 0xb2ff_fa5a_71fb_a0e7, 0x0068_67a5_a867_f103}, - {0x2100_0000_0000_0000, 0xfdff_c788_73d4_490d, 0x0414_0c78_940f_6a24}, - {0x4a00_0000_0000_0000, 0xebfd_cb54_864a_da83, 0x28c8_7cb5_c89a_2571}, - } -) - -type uint128 [2]uint64 - -func (n uint128) String() string { - if n[0]|n[1] == 0 { - return "0" - } - - var buf [39]byte - - i := 39 - for n[0]|n[1] != 0 { - var d uint64 - n, d = n.div10() - i-- - buf[i] = '0' + byte(d) - } - - return string(buf[i:]) -} - -func (n uint128) add(o uint128) uint192 { - r0, carry := bits.Add64(n[0], o[0], 0) - r1, r2 := bits.Add64(n[1], o[1], carry) - - return uint192{r0, r1, r2} -} - -func (n uint128) add64(o uint64) uint128 { - r0, carry := bits.Add64(n[0], o, 0) - r1 := n[1] + carry - - return uint128{r0, r1} -} - -func (n uint128) cmp(o uint128) int { - if n[1] == o[1] { - if n[0] == o[0] { - return 0 - } - - if n[0] < o[0] { - return -1 - } - - return 1 - } - - if n[1] < o[1] { - return -1 - } - - return 1 -} - -func (n uint128) div(o uint128) (uint128, uint128) { - if o[1] == 0 { - var r0, r1, rem uint64 - if n[1] < o[0] { - r0, rem = bits.Div64(n[1], n[0], o[0]) - } else { - r1, rem = bits.Div64(0, n[1], o[0]) - r0, rem = bits.Div64(rem, n[0], o[0]) - } - - return uint128{r0, r1}, uint128{rem, 0} - } - - i := uint(bits.LeadingZeros64(o[1])) - u := o.lsh(i) - v := n.rsh(1) - r0, _ := bits.Div64(v[1], v[0], u[1]) - r0 >>= 63 - i - if r0 != 0 { - r0-- - } - - r := uint128{r0, 0} - rem, _ := n.sub(o.mul64(r0)) - - if rem.cmp(o) >= 0 { - r = r.add64(1) - rem, _ = rem.sub(o) - } - - return r, rem -} - -func (n uint128) div10() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 10 { - r0, rem = bits.Div64(n[1], n[0], 10) - } else { - r1, rem = bits.Div64(0, n[1], 10) - r0, rem = bits.Div64(rem, n[0], 10) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) div100() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 100 { - r0, rem = bits.Div64(n[1], n[0], 100) - } else { - r1, rem = bits.Div64(0, n[1], 100) - r0, rem = bits.Div64(rem, n[0], 100) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) div1000() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 1000 { - r0, rem = bits.Div64(n[1], n[0], 1000) - } else { - r1, rem = bits.Div64(0, n[1], 1000) - r0, rem = bits.Div64(rem, n[0], 1000) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) div10000() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 10_000 { - r0, rem = bits.Div64(n[1], n[0], 10_000) - } else { - r1, rem = bits.Div64(0, n[1], 10_000) - r0, rem = bits.Div64(rem, n[0], 10_000) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) div1e8() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 100_000_000 { - r0, rem = bits.Div64(n[1], n[0], 100_000_000) - } else { - r1, rem = bits.Div64(0, n[1], 100_000_000) - r0, rem = bits.Div64(rem, n[0], 100_000_000) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) div1e19() (uint128, uint64) { - var r0, r1, rem uint64 - if n[1] < 10_000_000_000_000_000_000 { - r0, rem = bits.Div64(n[1], n[0], 10_000_000_000_000_000_000) - } else { - r1, rem = bits.Div64(0, n[1], 10_000_000_000_000_000_000) - r0, rem = bits.Div64(rem, n[0], 10_000_000_000_000_000_000) - } - - return uint128{r0, r1}, rem -} - -func (n uint128) log10() int { - var l2 int - if n[1] != 0 { - l2 = bits.Len64(n[1]) + 64 - } else if n[0] != 0 { - l2 = bits.Len64(n[0]) - } else { - return 0 - } - - l10 := l2 * 1233 >> 12 - if n.cmp(uint128PowersOf10[l10]) < 0 { - l10-- - } - - return l10 -} - -func (n uint128) lsh(o uint) uint128 { - var r0, r1 uint64 - if o > 64 { - r1 = n[0] << (o - 64) - } else { - r0 = n[0] << o - r1 = n[1]<>(64-o) - } - - return uint128{r0, r1} -} - -func (n uint128) mul(o uint128) uint256 { - s1, r0 := bits.Mul64(n[0], o[0]) - t2, t1 := bits.Mul64(n[1], o[0]) - u2, u1 := bits.Mul64(n[0], o[1]) - v3, v2 := bits.Mul64(n[1], o[1]) - - r1, carry := bits.Add64(s1, t1, 0) - r2, w3 := bits.Add64(t2, u2, carry) - r1, carry = bits.Add64(r1, u1, 0) - r2, x3 := bits.Add64(r2, v2, carry) - r3, _ := bits.Add64(v3, w3, x3) - - return uint256{r0, r1, r2, r3} -} - -func (n uint128) mul1e38() uint256 { - const o0 = 687399551400673280 - const o1 = 5421010862427522170 - - s1, r0 := bits.Mul64(n[0], o0) - t2, t1 := bits.Mul64(n[1], o0) - u2, u1 := bits.Mul64(n[0], o1) - v3, v2 := bits.Mul64(n[1], o1) - - r1, carry := bits.Add64(s1, t1, 0) - r2, w3 := bits.Add64(t2, u2, carry) - r1, carry = bits.Add64(r1, u1, 0) - r2, x3 := bits.Add64(r2, v2, carry) - r3, _ := bits.Add64(v3, w3, x3) - - return uint256{r0, r1, r2, r3} -} - -func (n uint128) mul64(o uint64) uint128 { - r1, r0 := bits.Mul64(n[0], o) - r1 += n[1] * o - - return uint128{r0, r1} -} - -func (n uint128) or64(o uint64) uint128 { - return uint128{n[0] | o, n[1]} -} - -func (n uint128) rsh(o uint) uint128 { - var r0, r1 uint64 - if o > 64 { - r0 = n[1] >> (o - 64) - } else { - r0 = n[0]>>o | n[1]<<(64-o) - r1 = n[1] >> o - } - - return uint128{r0, r1} -} - -func (n uint128) sub(o uint128) (uint128, uint) { - r0, borrow := bits.Sub64(n[0], o[0], 0) - r1, borrow := bits.Sub64(n[1], o[1], borrow) - - return uint128{r0, r1}, uint(borrow) -} - -func (n uint128) sub64(o uint64) uint128 { - r0, borrow := bits.Sub64(n[0], o, 0) - r1 := n[1] - borrow - - return uint128{r0, r1} -} - -func (n uint128) twos() uint128 { - r0, carry := bits.Add64(^n[0], 1, 0) - r1 := ^n[1] + carry - - return uint128{r0, r1} -} - -type uint192 [3]uint64 - -func (n uint192) String() string { - if n[0]|n[1]|n[2] == 0 { - return "0" - } - - var buf [58]byte - - i := 58 - for n[0]|n[1]|n[2] != 0 { - var d uint64 - n, d = n.div10() - i-- - buf[i] = '0' + byte(d) - } - - return string(buf[i:]) -} - -func (n uint192) add(o uint192) uint256 { - r0, carry := bits.Add64(n[0], o[0], 0) - r1, carry := bits.Add64(n[1], o[1], carry) - r2, r3 := bits.Add64(n[2], o[2], carry) - - return uint256{r0, r1, r2, r3} -} - -func (n uint192) add64(o uint64) uint192 { - r0, carry := bits.Add64(n[0], o, 0) - r1, carry := bits.Add64(n[1], 0, carry) - r2 := n[2] + carry - - return uint192{r0, r1, r2} -} - -func (n uint192) cmp(o uint192) int { - if n[2] == o[2] { - if n[1] == o[1] { - if n[0] == o[0] { - return 0 - } - - if n[0] < o[0] { - return -1 - } - - return 1 - } - - if n[1] < o[1] { - return -1 - } - - return 1 - } - - if n[2] < o[2] { - return -1 - } - - return 1 -} - -func (n uint192) div(o uint192) (uint192, uint192) { - if o[2] == 0 { - if o[1] == 0 { - var r0, r1, r2, rem uint64 - if n[2] < o[0] { - r1, rem = bits.Div64(n[2], n[1], o[0]) - r0, rem = bits.Div64(rem, n[0], o[0]) - } else { - r2, rem = bits.Div64(0, n[2], o[0]) - r1, rem = bits.Div64(rem, n[1], o[0]) - r0, rem = bits.Div64(rem, n[0], o[0]) - } - - return uint192{r0, r1, r2}, uint192{rem, 0, 0} - } - - i := uint(bits.LeadingZeros64(o[1])) - u := o.lsh(i) - - if n[2] == 0 { - v := n.rsh(1) - r0, _ := bits.Div64(v[1], v[0], u[1]) - r0 >>= 63 - i - if r0 != 0 { - r0-- - } - - r := uint192{r0, 0, 0} - rem, _ := n.sub(o.mul64(r0)) - - if rem.cmp(o) >= 0 { - r = r.add64(1) - rem, _ = rem.sub(o) - } - - return r, rem - } - - if n[2] < o[1] { - v := n.lsh(i) - r0, ur := bits.Div64(v[2], v[1], u[1]) - - p1, p0 := bits.Mul64(r0, u[0]) - if p1 > ur || (p1 == ur && p0 > v[0]) { - r0-- - ur, carry := bits.Add64(ur, u[1], 0) - - if carry == 0 { - p1, p0 = bits.Mul64(r0, u[0]) - if p1 > ur || (p1 == ur && p0 > v[0]) { - r0-- - } - } - } - - r := uint192{r0, 0, 0} - - q := o.mul(r) - rem, _ := n.sub(uint192{q[0], q[1], q[2]}) - - if rem.cmp(o) >= 0 { - rem, _ = rem.sub(o) - r = r.add64(1) - } - - return r, rem - } - - v := uint256{n[0], n[1], n[2], 0}.lsh(i) - r1, ur := bits.Div64(v[3], v[2], u[1]) - - p1, p0 := bits.Mul64(r1, u[0]) - if p1 > ur || (p1 == ur && p0 > v[1]) { - ur, carry := bits.Add64(ur, u[1], 0) - r1-- - - if carry == 0 { - p1, p0 = bits.Mul64(r1, u[0]) - if p1 > ur || (p1 == ur && p0 > v[1]) { - r1-- - } - } - } - - q192 := u.mul64(r1) - rem, _ := uint192{v[1], v[2], v[3]}.sub(q192) - - if rem.cmp(u) >= 0 { - rem, _ = rem.sub(u) - r1++ - } - - var r0 uint64 - if rem[1] == u[1] { - r0, ur = math.MaxUint64, rem[0] - } else { - r0, ur = bits.Div64(rem[1], rem[0], u[1]) - } - - p1, p0 = bits.Mul64(r0, u[0]) - if p1 > ur || (p1 == ur && p0 > v[0]) { - var carry uint64 - ur, carry = bits.Add64(ur, u[1], 0) - r0-- - - if carry == 0 { - p1, p0 = bits.Mul64(r0, u[0]) - if p1 > ur || (p1 == ur && p0 > v[0]) { - r0-- - } - } - } - - r := uint192{r0, r1, 0} - - q := o.mul(r) - rem, _ = n.sub(uint192{q[0], q[1], q[2]}) - - if rem.cmp(o) >= 0 { - rem, _ = rem.sub(o) - r = r.add64(1) - } - - return r, rem - } - - i := uint(bits.LeadingZeros64(o[2])) - u := o.lsh(i) - v := n.rsh(1) - r0, ur := bits.Div64(v[2], v[1], u[2]) - - p1, p0 := bits.Mul64(r0, u[1]) - if p1 > ur || (p1 == ur && p0 > v[0]) { - r0-- - } - - r0 >>= 63 - i - if r0 != 0 { - r0-- - } - - r := uint192{r0, 0, 0} - - q := o.mul(r) - rem, _ := n.sub(uint192{q[0], q[1], q[2]}) - - if rem.cmp(o) >= 0 { - rem, _ = rem.sub(o) - r = r.add64(1) - } - - return r, rem -} - -func (n uint192) div10() (uint192, uint64) { - var r1, r2, rem uint64 - if n[2] < 10 { - r1, rem = bits.Div64(n[2], n[1], 10) - } else { - r2, rem = bits.Div64(0, n[2], 10) - r1, rem = bits.Div64(rem, n[1], 10) - } - - r0, rem := bits.Div64(rem, n[0], 10) - - return uint192{r0, r1, r2}, rem -} - -func (n uint192) div10000() (uint192, uint64) { - var r1, r2, rem uint64 - if n[2] < 10000 { - r1, rem = bits.Div64(n[2], n[1], 10000) - } else { - r2, rem = bits.Div64(0, n[2], 10000) - r1, rem = bits.Div64(rem, n[1], 10000) - } - - r0, rem := bits.Div64(rem, n[0], 10000) - - return uint192{r0, r1, r2}, rem -} - -func (n uint192) div1e8() (uint192, uint64) { - var r1, r2, rem uint64 - if n[2] < 100_000_000 { - r1, rem = bits.Div64(n[2], n[1], 100_000_000) - } else { - r2, rem = bits.Div64(0, n[2], 100_000_000) - r1, rem = bits.Div64(rem, n[1], 100_000_000) - } - - r0, rem := bits.Div64(rem, n[0], 100_000_000) - - return uint192{r0, r1, r2}, rem -} - -func (n uint192) div1e19() (uint192, uint64) { - var r1, r2, rem uint64 - if n[2] < 10_000_000_000_000_000_000 { - r1, rem = bits.Div64(n[2], n[1], 10_000_000_000_000_000_000) - } else { - r2, rem = bits.Div64(0, n[2], 10_000_000_000_000_000_000) - r1, rem = bits.Div64(rem, n[1], 10_000_000_000_000_000_000) - } - - r0, rem := bits.Div64(rem, n[0], 10_000_000_000_000_000_000) - - return uint192{r0, r1, r2}, rem -} - -func (n uint192) log10() int { - var l2 int - if n[2] != 0 { - l2 = bits.Len64(n[2]) + 128 - } else if n[1] != 0 { - l2 = bits.Len64(n[1]) + 64 - } else if n[0] != 0 { - l2 = bits.Len64(n[0]) - } else { - return 0 - } - - l10 := l2 * 1233 >> 12 - if n.cmp(uint192PowersOf10[l10]) < 0 { - l10-- - } - - return l10 -} - -func (n uint192) lsh(o uint) uint192 { - var r0, r1, r2 uint64 - if o > 128 { - r2 = n[0] << (o - 128) - } else if o > 64 { - r1 = n[0] << (o - 64) - r2 = n[1]<<(o-64) | n[0]>>(128-o) - } else { - r0 = n[0] << o - r1 = n[1]<>(64-o) - r2 = n[2]<>(64-o) - } - - return uint192{r0, r1, r2} -} - -func (n uint192) mul(o uint192) uint384 { - s1, r0 := bits.Mul64(n[0], o[0]) - t2, t1 := bits.Mul64(n[1], o[0]) - s3, s2 := bits.Mul64(n[2], o[0]) - u2, u1 := bits.Mul64(n[0], o[1]) - v3, v2 := bits.Mul64(n[1], o[1]) - u4, u3 := bits.Mul64(n[2], o[1]) - w3, w2 := bits.Mul64(n[0], o[2]) - x4, x3 := bits.Mul64(n[1], o[2]) - w5, w4 := bits.Mul64(n[2], o[2]) - - r1, carry := bits.Add64(s1, t1, 0) - r2, a3 := bits.Add64(s2, t2, carry) - r1, carry = bits.Add64(r1, u1, 0) - r2, b3 := bits.Add64(r2, u2, carry) - r2, carry = bits.Add64(r2, v2, 0) - r3, a4 := bits.Add64(s3, u3, a3) - r3, b4 := bits.Add64(r3, v3, b3) - r3, c4 := bits.Add64(r3, w3, carry) - r2, carry = bits.Add64(r2, w2, 0) - r3, carry = bits.Add64(r3, x3, carry) - r4, a5 := bits.Add64(u4, w4, a4) - r4, b5 := bits.Add64(r4, x4, b4) - r4, carry = bits.Add64(r4, c4+carry, 0) - r5, _ := bits.Add64(w5, a5+b5+carry, 0) - - return uint384{r0, r1, r2, r3, r4, r5} -} - -func (n uint192) mul64(o uint64) uint192 { - s1, r0 := bits.Mul64(n[0], o) - t2, t1 := bits.Mul64(n[1], o) - u2 := n[2] * o - - r1, carry := bits.Add64(s1, t1, 0) - r2, _ := bits.Add64(t2, u2, carry) - - return uint192{r0, r1, r2} -} - -func (n uint192) msd2() int { - for n[2] >= 10 { - n, _ = n.div1e19() - } - - if n[2] != 0 { - n, _ = n.div10() - } - - n128 := uint128{n[0], n[1]} - - for n128[1] >= 10 { - n128, _ = n128.div1e19() - } - - if n128[1] != 0 { - n128, _ = n128.div10() - } - - n64 := n128[0] - - for n64 >= 10000 { - n64 /= 1000 - } - - for n64 >= 100 { - n64 /= 10 - } - - return int(n64) -} - -func (n uint192) pow2() uint384 { - s1, r0 := bits.Mul64(n[0], n[0]) - t2, t1 := bits.Mul64(n[1], n[0]) - s3, s2 := bits.Mul64(n[2], n[0]) - u2, u1 := bits.Mul64(n[0], n[1]) - v3, v2 := bits.Mul64(n[1], n[1]) - u4, u3 := bits.Mul64(n[2], n[1]) - w3, w2 := bits.Mul64(n[0], n[2]) - x4, x3 := bits.Mul64(n[1], n[2]) - w5, w4 := bits.Mul64(n[2], n[2]) - - r1, carry := bits.Add64(s1, t1, 0) - r2, a3 := bits.Add64(s2, t2, carry) - r1, carry = bits.Add64(r1, u1, 0) - r2, b3 := bits.Add64(r2, u2, carry) - r2, carry = bits.Add64(r2, v2, 0) - r3, a4 := bits.Add64(s3, u3, a3) - r3, b4 := bits.Add64(r3, v3, b3) - r3, c4 := bits.Add64(r3, w3, carry) - r2, carry = bits.Add64(r2, w2, 0) - r3, carry = bits.Add64(r3, x3, carry) - r4, a5 := bits.Add64(u4, w4, a4) - r4, b5 := bits.Add64(r4, x4, b4) - r4, carry = bits.Add64(r4, c4+carry, 0) - r5, _ := bits.Add64(w5, a5+b5+carry, 0) - - return uint384{r0, r1, r2, r3, r4, r5} -} - -func (n uint192) rsh(o uint) uint192 { - var r0, r1, r2 uint64 - if o > 128 { - r0 = n[2] >> (o - 128) - } else if o > 64 { - r0 = n[1]>>(o-64) | n[2]<<(128-o) - r1 = n[2] >> (o - 64) - } else { - r0 = n[0]>>o | n[1]<<(64-o) - r1 = n[1]>>o | n[2]<<(64-o) - r2 = n[2] >> o - } - - return uint192{r0, r1, r2} -} - -func (n uint192) sub(o uint192) (uint192, uint) { - r0, borrow := bits.Sub64(n[0], o[0], 0) - r1, borrow := bits.Sub64(n[1], o[1], borrow) - r2, borrow := bits.Sub64(n[2], o[2], borrow) - - return uint192{r0, r1, r2}, uint(borrow) -} - -func (n uint192) sub64(o uint64) uint192 { - r0, borrow := bits.Sub64(n[0], o, 0) - r1, borrow := bits.Sub64(n[1], 0, borrow) - r2 := n[2] - borrow - - return uint192{r0, r1, r2} -} - -func (n uint192) twos() uint192 { - r0, carry := bits.Add64(^n[0], 1, 0) - r1, carry := bits.Add64(^n[1], 0, carry) - r2 := ^n[2] + carry - - return uint192{r0, r1, r2} -} - -type uint256 [4]uint64 - -func (n uint256) String() string { - if n[0]|n[1]|n[2]|n[3] == 0 { - return "0" - } - - var buf [78]byte - - i := 78 - for n[0]|n[1]|n[2]|n[3] != 0 { - var d uint64 - n, d = n.div10() - i-- - buf[i] = '0' + byte(d) - } - - return string(buf[i:]) -} - -func (n uint256) div10() (uint256, uint64) { - var r2, r3, rem uint64 - if n[3] < 10 { - r2, rem = bits.Div64(n[3], n[2], 10) - } else { - r3, rem = bits.Div64(0, n[3], 10) - r2, rem = bits.Div64(rem, n[2], 10) - } - - r1, rem := bits.Div64(rem, n[1], 10) - r0, rem := bits.Div64(rem, n[0], 10) - - return uint256{r0, r1, r2, r3}, rem -} - -func (n uint256) div10000() (uint256, uint64) { - var r2, r3, rem uint64 - if n[3] < 10_000 { - r2, rem = bits.Div64(n[3], n[2], 10_000) - } else { - r3, rem = bits.Div64(0, n[3], 10_000) - r2, rem = bits.Div64(rem, n[2], 10_000) - } - - r1, rem := bits.Div64(rem, n[1], 10_000) - r0, rem := bits.Div64(rem, n[0], 10_000) - - return uint256{r0, r1, r2, r3}, rem -} - -func (n uint256) div1e8() (uint256, uint64) { - var r2, r3, rem uint64 - if n[3] < 100_000_000 { - r2, rem = bits.Div64(n[3], n[2], 100_000_000) - } else { - r3, rem = bits.Div64(0, n[3], 100_000_000) - r2, rem = bits.Div64(rem, n[2], 100_000_000) - } - - r1, rem := bits.Div64(rem, n[1], 100_000_000) - r0, rem := bits.Div64(rem, n[0], 100_000_000) - - return uint256{r0, r1, r2, r3}, rem -} - -func (n uint256) div1e19() (uint256, uint64) { - var r2, r3, rem uint64 - if n[3] < 10_000_000_000_000_000_000 { - r2, rem = bits.Div64(n[3], n[2], 10_000_000_000_000_000_000) - } else { - r3, rem = bits.Div64(0, n[3], 10_000_000_000_000_000_000) - r2, rem = bits.Div64(rem, n[2], 10_000_000_000_000_000_000) - } - - r1, rem := bits.Div64(rem, n[1], 10_000_000_000_000_000_000) - r0, rem := bits.Div64(rem, n[0], 10_000_000_000_000_000_000) - - return uint256{r0, r1, r2, r3}, rem -} - -func (n uint256) lsh(o uint) uint256 { - var r0, r1, r2, r3 uint64 - if o > 192 { - r3 = n[0] << (o - 192) - } else if o > 128 { - r2 = n[0] << (o - 128) - r3 = n[1]<<(o-128) | n[0]>>(192-o) - } else if o > 64 { - r1 = n[0] << (o - 64) - r2 = n[1]<<(o-64) | n[0]>>(128-o) - r3 = n[2]<<(o-64) | n[1]>>(128-o) - } else { - r0 = n[0] << o - r1 = n[1]<>(64-o) - r2 = n[2]<>(64-o) - r3 = n[3]<>(64-o) - } - - return uint256{r0, r1, r2, r3} -} - -func (n uint256) mul64(o uint64) uint256 { - s1, r0 := bits.Mul64(n[0], o) - t2, t1 := bits.Mul64(n[1], o) - u3, u2 := bits.Mul64(n[2], o) - v3 := n[3] * o - - r1, carry := bits.Add64(s1, t1, 0) - r2, carry := bits.Add64(t2, u2, carry) - r3, _ := bits.Add64(u3, v3, carry) - - return uint256{r0, r1, r2, r3} -} - -func (n uint256) rsh(o uint) uint256 { - var r0, r1, r2, r3 uint64 - if o > 192 { - r0 = n[3] >> (o - 192) - } else if o > 128 { - r0 = n[2]>>(o-128) | n[3]<<(192-o) - r1 = n[3] >> (o - 128) - } else if o > 64 { - r0 = n[1]>>(o-64) | n[2]<<(128-o) - r1 = n[2]>>(o-64) | n[3]<<(128-o) - r2 = n[3] >> (o - 64) - } else { - r0 = n[0]>>o | n[1]<<(64-o) - r1 = n[1]>>o | n[2]<<(64-o) - r2 = n[2]>>o | n[3]<<(64-o) - r3 = n[3] >> o - } - - return uint256{r0, r1, r2, r3} -} - -type uint384 [6]uint64 - -func (n uint384) String() string { - if n[0]|n[1]|n[2]|n[3]|n[4]|n[5] == 0 { - return "0" - } - - var buf [116]byte - - i := 116 - for n[0]|n[1]|n[2]|n[3]|n[4]|n[5] != 0 { - var d uint64 - n, d = n.div10() - i-- - buf[i] = '0' + byte(d) - } - - return string(buf[i:]) -} - -func (n uint384) div10() (uint384, uint64) { - var r5, r4, rem uint64 - if n[5] < 10 { - r4, rem = bits.Div64(n[5], n[4], 10) - } else { - r5, rem = bits.Div64(0, n[5], 10) - r4, rem = bits.Div64(rem, n[4], 10) - } - - r3, rem := bits.Div64(rem, n[3], 10) - r2, rem := bits.Div64(rem, n[2], 10) - r1, rem := bits.Div64(rem, n[1], 10) - r0, rem := bits.Div64(rem, n[0], 10) - - return uint384{r0, r1, r2, r3, r4, r5}, rem -} - -func (n uint384) div1e19() (uint384, uint64) { - var r5, r4, rem uint64 - if n[5] < 10_000_000_000_000_000_000 { - r4, rem = bits.Div64(n[5], n[4], 10_000_000_000_000_000_000) - } else { - r5, rem = bits.Div64(0, n[5], 10_000_000_000_000_000_000) - r4, rem = bits.Div64(rem, n[4], 10_000_000_000_000_000_000) - } - - r3, rem := bits.Div64(rem, n[3], 10_000_000_000_000_000_000) - r2, rem := bits.Div64(rem, n[2], 10_000_000_000_000_000_000) - r1, rem := bits.Div64(rem, n[1], 10_000_000_000_000_000_000) - r0, rem := bits.Div64(rem, n[0], 10_000_000_000_000_000_000) - - return uint384{r0, r1, r2, r3, r4, r5}, rem -} diff --git a/vendor/github.com/woodsbury/decimal128/json.go b/vendor/github.com/woodsbury/decimal128/json.go deleted file mode 100644 index 6cb9969..0000000 --- a/vendor/github.com/woodsbury/decimal128/json.go +++ /dev/null @@ -1,104 +0,0 @@ -package decimal128 - -import ( - "encoding/json" - "reflect" -) - -// MarshalJSON implements the [encoding/json.Marshaler] interface. -func (d Decimal) MarshalJSON() ([]byte, error) { - if d.isSpecial() { - return nil, &json.UnsupportedValueError{ - Value: reflect.ValueOf(d), - Str: d.String(), - } - } - - var digs digits - d.digits(&digs) - - prec := 0 - if digs.ndig != 0 { - prec = digs.ndig - 1 - } - - exp := digs.exp + prec - - if exp < -6 || exp >= 20 { - return digs.fmtE(nil, prec, 0, false, false, false, false, false, false, 'e'), nil - } - - prec = 0 - if digs.exp < 0 { - prec = -digs.exp - } - - return digs.fmtF(nil, prec, 0, false, false, false, false, false), nil -} - -// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. -func (d *Decimal) UnmarshalJSON(data []byte) error { - if string(data) == "null" { - return nil - } - - l := len(data) - - if l == 0 { - return nil - } - - neg := false - - i := 0 - if data[0] == '+' { - i = 1 - } else if data[0] == '-' { - neg = true - i = 1 - } - - tmp, err := parseNumber(data[i:], neg, false) - if err != nil { - switch err := err.(type) { - case parseNumberRangeError: - return &json.UnmarshalTypeError{ - Value: "number " + string(data), - Type: reflect.TypeOf(Decimal{}), - } - case parseNumberSyntaxError: - switch data[0] { - case '[': - return &json.UnmarshalTypeError{ - Value: "array", - Type: reflect.TypeOf(Decimal{}), - } - case '{': - return &json.UnmarshalTypeError{ - Value: "object", - Type: reflect.TypeOf(Decimal{}), - } - case 'f', 't': - return &json.UnmarshalTypeError{ - Value: "bool", - Type: reflect.TypeOf(Decimal{}), - } - case '"': - return &json.UnmarshalTypeError{ - Value: "string", - Type: reflect.TypeOf(Decimal{}), - } - default: - return &json.UnmarshalTypeError{ - Value: "number " + string(data), - Type: reflect.TypeOf(Decimal{}), - } - } - default: - return err - } - } - - *d = tmp - return nil -} diff --git a/vendor/github.com/woodsbury/decimal128/payload.go b/vendor/github.com/woodsbury/decimal128/payload.go deleted file mode 100644 index 8892d2d..0000000 --- a/vendor/github.com/woodsbury/decimal128/payload.go +++ /dev/null @@ -1,125 +0,0 @@ -package decimal128 - -import "fmt" - -const ( - payloadOpCompose Payload = iota + 1 - payloadOpFromFloat32 - payloadOpFromFloat64 - payloadOpMustParse - payloadOpNaN - payloadOpParse - payloadOpScan - payloadOpUnmarshalText - - payloadOpAdd - payloadOpLog - payloadOpLog10 - payloadOpLog1p - payloadOpLog2 - payloadOpMul - payloadOpPow - payloadOpQuo - payloadOpQuoRem - payloadOpSqrt - payloadOpSub -) - -const ( - payloadValPosZero Payload = iota + 1 - payloadValNegZero - payloadValPosFinite - payloadValNegFinite - payloadValPosInfinite - payloadValNegInfinite -) - -// Payload returns the first 64 bits of the payload of a NaN. If the NaN was -// generated by an operation in this package, the contents of the payload -// provides information about what kind of operation was being performed that -// lead to the NaN being generated. Payload panics if d is not a NaN. -func (d Decimal) Payload() Payload { - if !d.IsNaN() { - panic("Decimal(!NaN).Payload()") - } - - return Payload(d.lo) -} - -// Payload represents the payload value of a NaN decimal. This value can -// contain additional information about the operation that caused the value to -// be set to NaN. -type Payload uint64 - -// String returns a string representation of the payload. -func (p Payload) String() string { - if p == 0 { - return "Payload(0)" - } - - if p > 0x00ff_ffff { - return fmt.Sprintf("Payload(%d)", uint64(p)) - } - - switch p & 0xff { - case payloadOpCompose: - return "Compose()" - case payloadOpFromFloat32: - return "FromFloat32()" - case payloadOpFromFloat64: - return "FromFloat64()" - case payloadOpMustParse: - return "MustParse()" - case payloadOpNaN: - return "NaN()" - case payloadOpParse: - return "Parse()" - case payloadOpScan: - return "Scan()" - case payloadOpUnmarshalText: - return "UnmarshalText()" - case payloadOpAdd: - return "Add(" + p.argString(8) + ", " + p.argString(16) + ")" - case payloadOpLog: - return "Log(" + p.argString(8) + ")" - case payloadOpLog10: - return "Log10(" + p.argString(8) + ")" - case payloadOpLog1p: - return "Log1p(" + p.argString(8) + ")" - case payloadOpLog2: - return "Log2(" + p.argString(8) + ")" - case payloadOpMul: - return "Mul(" + p.argString(8) + ", " + p.argString(16) + ")" - case payloadOpPow: - return "Pow(" + p.argString(8) + ", " + p.argString(16) + ")" - case payloadOpQuo: - return "Quo(" + p.argString(8) + ", " + p.argString(16) + ")" - case payloadOpQuoRem: - return "QuoRem(" + p.argString(8) + ", " + p.argString(16) + ")" - case payloadOpSqrt: - return "Sqrt(" + p.argString(8) + ")" - case payloadOpSub: - return "Sub(" + p.argString(8) + ", " + p.argString(16) + ")" - default: - return fmt.Sprintf("Payload(%d)", uint64(p)) - } -} - -func (p Payload) argString(offset int) string { - switch p >> offset & 0xff { - case payloadValPosZero: - return "Zero" - case payloadValNegZero: - return "-Zero" - case payloadValPosFinite: - return "Finite" - case payloadValNegFinite: - return "-Finite" - case payloadValPosInfinite: - return "Infinite" - case payloadValNegInfinite: - return "-Infinite" - default: - return "Unknown" - } -} diff --git a/vendor/github.com/woodsbury/decimal128/rounding.go b/vendor/github.com/woodsbury/decimal128/rounding.go deleted file mode 100644 index ac47f40..0000000 --- a/vendor/github.com/woodsbury/decimal128/rounding.go +++ /dev/null @@ -1,747 +0,0 @@ -package decimal128 - -import "fmt" - -// Ceil returns the least integer value greater than or equal to d. -// -// Ceil is equivalent to: -// -// d.Ceil(0) -func Ceil(d Decimal) Decimal { - return d.Ceil(0) -} - -// Floor returns the greatest integer value less than or equal to d. -// -// Floor is equivalent to: -// -// d.Floor(0) -func Floor(d Decimal) Decimal { - return d.Floor(0) -} - -// Round returns the nearest integer, rounding half away from zero. -// -// Round is equivalent to: -// -// d.Round(0, decimal128.ToNearestAway) -func Round(d Decimal) Decimal { - return d.Round(0, ToNearestAway) -} - -// Trunc returns the integer value of d. -// -// Trunc is equivalent to: -// -// d.Round(0, decimal128.ToZero) -func Trunc(d Decimal) Decimal { - return d.Round(0, ToZero) -} - -// Ceil returns the least Decimal value greater than or equal to d that has no -// digits after the specified number of decimal places. -// -// The value of dp affects how many digits after the decimal point the Decimal -// would have if it were printed in decimal notation (for example, by the '%f' -// verb in Format). It can be zero to return an integer, and can also be -// negative to round off digits before the decimal point. -// -// NaN and infinity values are left untouched. -func (d Decimal) Ceil(dp int) Decimal { - if d.isSpecial() { - return d - } - - sig, exp := d.decompose() - - if sig[0]|sig[1] == 0 { - return zero(d.Signbit()) - } - - dp = dp*-1 + exponentBias - iexp := int(exp) - - if iexp >= dp { - return d - } - - if iexp < dp-maxDigits { - if d.Signbit() { - return zero(d.Signbit()) - } - - return compose(false, uint128{1, 0}, int16(dp)) - } - - var trunc int8 - - for iexp < dp { - var rem uint64 - sig, rem = sig.div10() - - if rem != 0 { - trunc = 1 - } - - if sig[0]|sig[1] == 0 { - iexp = dp - break - } - - iexp++ - } - - neg := d.Signbit() - exp = int16(iexp) - - if !neg { - for trunc != 0 { - sig = sig.add64(1) - trunc = 0 - - if sig[1] > 0x0002_7fff_ffff_ffff { - var rem uint64 - sig, rem = sig.div10() - - if rem != 0 { - trunc = 1 - } - - exp++ - } - } - } - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Floor returns the greatest Decimal value less than or equal to d that has no -// digits after the specified number of decimal places. -// -// The value of dp affects how many digits after the decimal point the Decimal -// would have if it were printed in decimal notation (for example, by the '%f' -// verb in Format). It can be zero to return an integer, and can also be -// negative to round off digits before the decimal point. -// -// NaN and infinity values are left untouched. -func (d Decimal) Floor(dp int) Decimal { - if d.isSpecial() { - return d - } - - sig, exp := d.decompose() - - if sig[0]|sig[1] == 0 { - return zero(d.Signbit()) - } - - dp = dp*-1 + exponentBias - iexp := int(exp) - - if iexp >= dp { - return d - } - - if iexp < dp-maxDigits { - if !d.Signbit() { - return zero(d.Signbit()) - } - - return compose(true, uint128{1, 0}, int16(dp)) - } - - var trunc int8 - - for iexp < dp { - var rem uint64 - sig, rem = sig.div10() - - if rem != 0 { - trunc = 1 - } - - if sig[0]|sig[1] == 0 { - iexp = dp - break - } - - iexp++ - } - - neg := d.Signbit() - exp = int16(iexp) - - if neg { - for trunc != 0 { - sig = sig.add64(1) - trunc = 0 - - if sig[1] > 0x0002_7fff_ffff_ffff { - var rem uint64 - sig, rem = sig.div10() - - if rem != 0 { - trunc = 1 - } - - exp++ - } - } - } - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// Round rounds (or quantises) a Decimal value to the specified number of -// decimal places using the rounding mode provided. -// -// The value of dp affects how many digits after the decimal point the Decimal -// would have if it were printed in decimal notation (for example, by the '%f' -// verb in Format). It can be zero to round off all digits after the decimal -// point and return an integer, and can also be negative to round off digits -// before the decimal point. -// -// NaN and infinity values are left untouched. -func (d Decimal) Round(dp int, mode RoundingMode) Decimal { - if d.isSpecial() { - return d - } - - sig, exp := d.decompose() - - if sig[0]|sig[1] == 0 { - return zero(d.Signbit()) - } - - dp = dp*-1 + exponentBias - iexp := int(exp) - - if iexp >= dp { - return d - } - - if iexp < dp-maxDigits { - return zero(d.Signbit()) - } - - var trunc int8 - var digit uint64 - - for iexp < dp { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - - if sig[0]|sig[1]|digit == 0 { - return zero(d.Signbit()) - } - - iexp++ - } - - neg := d.Signbit() - sig, exp = mode.round(false, neg, sig, int16(iexp), trunc, digit) - - if exp > maxBiasedExponent { - return inf(neg) - } - - return compose(neg, sig, exp) -} - -// RoundingMode determines how a Decimal value is rounded when the result of an -// operation is greater than the format can hold. -type RoundingMode uint8 - -const ( - ToNearestEven RoundingMode = iota // == IEEE 754 roundTiesToEven - ToNearestAway // == IEEE 754 roundTiesToAway - ToZero // == IEEE 754 roundTowardZero - AwayFromZero // no IEEE 754 equivalent - ToNegativeInf // == IEEE 754 roundTowardNegative - ToPositiveInf // == IEEE 754 roundTowardPositive -) - -// String returns a string representation of the rounding mode. -func (rm RoundingMode) String() string { - switch rm { - case ToNearestEven: - return "ToNearestEven" - case ToNearestAway: - return "ToNearestAway" - case ToZero: - return "ToZero" - case AwayFromZero: - return "AwayFromZero" - case ToNegativeInf: - return "ToNegativeInf" - case ToPositiveInf: - return "ToPositiveInf" - default: - return fmt.Sprintf("RoundingMode(%d)", uint8(rm)) - } -} - -func (rm RoundingMode) reduce256(neg bool, sig256 uint256, exp int16, trunc int8) (uint128, int16) { - for sig256[3] > 0 { - var rem uint64 - sig256, rem = sig256.div1e19() - exp += 19 - - if rem != 0 { - trunc = 1 - } - } - - sig192 := uint192{sig256[0], sig256[1], sig256[2]} - - if sig192[2] > 10000 { - var rem uint64 - sig192, rem = sig192.div1e8() - exp += 8 - - if rem != 0 { - trunc = 1 - } - } - - for sig192[2] > 0 { - var rem uint64 - sig192, rem = sig192.div10000() - exp += 4 - - if rem != 0 { - trunc = 1 - } - } - - sig := uint128{sig192[0], sig192[1]} - - var digit uint64 - - if sig[1] > 0x09c4_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div10000() - exp += 4 - - if rem != 0 { - digit = rem / 1000 - - if rem%1000 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x00fa_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div1000() - exp += 3 - - if rem != 0 { - digit = rem / 100 - - if rem%100 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x0019_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div100() - exp += 2 - - if rem != 0 { - digit = rem / 10 - - if rem%10 != 0 { - trunc = 1 - } - } - } - - for sig[1] > 0x0002_7fff_ffff_ffff { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - exp++ - } - - for exp < minBiasedExponent { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - - if sig[0]|sig[1]|digit == 0 { - trunc = 0 - digit = 0 - exp = 0 - break - } - - exp++ - } - - for exp > maxBiasedExponent && sig[1] < 0x0002_7fff_ffff_ffff { - tmp := sig.mul64(10) - - if tmp[1] <= 0x0002_7fff_ffff_ffff { - sig = tmp - exp-- - } else { - break - } - } - - return rm.round(true, neg, sig, exp, trunc, digit) -} - -func (rm RoundingMode) reduce192(neg bool, sig192 uint192, exp int16, trunc int8) (uint128, int16) { - if sig192[2] > 10000 { - var rem uint64 - sig192, rem = sig192.div1e8() - exp += 8 - - if rem != 0 { - trunc = 1 - } - } - - for sig192[2] > 0 { - var rem uint64 - sig192, rem = sig192.div10000() - exp += 4 - - if rem != 0 { - trunc = 1 - } - } - - sig := uint128{sig192[0], sig192[1]} - - var digit uint64 - - if sig[1] > 0x09c4_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div10000() - exp += 4 - - if rem != 0 { - digit = rem / 1000 - - if rem%1000 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x00fa_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div1000() - exp += 3 - - if rem != 0 { - digit = rem / 100 - - if rem%100 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x0019_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div100() - exp += 2 - - if rem != 0 { - digit = rem / 10 - - if rem%10 != 0 { - trunc = 1 - } - } - } - - for sig[1] > 0x0002_7fff_ffff_ffff { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - exp++ - } - - for exp < minBiasedExponent { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - - if sig[0]|sig[1]|digit == 0 { - trunc = 0 - digit = 0 - exp = 0 - break - } - - exp++ - } - - for exp > maxBiasedExponent && sig[1] < 0x0002_7fff_ffff_ffff { - tmp := sig.mul64(10) - - if tmp[1] <= 0x0002_7fff_ffff_ffff { - sig = tmp - exp-- - } else { - break - } - } - - return rm.round(true, neg, sig, exp, trunc, digit) -} - -func (rm RoundingMode) reduce128(neg bool, sig uint128, exp int16, trunc int8) (uint128, int16) { - var digit uint64 - - if sig[1] > 0x09c4_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div10000() - exp += 4 - - if rem != 0 { - digit = rem / 1000 - - if rem%1000 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x00fa_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div1000() - exp += 3 - - if rem != 0 { - digit = rem / 100 - - if rem%100 != 0 { - trunc = 1 - } - } - } else if sig[1] > 0x0019_0000_0000_0000 { - var rem uint64 - sig, rem = sig.div100() - exp += 2 - - if rem != 0 { - digit = rem / 10 - - if rem%10 != 0 { - trunc = 1 - } - } - } - - for sig[1] > 0x0002_7fff_ffff_ffff { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - exp++ - } - - for exp < minBiasedExponent { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - - if sig[0]|sig[1]|digit == 0 { - trunc = 0 - digit = 0 - exp = 0 - break - } - - exp++ - } - - for exp > maxBiasedExponent && sig[1] < 0x0002_7fff_ffff_ffff { - tmp := sig.mul64(10) - - if tmp[1] <= 0x0002_7fff_ffff_ffff { - sig = tmp - exp-- - } else { - break - } - } - - return rm.round(true, neg, sig, exp, trunc, digit) -} - -func (rm RoundingMode) reduce64(neg bool, sig64 uint64, exp int16) (uint128, int16) { - var trunc int8 - var digit uint64 - - for exp < minBiasedExponent { - if digit != 0 { - trunc = 1 - } - - digit = sig64 % 10 - sig64 = sig64 / 10 - - if sig64|digit == 0 { - trunc = 0 - digit = 0 - exp = 0 - break - } - - exp++ - } - - sig := uint128{sig64, 0} - - for exp > maxBiasedExponent && sig[1] < 0x0002_7fff_ffff_ffff { - tmp := sig.mul64(10) - - if tmp[1] <= 0x0002_7fff_ffff_ffff { - sig = tmp - exp-- - } else { - break - } - } - - return rm.round(true, neg, sig, exp, trunc, digit) -} - -func (rm RoundingMode) round(shift, neg bool, sig uint128, exp int16, trunc int8, digit uint64) (uint128, int16) { - for { - var adjust int - switch rm { - case ToNearestEven: - if trunc == 1 { - if digit >= 5 { - adjust = 1 - } - } else if trunc == -1 { - if digit > 5 { - adjust = 1 - } - } else { - if digit > 5 { - adjust = 1 - } else if digit == 5 { - if sig[0]%2 != 0 { - adjust = 1 - } - } - } - case ToNearestAway: - if digit >= 5 { - adjust = 1 - } - case ToZero: - if trunc == -1 && digit == 0 { - adjust = -1 - } - case AwayFromZero: - if trunc == 1 || digit != 0 { - adjust = 1 - } - case ToPositiveInf: - if neg { - if trunc == -1 && digit == 0 { - adjust = -1 - } - } else if trunc == 1 || digit != 0 { - adjust = 1 - } - case ToNegativeInf: - if neg { - if trunc == 1 || digit != 0 { - adjust = 1 - } - } else if trunc == -1 && digit == 0 { - adjust = -1 - } - } - - if adjust != 0 { - var tsig uint128 - if adjust == 1 { - if shift { - if sig[0]|sig[1] != 0 { - if exp >= minBiasedExponent+19 && sig[1] == 0 { - sig = sig.mul64(10_000_000_000_000_000_000) - exp -= 19 - } - - for exp > minBiasedExponent && sig[1] < 0x0002_7fff_ffff_ffff/10 { - sig = sig.mul64(10) - exp-- - } - } else { - exp = minBiasedExponent - } - - shift = false - } - - tsig = sig.add64(1) - } else { - if shift { - if sig[0]|sig[1] != 0 { - if exp >= minBiasedExponent+19 && sig[1] == 0 { - sig = sig.mul64(10_000_000_000_000_000_000) - exp -= 19 - } - - for exp > minBiasedExponent && sig[1] <= 0x0002_7fff_ffff_ffff/10 { - sig = sig.mul64(10) - exp-- - } - } else { - exp = minBiasedExponent - } - - shift = false - } - - tsig = sig.sub64(1) - } - - if tsig[1] > 0x0002_7fff_ffff_ffff { - if digit != 0 { - trunc = 1 - } - - sig, digit = sig.div10() - exp++ - continue - } - - sig = tsig - } - - return sig, exp - } -} - -// DefaultRoundingMode is the rounding mode used by any methods where an -// alternate rounding mode isn't provided. -var DefaultRoundingMode RoundingMode = ToNearestEven diff --git a/vendor/github.com/woodsbury/decimal128/scan.go b/vendor/github.com/woodsbury/decimal128/scan.go deleted file mode 100644 index 8fb7910..0000000 --- a/vendor/github.com/woodsbury/decimal128/scan.go +++ /dev/null @@ -1,475 +0,0 @@ -package decimal128 - -import ( - "errors" - "fmt" - "io" - "strconv" -) - -// MustParse is like [Parse] but panics if the provided string cannot be parsed, -// instead of returning an error. -func MustParse(s string) Decimal { - d, err := parse(s, payloadOpMustParse) - if err != nil { - panic("decimal128.MustParse(" + strconv.Quote(s) + "): invalid syntax") - } - - return d -} - -// Parse parses a Decimal value from the string provided. Parse accepts decimal -// floating point syntax. An underscore character '_' may appear between digits -// as a separator. Parse also recognises the string "NaN", and the (possibly -// signed) strings "Inf" and "Infinity", as their respective special floating -// point values. It ignores case when matching. -// -// If s is not syntactically well-formed, Parse returns an error that can be -// compared to [strconv.ErrSyntax] via [errors.Is]. -// -// If the value is too precise to fit in a Decimal the result is rounded using -// the [DefaultRoundingMode]. If the value is greater than the largest possible -// Decimal value, Parse returns ±Inf and an error that can be compared to -// [strconv.ErrRange] via [errors.Is]. -func Parse(s string) (Decimal, error) { - return parse(s, payloadOpParse) -} - -// Scan implements the [fmt.Scanner] interface. It supports the verbs 'e', 'E', -// 'f', 'F', 'g', 'G', and 'v'. -func (d *Decimal) Scan(f fmt.ScanState, verb rune) error { - switch verb { - case 'e', 'E', 'f', 'F', 'g', 'G', 'v': - default: - return errors.New("bad verb '%" + string(verb) + "' for Decimal") - } - - f.SkipSpace() - r, _, err := f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - neg := false - - if r == '-' { - neg = true - } else if r != '+' { - f.UnreadRune() - } - - r, _, err = f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - if r == 'I' || r == 'i' { - r2, _, err := f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - if r2 != 'N' && r2 != 'n' { - return &parseSyntaxError{s: string([]rune{r, r2})} - } - - r3, _, err := f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - if r3 != 'F' && r3 != 'f' { - return &parseSyntaxError{s: string([]rune{r, r2, r3})} - } - - *d = inf(neg) - return nil - } - - if r == 'N' || r == 'n' { - r2, _, err := f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - if r2 != 'A' && r2 != 'a' { - return &parseSyntaxError{s: string([]rune{r, r2})} - } - - r3, _, err := f.ReadRune() - if err != nil { - if errors.Is(err, io.EOF) { - return io.ErrUnexpectedEOF - } - - return err - } - - if r3 != 'N' && r3 != 'n' { - return &parseSyntaxError{s: string([]rune{r, r2, r3})} - } - - *d = nan(payloadOpScan, 0, 0) - return nil - } - - f.UnreadRune() - - tok, err := f.Token(false, func(r rune) bool { - switch { - case r >= '0' && r <= '9': - return true - case r == '.': - return true - case r == 'E' || r == 'e': - return true - case r == '-': - return true - case r == '_': - return true - case r == '+': - return true - default: - return false - } - }) - - if err != nil { - return err - } - - tmp, err := parseNumber(tok, neg, true) - if err != nil { - switch err := err.(type) { - case parseNumberRangeError: - return &parseRangeError{string(tok)} - case parseNumberSyntaxError: - return &parseSyntaxError{string(tok)} - default: - return err - } - } - - *d = tmp - return nil -} - -// UnmarshalText implements the [encoding.TextUnmarshaler] interface. -func (d *Decimal) UnmarshalText(data []byte) error { - tmp, err := parse(data, payloadOpUnmarshalText) - if err != nil { - return err - } - - *d = tmp - return nil -} - -func parse[D []byte | string](d D, op Payload) (Decimal, error) { - if len(d) == 0 { - return Decimal{}, &parseSyntaxError{} - } - - s := d - neg := false - - if d[0] == '+' { - d = d[1:] - } else if d[0] == '-' { - neg = true - d = d[1:] - } - - l := len(d) - - if l == 0 { - return Decimal{}, &parseSyntaxError{string(s)} - } else if l == 3 { - if (d[0] == 'I' || d[0] == 'i') && (d[1] == 'N' || d[1] == 'n') && (d[2] == 'F' || d[2] == 'f') { - return inf(neg), nil - } - - if (d[0] == 'N' || d[0] == 'n') && (d[1] == 'A' || d[1] == 'a') && (d[2] == 'N' || d[2] == 'n') { - return nan(op, 0, 0), nil - } - } else if l == 8 { - if (d[0] == 'I' || d[0] == 'i') && (d[1] == 'N' || d[1] == 'n') && (d[2] == 'F' || d[2] == 'f') && (d[3] == 'I' || d[3] == 'i') && (d[4] == 'N' || d[4] == 'n') && (d[5] == 'I' || d[5] == 'i') && (d[6] == 'T' || d[6] == 't') && (d[7] == 'Y' || d[7] == 'y') { - return inf(neg), nil - } - } - - v, err := parseNumber(d, neg, true) - if err != nil { - switch err := err.(type) { - case parseNumberRangeError: - return v, &parseRangeError{string(s)} - case parseNumberSyntaxError: - return v, &parseSyntaxError{string(s)} - default: - return v, err - } - } - - return v, nil -} - -func parseNumber[D []byte | string](d D, neg, sepallowed bool) (Decimal, error) { - var sig64 uint64 - var nfrac int16 - var trunc int8 - caneof := false - cansep := false - cansgn := false - eneg := false - sawdig := false - sawdot := false - sawexp := false - - l := len(d) - i := 0 - for ; !sawexp && sig64 <= 0x18ff_ffff_ffff_ffff && i < l; i++ { - switch c := d[i]; true { - case c >= '0' && c <= '9': - caneof = true - cansep = true - cansgn = false - sawdig = true - - sig64 = sig64*10 + uint64(c-'0') - - if sawdot { - nfrac++ - } - case c == '.': - if sawdot { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = true - cansep = false - cansgn = false - sawdot = true - case c == 'E' || c == 'e': - if !sawdig { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = true - sawexp = true - case c == '_': - if !sepallowed || !cansep { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = false - default: - return Decimal{}, parseNumberSyntaxError{} - } - } - - sig := uint128{sig64, 0} - var exp int16 - maxexp := false - - for ; i < l; i++ { - switch c := d[i]; true { - case c >= '0' && c <= '9': - caneof = true - cansep = true - cansgn = false - sawdig = true - - if sawexp { - if exp > exponentBias/10+1 { - maxexp = true - } - - exp *= 10 - exp += int16(c - '0') - } else { - if sig[1] <= 0x18ff_ffff_ffff_ffff { - if sig[1] <= 0x027f_ffff_ffff_ffff && i < l-1 { - c2 := d[i+1] - if c2 >= '0' && c2 <= '9' { - sig = sig.mul64(100) - sig = sig.add64(uint64(c-'0')*10 + uint64(c2-'0')) - - if sawdot { - nfrac += 2 - } - - i++ - continue - } - } - - sig = sig.mul64(10) - sig = sig.add64(uint64(c - '0')) - - if sawdot { - nfrac++ - } - } else { - if c != '0' { - trunc = 1 - } - - if !sawdot { - if exp < exponentBias+39 { - nfrac-- - } - } - } - } - case c == '.': - if sawdot || sawexp { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = true - cansep = false - cansgn = false - sawdot = true - case c == 'E' || c == 'e': - if !sawdig || sawexp { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = true - sawexp = true - case c == '-': - if !cansgn { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = false - eneg = true - case c == '_': - if !cansep { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = false - case c == '+': - if !cansgn { - return Decimal{}, parseNumberSyntaxError{} - } - - caneof = false - cansep = false - cansgn = false - default: - return Decimal{}, parseNumberSyntaxError{} - } - } - - if !caneof { - return Decimal{}, parseNumberSyntaxError{} - } - - if sig[0]|sig[1] == 0 { - return zero(neg), nil - } - - // If the exponent value is larger than the maximum supported exponent, - // there are two cases where the value is still valid: - // - the exponent is negative, where the logical value rounds to 0 - // - the significand is zero, where the logical value is 0 - // - // Otherwise, return a range error. - if maxexp { - if eneg { - return zero(neg), nil - } - - return inf(neg), parseNumberRangeError{} - } - - if eneg { - exp *= -1 - } - - exp -= nfrac - - if exp > maxUnbiasedExponent+39 { - return inf(neg), parseNumberRangeError{} - } - - if exp < minUnbiasedExponent-39 { - return zero(neg), nil - } - - sig, exp = DefaultRoundingMode.reduce128(neg, sig, exp+exponentBias, trunc) - - if exp > maxBiasedExponent { - return inf(neg), parseNumberRangeError{} - } - - return compose(neg, sig, exp), nil -} - -type parseNumberRangeError struct{} - -func (err parseNumberRangeError) Error() string { - return "value out of range" -} - -type parseNumberSyntaxError struct{} - -func (err parseNumberSyntaxError) Error() string { - return "invalid syntax" -} - -type parseRangeError struct { - s string -} - -func (err *parseRangeError) Error() string { - return "parsing " + strconv.Quote(err.s) + ": value out of range" -} - -func (err *parseRangeError) Is(target error) bool { - return target == strconv.ErrRange -} - -type parseSyntaxError struct { - s string -} - -func (err *parseSyntaxError) Error() string { - return "parsing " + strconv.Quote(err.s) + ": invalid syntax" -} - -func (err *parseSyntaxError) Is(target error) bool { - return target == strconv.ErrSyntax -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 40d4225..0c99a3a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,19 +4,19 @@ github.com/clipperhouse/uax29/v2/graphemes # github.com/davecgh/go-spew v1.1.1 ## explicit github.com/davecgh/go-spew/spew -# github.com/getkin/kin-openapi v0.139.0 +# github.com/getkin/kin-openapi v0.140.0 ## explicit; go 1.25 github.com/getkin/kin-openapi/openapi3 # github.com/go-chi/chi/v5 v5.3.0 ## explicit; go 1.23 github.com/go-chi/chi/v5 github.com/go-chi/chi/v5/middleware -# github.com/go-openapi/jsonpointer v0.21.0 -## explicit; go 1.20 +# github.com/go-openapi/jsonpointer v0.22.5 +## explicit; go 1.24.0 github.com/go-openapi/jsonpointer -# github.com/go-openapi/swag v0.23.0 -## explicit; go 1.20 -github.com/go-openapi/swag +# github.com/go-openapi/swag/jsonname v0.25.5 +## explicit; go 1.24.0 +github.com/go-openapi/swag/jsonname # github.com/go-viper/mapstructure/v2 v2.5.0 ## explicit; go 1.18 github.com/go-viper/mapstructure/v2 @@ -61,14 +61,8 @@ github.com/hashicorp/nomad/api/contexts ## explicit; go 1.18 github.com/jedib0t/go-pretty/v6/table github.com/jedib0t/go-pretty/v6/text -# github.com/josharian/intern v1.0.0 -## explicit; go 1.5 -github.com/josharian/intern -# github.com/mailru/easyjson v0.7.7 +# github.com/kr/pretty v0.3.1 ## explicit; go 1.12 -github.com/mailru/easyjson/buffer -github.com/mailru/easyjson/jlexer -github.com/mailru/easyjson/jwriter # github.com/mattn/go-colorable v0.1.14 ## explicit; go 1.18 github.com/mattn/go-colorable @@ -81,18 +75,12 @@ github.com/mattn/go-runewidth # github.com/mitchellh/go-homedir v1.1.0 ## explicit github.com/mitchellh/go-homedir -# github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 -## explicit -github.com/mohae/deepcopy # github.com/oasdiff/yaml v0.1.0 ## explicit; go 1.22.5 github.com/oasdiff/yaml # github.com/oasdiff/yaml3 v0.0.13 ## explicit; go 1.22.5 github.com/oasdiff/yaml3 -# github.com/perimeterx/marshmallow v1.1.5 -## explicit; go 1.17 -github.com/perimeterx/marshmallow # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib @@ -110,9 +98,6 @@ github.com/santhosh-tekuri/jsonschema/v6/kind ## explicit; go 1.17 github.com/stretchr/testify/assert github.com/stretchr/testify/assert/yaml -# github.com/woodsbury/decimal128 v1.3.0 -## explicit; go 1.21 -github.com/woodsbury/decimal128 # golang.org/x/sys v0.41.0 ## explicit; go 1.24.0 golang.org/x/sys/unix