Skip to content

Commit d120770

Browse files
authored
Use textwidth and handle precision with wide characters correctly for cfmt (#71)
1 parent 6e1008d commit d120770

3 files changed

Lines changed: 25 additions & 12 deletions

File tree

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ keywords = ["Strings", "Formatting"]
2323
license = "MIT"
2424
name = "Format"
2525
uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
26-
version = "1.3.4"
26+
version = "1.3.5"
2727

2828
[deps]
2929

src/printf.jl

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -234,21 +234,28 @@ end
234234
# strings
235235
function _fmt(buf, pos, spec::FmtSpec{FmtStr}, arg)
236236
altf, width, prec = spec.altf, spec.width, spec.prec
237-
str = altf && (arg isa Symbol || arg isa AbstractString) ? repr(arg) : string(arg)
238-
slen = length(str)
239-
op = p = prec == -1 ? slen : min(slen, prec)
237+
s = altf && (arg isa Symbol || arg isa AbstractString) ? repr(arg) : string(arg)
238+
slen = textwidth(s)
239+
str, slen = 0 <= prec < slen ? _truncstr(s, slen, prec) : (s, slen)
240+
prepad = postpad = 0
241+
pad = width - slen
242+
if pad > 0
243+
if spec.leftalign
244+
postpad = pad
245+
else
246+
prepad = pad
247+
end
248+
end
249+
240250
# Make sure there is enough room in buffer
241-
nlen = max(width, p)
242-
buflen = sizeof(buf) - pos
243-
buflen < nlen && resize!(buf, nlen + pos)
244-
!spec.leftalign && width > p && (pos = padn(buf, pos, width - p))
251+
nlen = pos + prepad + sizeof(str) + postpad
252+
nlen > sizeof(buf) && resize!(buf, nlen)
253+
254+
prepad == 0 || (pos = padn(buf, pos, prepad))
245255
for c in str
246-
p == 0 && break
247256
pos = writechar(buf, pos, c)
248-
p -= 1
249257
end
250-
spec.leftalign && width > op && return padn(buf, pos, width - op)
251-
return pos
258+
return postpad == 0 ? pos : padn(buf, pos, postpad)
252259
end
253260

254261
const BaseInt = Union{Int8, Int16, Int32, Int64, Int128}

test/cformat.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,18 @@ include("speedtest.jl")
4949
@test cfmt( "%'f", -Inf ) == "-Inf"
5050
@test cfmt( "%'s", 1000.0 ) == "1,000.0"
5151
@test cfmt( "%'s", 1234567.0 ) == "1.234567e6"
52+
@test cfmt( "%'g", 1000.0 ) == "1,000"
5253
end
5354

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

59+
@testset "Test precision with wide characters" begin
60+
@test cfmt( "%10.9s", "\U1f355" ^ 6) == " " * "\U1f355" ^ 4
61+
@test cfmt( "%10.10s", "\U1f355" ^ 6) == "\U1f355" ^ 5
62+
end
63+
5864
@testset "test format..." begin
5965
@test format( 10 ) == "10"
6066
@test format( 10.0 ) == "10"

0 commit comments

Comments
 (0)