Skip to content

Commit 9c4561f

Browse files
committed
Julia-like Printing
1 parent 7057716 commit 9c4561f

File tree

2 files changed

+34
-11
lines changed

2 files changed

+34
-11
lines changed

src/Quadmath.jl

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
module Quadmath
22
using Compat: @assume_effects
33

4-
export Float128, ComplexF128, Inf128
4+
export Float128, ComplexF128, Inf128, NaN128
55

66
import Base: (*), +, -, /, <, <=, ==, ^, convert,
77
reinterpret, sign_mask, exponent_mask, exponent_one, exponent_half,
@@ -341,6 +341,13 @@ const Inf128 = reinterpret(Float128, exponent_mask(Float128))
341341
typemax(::Type{Float128}) = Inf128
342342
typemin(::Type{Float128}) = -Inf128
343343

344+
"""
345+
NaN128
346+
347+
A not-a-number value of type [`Float128`](@ref).
348+
"""
349+
const NaN128 = reinterpret(Float128, UInt128(0x7fff8)<<108)
350+
344351
@static if !Sys.iswindows()
345352
# disable fma on Windows until rounding mode issue fixed
346353
# https://github.com/JuliaMath/Quadmath.jl/issues/31
@@ -551,15 +558,26 @@ function parse(::Type{Float128}, s::AbstractString)
551558
Float128(@quad_ccall(libquadmath.strtoflt128(s::Cstring, C_NULL::Ptr{Ptr{Cchar}})::Cfloat128))
552559
end
553560

561+
using Base.Ryu: writeshortest
554562
function string(x::Float128)
555-
lng = 64
556-
buf = Array{UInt8}(undef, lng + 1)
557-
lng = @quad_ccall(libquadmath.quadmath_snprintf(buf::Ptr{UInt8}, (lng+1)::Csize_t, "%.35Qe"::Ptr{UInt8}, x::(Cfloat128...))::Cint)
558-
return String(resize!(buf, lng))
563+
buf = Base.StringVector(64)
564+
pos = writeshortest(buf, 1, x)
565+
return String(resize!(buf, pos - 1))
566+
end
567+
function show(io::IO, x::Float128)
568+
buf = Base.StringVector(64)
569+
pos = writeshortest(buf, 1, x)
570+
if isfinite(x)
571+
write(io, "Float128(")
572+
write(io, resize!(buf, pos - 1))
573+
write(io, ')')
574+
else
575+
write(io, resize!(buf, pos - 1))
576+
write(io, "128")
577+
end
578+
return
559579
end
560-
561580
print(io::IO, b::Float128) = print(io, string(b))
562-
show(io::IO, b::Float128) = print(io, string(b))
563581

564582
include("printf.jl")
565583

test/runtests.jl

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,10 +186,15 @@ end
186186
end
187187

188188
@testset "string conversion" begin
189-
s = string(Float128(3.0))
190-
p = r"3\.0+e\+0+"
191-
m = match(p, s)
192-
@test (m != nothing) && (m.match == s)
189+
for (f, s_expected) in [(3.0, "Float128(3.0)"),
190+
(Inf, "Inf128"),
191+
(NaN, "NaN128"),]
192+
iob = IOBuffer()
193+
show(iob, Float128(f))
194+
s = String(take!(iob))
195+
@test s == s_expected
196+
@test string(Float128(f)) == string(f)
197+
end
193198
@test parse(Float128,"3.0") == Float128(3.0)
194199
end
195200

0 commit comments

Comments
 (0)