Skip to content

Commit ecfd1a0

Browse files
authored
better error message for rpad/lpad with zero-width padding (JuliaLang#56488)
Closes JuliaLang#45339 — throw a more informative `ArgumentError` message from `rpad` and `lpad` if a zero-`textwidth` padding is passed (not a `DivideError`). If the padding character has `ncodeunits == 1`, suggests that maybe they want `str * pad^max(0, npad - ncodeunits(str))` instead.
1 parent 024d42a commit ecfd1a0

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

base/strings/util.jl

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,12 @@ function lpad(
476476
n = Int(n)::Int
477477
m = signed(n) - Int(textwidth(s))::Int
478478
m 0 && return stringfn(s)
479-
l = textwidth(p)
479+
l = Int(textwidth(p))::Int
480+
if l == 0
481+
throw(ArgumentError("$(repr(p)) has zero textwidth" * (ncodeunits(p) != 1 ? "" :
482+
"; maybe you want pad^max(0, npad - ncodeunits(str)) * str to pad by codeunits" *
483+
(s isa AbstractString && codeunit(s) != UInt8 ? "?" : " (bytes)?"))))
484+
end
480485
q, r = divrem(m, l)
481486
r == 0 ? stringfn(p^q, s) : stringfn(p^q, first(p, r), s)
482487
end
@@ -508,7 +513,12 @@ function rpad(
508513
n = Int(n)::Int
509514
m = signed(n) - Int(textwidth(s))::Int
510515
m 0 && return stringfn(s)
511-
l = textwidth(p)
516+
l = Int(textwidth(p))::Int
517+
if l == 0
518+
throw(ArgumentError("$(repr(p)) has zero textwidth" * (ncodeunits(p) != 1 ? "" :
519+
"; maybe you want str * pad^max(0, npad - ncodeunits(str)) to pad by codeunits" *
520+
(s isa AbstractString && codeunit(s) != UInt8 ? "?" : " (bytes)?"))))
521+
end
512522
q, r = divrem(m, l)
513523
r == 0 ? stringfn(s, p^q) : stringfn(s, p^q, first(p, r))
514524
end

test/strings/util.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ end
6565
@test rpad("⟨k|H₁|k̃⟩", 12) |> textwidth == 12
6666
@test lpad("⟨k|H₁|k⟩", 12) |> textwidth == 12
6767
@test rpad("⟨k|H₁|k⟩", 12) |> textwidth == 12
68+
for pad in (rpad, lpad), p in ('\0', "\0", "\0\0", "\u302")
69+
if ncodeunits(p) == 1
70+
@test_throws r".*has zero textwidth.*maybe you want.*bytes.*" pad("foo", 10, p)
71+
else
72+
@test_throws r".*has zero textwidth$" pad("foo", 10, p)
73+
end
74+
end
6875
end
6976

7077
@testset "string truncation (ltruncate, rtruncate, ctruncate)" begin

0 commit comments

Comments
 (0)