Skip to content

Commit

Permalink
[GR-18163] Return new String instances from File.basename
Browse files Browse the repository at this point in the history
PullRequest: truffleruby/2631
  • Loading branch information
eregon committed May 6, 2021
2 parents f2e97df + a342767 commit d2c8638
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Compatibility:
* Configure `mandir` value in `RbConfig::CONFIG` and `RbConfig::MAKEFILE_CONFIG` (#2315).
* TruffleRuby now supports the Truffle polyglot Hash interop API.
* Implement `Fiber#raise` (#2338).
* Update `File.basename` to return new `String` instances (#2343).

Performance:

Expand Down
15 changes: 15 additions & 0 deletions spec/ruby/core/file/basename_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,20 @@
basename.encoding.should == Encoding::Windows_1250
end

it "returns a new unfrozen String" do
exts = [nil, '.rb', '.*', '.txt']
['foo.rb','//', '/test/', 'test'].each do |example|
exts.each do |ext|
original = example.freeze
result = if ext
File.basename(original, ext)
else
File.basename(original)
end
result.should_not equal(original)
result.frozen?.should == false
end
end
end

end
8 changes: 4 additions & 4 deletions src/main/ruby/truffleruby/core/file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,20 +183,20 @@ def self.basename(path, ext=undefined)
end

# edge case, it's all /'s, return "/"
return slash unless found
return slash.dup unless found

# Now that we've trimmed the /'s at the end, search again
pos = Primitive.find_string_reverse(path, slash, path.bytesize)
if ext_not_present and !pos
# No /'s found and ext not present, return path.
return path
return path.dup
end
end

path = path.byteslice(pos + 1, path.bytesize - pos) if pos
end

return path if ext_not_present
return path.dup if ext_not_present

# special case. if ext is ".*", remove any extension

Expand All @@ -213,7 +213,7 @@ def self.basename(path, ext=undefined)
end
end

path
path.dup
end

def self.query_stat_mode(path)
Expand Down

0 comments on commit d2c8638

Please sign in to comment.