diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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/README.md b/README.md new file mode 100644 index 0000000..520d8ff --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# ryu + +This is a Go implementation of [Ryu](https://github.com/ulfjack/ryu), a fast +algorithm for converting floating-point numbers to strings. + +TODO: more description. diff --git a/maketables.go b/maketables.go new file mode 100644 index 0000000..5fa6b88 --- /dev/null +++ b/maketables.go @@ -0,0 +1,118 @@ +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// 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. +// +// The code in this file is a Go translation of the Java code written by +// Ulf Adams which may be found at +// +// https://github.com/ulfjack/ryu/analysis/PrintFloatLookupTable.java +// +// That source code is licensed under Apache 2.0 and this code is derivative +// work thereof. + +// +build ignore + +// This program generates tables.go. + +package main + +import ( + "bytes" + "fmt" + "go/format" + "io/ioutil" + "log" + "math/big" +) + +var header = []byte(`// Code generated by running "go generate". DO NOT EDIT. + +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. +// +// The code in this file is part of a Go translation of the C code written by +// Ulf Adams which may be found at https://github.com/ulfjack/ryu. That source +// code is licensed under Apache 2.0 and this code is derivative work thereof. + +package ryu + +`) + +const ( + posTableSize = 47 + invTableSize = 31 + pow5NumBits = 61 // max 63 + pow5InvNumBits = 59 // max 63 +) + +func main() { + b := bytes.NewBuffer(header) + + fmt.Fprintf(b, "const pow5NumBits = %d\n", pow5NumBits) + fmt.Fprintln(b, "var pow5Split = [...]uint64{") + for i := 0; i < posTableSize; i++ { + pow5 := big.NewInt(5) + pow5.Exp(pow5, big.NewInt(int64(i)), nil) + shift := pow5.BitLen() - pow5NumBits + rsh(pow5, shift) + fmt.Fprintf(b, "%d,", pow5.Uint64()) + if i%4 == 3 { + fmt.Fprintln(b) + } + } + fmt.Fprintln(b, "\n}") + + fmt.Fprintf(b, "const pow5InvNumBits = %d\n", pow5InvNumBits) + fmt.Fprintln(b, "var pow5InvSplit = [...]uint64{") + for i := 0; i < invTableSize; i++ { + pow5 := big.NewInt(5) + pow5.Exp(pow5, big.NewInt(int64(i)), nil) + shift := pow5.BitLen() - 1 + pow5InvNumBits + pow5Inv := big.NewInt(1) + rsh(pow5Inv, -shift) + pow5Inv.Quo(pow5Inv, pow5) + pow5Inv.Add(pow5Inv, big.NewInt(1)) + fmt.Fprintf(b, "%d,", pow5Inv.Uint64()) + if i%4 == 3 { + fmt.Fprintln(b) + } + } + fmt.Fprintln(b, "\n}") + + text, err := format.Source(b.Bytes()) + if err != nil { + log.Fatal(err) + } + if err := ioutil.WriteFile("tables.go", text, 0644); err != nil { + log.Fatal(err) + } +} + +func rsh(x *big.Int, n int) { + if n < 0 { + x.Lsh(x, uint(-n)) + } else { + x.Rsh(x, uint(n)) + } +} diff --git a/ryu.go b/ryu.go new file mode 100644 index 0000000..a322d83 --- /dev/null +++ b/ryu.go @@ -0,0 +1,78 @@ +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. +// +// The code in this file is part of a Go translation of the C code written by +// Ulf Adams which may be found at https://github.com/ulfjack/ryu. That source +// code is licensed under Apache 2.0 and this code is derivative work thereof. + +package ryu + +import ( + "math" + "reflect" + "unsafe" +) + +//go:generate go run maketables.go + +// FormatFloat32 converts a 32-bit floating point number f to a string. +// It behaves like strconv.FormatFloat(float64(f), 'e', -1, 32). +func FormatFloat32(f float32) string { + b := make([]byte, 0, 16) + b = AppendFloat32(b, f) + + // Convert the output to a string without copying. + var s string + sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) + sh.Data = uintptr(unsafe.Pointer(&b[0])) + sh.Len = len(b) + return s +} + +// AppendFloat32 appends the string form of the 32-bit floating point number f, +// as generated by FormatFlot32, to b and returns the extended buffer. +func AppendFloat32(b []byte, f float32) []byte { + // Step 1: Decode the floating-point number. + // Unify normalized and subnormal cases. + u := math.Float32bits(f) + neg := u>>(mantBits32+expBits32) != 0 + mant := u & (uint32(1)<> mantBits32) & (uint32(1)< 1 { + bufLen++ // extra space for '.' + } + + // Print the decimal digits. + // FIXME: optimize + n := len(b) + b = append(b, make([]byte, bufLen)...) + for i := 0; i < outLen-1; i++ { + b[n+outLen-i] = '0' + byte(out%10) + out /= 10 + } + b[n] = '0' + byte(out%10) + + // Print the '.' if needed. + if outLen > 1 { + b[n+1] = '.' + } + + // Print the exponent. + b = append(b, 'e') + exp := d.e + int32(outLen) - 1 + if exp < 0 { + b = append(b, '-') + exp = -exp + } else { + // Unconditionally print a + here to match strconv's formatting. + b = append(b, '+') + } + // Always print two digits to match strconv's formatting. + d1 := exp % 10 + d0 := exp / 10 + b = append(b, '0'+byte(d0), '0'+byte(d1)) + + return b +} + +func float32ToDecimal(mant, exp uint32) dec32 { + var e2 int32 + var m2 uint32 + if exp == 0 { + // We subtract 2 so that the bounds computation has 2 + // additional bits. + e2 = 1 - bias32 - mantBits32 - 2 + m2 = mant + } else { + e2 = int32(exp) - bias32 - mantBits32 - 2 + m2 = uint32(1)<= 0 { + q := log10Pow2(e2) + e10 = int32(q) + k := pow5InvNumBits + pow5Bits(int32(q)) - 1 + i := -e2 + int32(q) + k + vr = mulPow5InvDivPow2(mv, q, i) + vp = mulPow5InvDivPow2(mp, q, i) + vm = mulPow5InvDivPow2(mm, q, i) + if q != 0 && (vp-1)/10 <= vm/10 { + // We need to know one removed digit even if we are not + // going to loop below. We could use q = X - 1 above, + // except that would require 33 bits for the result, and + // we've found that 32-bit arithmetic is faster even on + // 64-bit machines. + l := pow5InvNumBits + pow5Bits(int32(q-1)) - 1 + lastRemovedDigit = uint8(mulPow5InvDivPow2(mv, q-1, -e2+int32(q-1)+l) % 10) + } + if q <= 9 { + // The largest power of 5 that fits in 24 bits is 5^10, + // but q <= 9 seems to be safe as well. Only one of mp, + // mv, and mm can be a multiple of 5, if any. + switch { + case mv%5 == 0: + vrIsTrailingZeros = multipleOfPowerOf5(mv, q) + case acceptBounds: + vmIsTrailingZeros = multipleOfPowerOf5(mm, q) + default: + if multipleOfPowerOf5(mp, q) { + vp-- + } + } + } + } else { + q := log10Pow5(-e2) + e10 = int32(q) + e2 + i := -e2 - int32(q) + k := pow5Bits(i) - pow5NumBits + j := int32(q) - k + vr = mulPow5DivPow2(mv, uint32(i), j) + vp = mulPow5DivPow2(mp, uint32(i), j) + vm = mulPow5DivPow2(mm, uint32(i), j) + if q != 0 && (vp-1)/10 <= vm/10 { + j = int32(q) - 1 - (pow5Bits(i+1) - pow5NumBits) + lastRemovedDigit = uint8(mulPow5DivPow2(mv, uint32(i+1), j) % 10) + } + if q <= 1 { + // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at + // least q trailing 0 bits. mv = 4 * m2, so it always + // has at least two trailing 0 bits. + vrIsTrailingZeros = true + if acceptBounds { + // mm = mv - 1 - mmShift, so it has 1 trailing 0 bit + // iff mmShift == 1. + vmIsTrailingZeros = mmShift == 1 + } else { + // mp = mv + 2, so it always has at least one + // trailing 0 bit. + vp-- + } + } else if q < 31 { + vrIsTrailingZeros = multipleOfPowerOf2(mv, q-1) + } + } + + // Step 4: Find the shortest decimal representation + // in the interval of valid representations. + var removed int32 + var out uint32 + if vmIsTrailingZeros || vrIsTrailingZeros { + // General case, which happens rarely (~4.0%). + for vp/10 > vm/10 { + vmIsTrailingZeros = vmIsTrailingZeros && vm%10 == 0 + vrIsTrailingZeros = vrIsTrailingZeros && lastRemovedDigit == 0 + lastRemovedDigit = uint8(vr % 10) + vr /= 10 + vp /= 10 + vm /= 10 + removed++ + } + if vmIsTrailingZeros { + for vm%10 == 0 { + vrIsTrailingZeros = vrIsTrailingZeros && lastRemovedDigit == 0 + lastRemovedDigit = uint8(vr % 10) + vr /= 10 + vp /= 10 + vm /= 10 + removed++ + } + } + if vrIsTrailingZeros && lastRemovedDigit == 5 && vr%2 == 0 { + // Round even if the exact number is .....50..0. + lastRemovedDigit = 4 + } + out = vr + // We need to take vr + 1 if vr is outside bounds + // or we need to round up. + if (vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5 { + out++ + } + } else { + // Specialized for the common case (~96.0%). Percentages below + // are relative to this. Loop iterations below (approximately): + // 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01% + for vp/10 > vm/10 { + lastRemovedDigit = uint8(vr % 10) + vr /= 10 + vp /= 10 + vm /= 10 + removed++ + } + // We need to take vr + 1 if vr is outside bounds + // or we need to round up. + out = vr + if vr == vm || lastRemovedDigit >= 5 { + out++ + } + } + + return dec32{m: out, e: e10 + removed} +} diff --git a/ryu64.go b/ryu64.go new file mode 100644 index 0000000..6d65be5 --- /dev/null +++ b/ryu64.go @@ -0,0 +1,128 @@ +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. +// +// The code in this file is part of a Go translation of the C code written by +// Ulf Adams which may be found at https://github.com/ulfjack/ryu. That source +// code is licensed under Apache 2.0 and this code is derivative work thereof. + +package ryu + +import ( + "math" + "math/bits" +) + +const ( + mantBits64 = 52 + expBits64 = 11 + bias64 = 1023 +) + +func decimalLen32(u uint32) int { + // Function precondition: u is not a 10-digit number. + // (9 digits are sufficient for round-tripping.) + assert(u < 1000000000, "too big") + switch { + case u >= 100000000: + return 9 + case u >= 10000000: + return 8 + case u >= 1000000: + return 7 + case u >= 100000: + return 6 + case u >= 10000: + return 5 + case u >= 1000: + return 4 + case u >= 100: + return 3 + case u >= 10: + return 2 + default: + return 1 + } + +} + +// log10Pow2 returns floor(log_10(2^e)). +func log10Pow2(e int32) uint32 { + // The first value this approximation fails for is 2^1651 + // which is just greater than 10^297. + assert(e >= 0, "e >= 0") + assert(e <= 1650, "e <= 1650") + return (uint32(e) * 78913) >> 18 +} + +// log10Pow5 returns floor(log_10(5^e)). +func log10Pow5(e int32) uint32 { + // The first value this approximation fails for is 5^2621 + // which is just greater than 10^1832. + assert(e >= 0, "e >= 0") + assert(e <= 2620, "e <= 2620") + return (uint32(e) * 732923) >> 20 +} + +// pow5Bits returns ceil(log_2(5^e)), or else 1 if e==0. +func pow5Bits(e int32) int32 { + // This approximation works up to the point that the multiplication + // overflows at e = 3529. If the multiplication were done in 64 bits, + // it would fail at 5^4004 which is just greater than 2^9297. + assert(e >= 0, "e >= 0") + assert(e <= 3528, "e <= 3528") + return int32((uint32(e)*1217359)>>19 + 1) +} + +func mulShift(m uint32, factor uint64, shift int32) uint32 { + assert(shift > 32, "shift > 32") + + factorLo := uint32(factor) + factorHi := uint32(factor >> 32) + bits0 := uint64(m) * uint64(factorLo) + bits1 := uint64(m) * uint64(factorHi) + + sum := (bits0 >> 32) + bits1 + shiftedSum := sum >> uint(shift-32) + assert(shiftedSum <= math.MaxUint32, "shiftedSum <= math.MaxUint32") + return uint32(shiftedSum) +} + +func mulPow5InvDivPow2(m, q uint32, j int32) uint32 { + return mulShift(m, pow5InvSplit[q], j) +} + +func mulPow5DivPow2(m, i uint32, j int32) uint32 { + return mulShift(m, pow5Split[i], j) +} + +// FIXME: use bits.Div + +func pow5Factor(v uint32) uint32 { + for n := uint32(0); ; n++ { + q, r := v/5, v%5 + if r != 0 { + return n + } + v = q + } +} + +// multipleOfPowerOf5 reports whether v is divisible by 5^p. +func multipleOfPowerOf5(v, p uint32) bool { + return pow5Factor(v) >= p +} + +// multipleOfPowerOf5 reports whether v is divisible by 2^p. +func multipleOfPowerOf2(v, p uint32) bool { + return uint32(bits.TrailingZeros32(v)) >= p +} diff --git a/ryu_test.go b/ryu_test.go new file mode 100644 index 0000000..9034724 --- /dev/null +++ b/ryu_test.go @@ -0,0 +1,73 @@ +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. +// +// The code in this file is part of a Go translation of the C code written by +// Ulf Adams which may be found at https://github.com/ulfjack/ryu. That source +// code is licensed under Apache 2.0 and this code is derivative work thereof. + +package ryu + +import ( + "strconv" + "testing" +) + +func TestFormatFloat32(t *testing.T) { + for _, f := range []float32{ + 0, + 1, + 0.3, + 1000000, + -123.45, + } { + got := FormatFloat32(f) + want := strconv.FormatFloat(float64(f), 'e', -1, 32) + if got != want { + t.Errorf("FormatFloat32(%g): got %q; want %q", f, got, want) + } + } +} + +var benchCases32 = []float32{ + 0, + 1, + 0.3, + 1000000, + -123.45, +} + +var sink string + +func BenchmarkFormatFloat32(b *testing.B) { + for _, f := range benchCases32 { + b.Run(FormatFloat32(f), func(b *testing.B) { + var s string + for i := 0; i < b.N; i++ { + s = FormatFloat32(f) + } + sink = s + }) + } +} + +func BenchmarkStrconvFormatFloat32(b *testing.B) { + for _, f := range benchCases32 { + b.Run(FormatFloat32(f), func(b *testing.B) { + var s string + for i := 0; i < b.N; i++ { + s = strconv.FormatFloat(float64(f), 'e', -1, 32) + } + sink = s + }) + } +} diff --git a/tables.go b/tables.go new file mode 100644 index 0000000..e9ec408 --- /dev/null +++ b/tables.go @@ -0,0 +1,50 @@ +// Code generated by running "go generate". DO NOT EDIT. + +// Copyright 2018 Ulf Adams +// Modifications copyright 2019 Caleb Spare +// +// The contents of this file may be used under the terms of the Apache License, +// Version 2.0. +// +// (See accompanying file LICENSE or copy at +// http://www.apache.org/licenses/LICENSE-2.0) +// +// Unless required by applicable law or agreed to in writing, this software +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. +// +// The code in this file is part of a Go translation of the C code written by +// Ulf Adams which may be found at https://github.com/ulfjack/ryu. That source +// code is licensed under Apache 2.0 and this code is derivative work thereof. + +package ryu + +const pow5NumBits = 61 + +var pow5Split = [...]uint64{ + 1152921504606846976, 1441151880758558720, 1801439850948198400, 2251799813685248000, + 1407374883553280000, 1759218604441600000, 2199023255552000000, 1374389534720000000, + 1717986918400000000, 2147483648000000000, 1342177280000000000, 1677721600000000000, + 2097152000000000000, 1310720000000000000, 1638400000000000000, 2048000000000000000, + 1280000000000000000, 1600000000000000000, 2000000000000000000, 1250000000000000000, + 1562500000000000000, 1953125000000000000, 1220703125000000000, 1525878906250000000, + 1907348632812500000, 1192092895507812500, 1490116119384765625, 1862645149230957031, + 1164153218269348144, 1455191522836685180, 1818989403545856475, 2273736754432320594, + 1421085471520200371, 1776356839400250464, 2220446049250313080, 1387778780781445675, + 1734723475976807094, 2168404344971008868, 1355252715606880542, 1694065894508600678, + 2117582368135750847, 1323488980084844279, 1654361225106055349, 2067951531382569187, + 1292469707114105741, 1615587133892632177, 2019483917365790221, +} + +const pow5InvNumBits = 59 + +var pow5InvSplit = [...]uint64{ + 576460752303423489, 461168601842738791, 368934881474191033, 295147905179352826, + 472236648286964522, 377789318629571618, 302231454903657294, 483570327845851670, + 386856262276681336, 309485009821345069, 495176015714152110, 396140812571321688, + 316912650057057351, 507060240091291761, 405648192073033409, 324518553658426727, + 519229685853482763, 415383748682786211, 332306998946228969, 531691198313966350, + 425352958651173080, 340282366920938464, 544451787073501542, 435561429658801234, + 348449143727040987, 557518629963265579, 446014903970612463, 356811923176489971, + 570899077082383953, 456719261665907162, 365375409332725730, +}