Skip to content

Commit

Permalink
Use textwidth and handle precision with wide characters correctly for…
Browse files Browse the repository at this point in the history
… cfmt (#71)
  • Loading branch information
ScottPJones authored Feb 15, 2024
1 parent 6e1008d commit d120770
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ keywords = ["Strings", "Formatting"]
license = "MIT"
name = "Format"
uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
version = "1.3.4"
version = "1.3.5"

[deps]

Expand Down
29 changes: 18 additions & 11 deletions src/printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -234,21 +234,28 @@ end
# strings
function _fmt(buf, pos, spec::FmtSpec{FmtStr}, arg)
altf, width, prec = spec.altf, spec.width, spec.prec
str = altf && (arg isa Symbol || arg isa AbstractString) ? repr(arg) : string(arg)
slen = length(str)
op = p = prec == -1 ? slen : min(slen, prec)
s = altf && (arg isa Symbol || arg isa AbstractString) ? repr(arg) : string(arg)
slen = textwidth(s)
str, slen = 0 <= prec < slen ? _truncstr(s, slen, prec) : (s, slen)
prepad = postpad = 0
pad = width - slen
if pad > 0
if spec.leftalign
postpad = pad
else
prepad = pad
end
end

# Make sure there is enough room in buffer
nlen = max(width, p)
buflen = sizeof(buf) - pos
buflen < nlen && resize!(buf, nlen + pos)
!spec.leftalign && width > p && (pos = padn(buf, pos, width - p))
nlen = pos + prepad + sizeof(str) + postpad
nlen > sizeof(buf) && resize!(buf, nlen)

prepad == 0 || (pos = padn(buf, pos, prepad))
for c in str
p == 0 && break
pos = writechar(buf, pos, c)
p -= 1
end
spec.leftalign && width > op && return padn(buf, pos, width - op)
return pos
return postpad == 0 ? pos : padn(buf, pos, postpad)
end

const BaseInt = Union{Int8, Int16, Int32, Int64, Int128}
Expand Down
6 changes: 6 additions & 0 deletions test/cformat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,18 @@ include("speedtest.jl")
@test cfmt( "%'f", -Inf ) == "-Inf"
@test cfmt( "%'s", 1000.0 ) == "1,000.0"
@test cfmt( "%'s", 1234567.0 ) == "1.234567e6"
@test cfmt( "%'g", 1000.0 ) == "1,000"
end

@testset "Test bug introduced by stdlib/Printf rewrite" begin
@test cfmt( "%4.2s", "a" ) == " a"
end

@testset "Test precision with wide characters" begin
@test cfmt( "%10.9s", "\U1f355" ^ 6) == " " * "\U1f355" ^ 4
@test cfmt( "%10.10s", "\U1f355" ^ 6) == "\U1f355" ^ 5
end

@testset "test format..." begin
@test format( 10 ) == "10"
@test format( 10.0 ) == "10"
Expand Down

0 comments on commit d120770

Please sign in to comment.