Skip to content

Commit

Permalink
Fix String#tr 1 byte from optimization bug
Browse files Browse the repository at this point in the history
Ref: crystal-lang#5912 (comment)

`"aabbcc".tr("a", "xyz")` yields `"xyzxyzbbcc"` currently.
Of course it is unintentional behavior, in Ruby it yields `"xxbbcc"` and
on shell `echo aabbcc | tr a xyz` shows `xxbbcc`.
  • Loading branch information
makenowjust committed Apr 4, 2018
1 parent ec423eb commit a083743
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
1 change: 1 addition & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1718,6 +1718,7 @@ describe "String" do
"hello".tr("helo", "1212").should eq("12112")
"this".tr("this", "").should eq("ⓧⓧⓧⓧ")
"über".tr("ü", "u").should eq("uber")
"aabbcc".tr("a", "xyz").should eq("xxbbcc")
end

context "given no replacement characters" do
Expand Down
4 changes: 2 additions & 2 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1590,8 +1590,8 @@ class String
def tr(from : String, to : String)
return delete(from) if to.empty?

if from.bytesize == 1
return gsub(from.unsafe_byte_at(0).unsafe_chr, to)
if from.bytesize == 1 && to.bytesize == 1
return gsub(from.unsafe_byte_at(0).unsafe_chr, to.unsafe_byte_at(0).unsafe_chr)
end

multi = nil
Expand Down

0 comments on commit a083743

Please sign in to comment.