Skip to content

Commit

Permalink
Add IO#set_encoding_by_bom method
Browse files Browse the repository at this point in the history
Method was introduced in MRI in 2.7.0 in e717d6faa
  • Loading branch information
pawandubey committed Jun 7, 2021
1 parent 81e816f commit b41bbcd
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
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(nil, Encoding::UTF_8)

-> { @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

0 comments on commit b41bbcd

Please sign in to comment.