Skip to content

Accept an Integer mode and open options in StringIO.new and StringIO.open - #3329

Open
hasannadeem wants to merge 1 commit into
ruby:masterfrom
hasannadeem:stringio-new-options
Open

hasannadeem wants to merge 1 commit into
ruby:masterfrom
hasannadeem:stringio-new-options

Conversation

@hasannadeem

Copy link
Copy Markdown
Contributor

StringIO.new and StringIO.open take the mode as a String or as an Integer of File flags, and they take the same mode and encoding keywords as IO.new. The signatures only allowed (?String string, ?String? mode), so these were rejected:

StringIO.new(str, File::RDONLY)
StringIO.new(str, mode: "rb:BOM|UTF-8")
StringIO.new(str, "r", encoding: Encoding::BINARY)
StringIO.open(str, mode: File::RDONLY) { |io| io.read }

strio_init hands the mode and the keywords to rb_io_extract_modeenc. That function reads mode:, flags:, external_encoding:, internal_encoding:, encoding:, textmode: and binmode:, and the signature now lists those. The string goes through StringValue and an Integer mode through to_int, so the positional arguments are string and string | int | nil.

The encoding keywords take effect only when a positional mode is given as well. strio_init uses the string's own encoding when the string is the only positional argument. For example, StringIO.new(s, "r", encoding: "BINARY") reads binary, while StringIO.new(s, encoding: "BINARY") keeps s's encoding.

Not changed

StringIO.new(nil) is also accepted at runtime, and then #string returns nil. Allowing nil here would mean #string has to return String?, which affects every caller, so I left it out.

Checked

  • Behaviour is the same on Ruby 3.4.4 and 4.0.7 (both ship stringio 3.2.0).
  • test/stdlib/StringIO_test.rb passes on both. With the old signature, test_new and test_open fail.
  • Steep (strict) on a sample that uses these calls: 10 errors before, 0 after. Two deliberately wrong calls, mode: :r and an unknown keyword, are still rejected.
  • rbs -r stringio validate passes, and rbs annotate makes no further changes to the file.
  • The branch merges cleanly with Accept a nil separator and a bare limit in StringIO's line methods #3328, which changes the line methods in the same files.

…open

StringIO.new takes the mode as a String or an Integer of File flags,
and the same mode and encoding keywords as IO.new (mode:, flags:,
external_encoding:, internal_encoding:, encoding:, textmode:,
binmode:). The string and the mode also go through to_str and to_int.
The signatures only allowed a String and a String mode, so
StringIO.new(str, File::RDONLY) and StringIO.new(str, mode: "rb")
were rejected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant