Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change sprintf "%c" to support only Char and Int::Primitive types #15142

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions spec/std/sprintf_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,30 @@ describe "::sprintf" do
pending "floats"
end

context "chars" do
it "works" do
assert_sprintf "%c", 'a', "a"
assert_sprintf "%3c", 'R', " R"
assert_sprintf "%-3c", 'L', "L "
assert_sprintf "%c", '▞', "▞"
assert_sprintf "%c", 65, "A"
assert_sprintf "%c", 66.to_i8, "B"
assert_sprintf "%c", 67.to_i16, "C"
assert_sprintf "%c", 68.to_i32, "D"
assert_sprintf "%c", 69.to_i64, "E"
assert_sprintf "%c", 97.to_u8, "a"
assert_sprintf "%c", 98.to_u16, "b"
assert_sprintf "%c", 99.to_u32, "c"
assert_sprintf "%c", 100.to_u64, "d"
nanobowers marked this conversation as resolved.
Show resolved Hide resolved
assert_sprintf "%c", 0x259E, "▞"
end

it "raises if not a Char or Int" do
expect_raises(ArgumentError, "Expected a char or integer") { sprintf("%c", "this") }
expect_raises(ArgumentError, "Expected a char or integer") { sprintf("%c", 17.34) }
end
end

context "strings" do
it "works" do
assert_sprintf "%s", 'a', "a"
Expand Down
9 changes: 8 additions & 1 deletion src/string/formatter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,15 @@ struct String::Formatter(A)
end

def char(flags, arg) : Nil
val = if arg.is_a?(Char)
arg
elsif arg.is_a?(Int::Primitive)
arg.chr
nanobowers marked this conversation as resolved.
Show resolved Hide resolved
else
raise ArgumentError.new("Expected a char or integer, not #{arg.inspect}")
end
nanobowers marked this conversation as resolved.
Show resolved Hide resolved
pad 1, flags if flags.left_padding?
@io << arg
@io << val
pad 1, flags if flags.right_padding?
end

Expand Down
Loading