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

Add IO#set_encoding_by_bom method #2372

Merged
merged 1 commit into from
Jun 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions spec/ruby/core/io/set_encoding_by_bom_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,11 @@

-> { @io.set_encoding_by_bom }.should raise_error(ArgumentError, 'encoding is set to UTF-8 already')
end

it 'returns exception if encoding conversion is already set' do
@io.set_encoding(Encoding::UTF_8, Encoding::UTF_16BE)

-> { @io.set_encoding_by_bom }.should raise_error(ArgumentError, 'encoding conversion is set')
end
end
end
8 changes: 0 additions & 8 deletions spec/tags/core/io/set_encoding_by_bom_tags.txt

This file was deleted.

19 changes: 19 additions & 0 deletions src/main/ruby/truffleruby/core/io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,25 @@ def set_encoding(external, internal=nil, options=undefined)
self
end

def set_encoding_by_bom
unless binmode?
raise ArgumentError, 'ASCII incompatible encoding needs binmode'
end

if internal_encoding
raise ArgumentError, 'encoding conversion is set'
end

if external_encoding && external_encoding != Encoding::ASCII_8BIT
raise ArgumentError, "encoding is set to #{external_encoding} already"
end

external = strip_bom
if external
@external = Encoding.find(external)
end
end

private def strip_bom
mode = Truffle::POSIX.truffleposix_fstat_mode(Primitive.io_fd(self))
return unless Truffle::StatOperations.file?(mode)
Expand Down