Skip to content

Commit

Permalink
Change sprintf "%c" to support only Char and Int::Primitive (#1…
Browse files Browse the repository at this point in the history
…5142)


Co-authored-by: Sijawusz Pur Rahnama <[email protected]>
Co-authored-by: Johannes Müller <[email protected]>
  • Loading branch information
3 people authored Dec 10, 2024
1 parent 5d6757c commit 746075e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
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_i8, "B"
assert_sprintf "%c", 67_i16, "C"
assert_sprintf "%c", 68_i32, "D"
assert_sprintf "%c", 69_i64, "E"
assert_sprintf "%c", 97_u8, "a"
assert_sprintf "%c", 98_u16, "b"
assert_sprintf "%c", 99_u32, "c"
assert_sprintf "%c", 100_u64, "d"
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
6 changes: 6 additions & 0 deletions src/string/formatter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,12 @@ struct String::Formatter(A)
end

def char(flags, arg) : Nil
if arg.is_a?(Int::Primitive)
arg = arg.chr
end
unless arg.is_a?(Char)
raise ArgumentError.new("Expected a char or integer, not #{arg.inspect}")
end
pad 1, flags if flags.left_padding?
@io << arg
pad 1, flags if flags.right_padding?
Expand Down

0 comments on commit 746075e

Please sign in to comment.