Fix duplicate sign printing of complex and quaternion types

Negative zero wasn't being detected (so it would appear as `+-0`), and
`+Inf` was appearing as `++Inf` when imaginary.
This commit is contained in:
Feoramund
2024-06-03 19:49:38 -04:00
parent d2a9122176
commit eb93779f63

View File

@@ -2,6 +2,7 @@ package fmt
import "base:intrinsics"
import "base:runtime"
import "core:math"
import "core:math/bits"
import "core:mem"
import "core:io"
@@ -2968,6 +2969,21 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) {
fmt_bit_field(fi, v, verb, info, "")
}
}
// This proc helps keep some of the code around whether or not to print an
// intermediate plus sign in complexes and quaternions more readable.
@(private)
_cq_should_print_intermediate_plus :: proc "contextless" (fi: ^Info, f: f64) -> bool {
if !fi.plus && f >= 0 {
#partial switch math.classify(f) {
case .Neg_Zero, .Inf:
// These two classes print their own signs.
return false
case:
return true
}
}
return false
}
// Formats a complex number based on the given formatting verb
//
// Inputs:
@@ -2981,7 +2997,7 @@ fmt_complex :: proc(fi: ^Info, c: complex128, bits: int, verb: rune) {
case 'f', 'F', 'v', 'h', 'H', 'w':
r, i := real(c), imag(c)
fmt_float(fi, r, bits/2, verb)
if !fi.plus && i >= 0 {
if _cq_should_print_intermediate_plus(fi, i) {
io.write_rune(fi.writer, '+', &fi.n)
}
fmt_float(fi, i, bits/2, verb)
@@ -3007,19 +3023,19 @@ fmt_quaternion :: proc(fi: ^Info, q: quaternion256, bits: int, verb: rune) {
fmt_float(fi, r, bits/4, verb)
if !fi.plus && i >= 0 {
if _cq_should_print_intermediate_plus(fi, i) {
io.write_rune(fi.writer, '+', &fi.n)
}
fmt_float(fi, i, bits/4, verb)
io.write_rune(fi.writer, 'i', &fi.n)
if !fi.plus && j >= 0 {
if _cq_should_print_intermediate_plus(fi, j) {
io.write_rune(fi.writer, '+', &fi.n)
}
fmt_float(fi, j, bits/4, verb)
io.write_rune(fi.writer, 'j', &fi.n)
if !fi.plus && k >= 0 {
if _cq_should_print_intermediate_plus(fi, k) {
io.write_rune(fi.writer, '+', &fi.n)
}
fmt_float(fi, k, bits/4, verb)