kaitai-io / kaitai_struct_ruby_runtime

Kaitai Struct: runtime for Ruby

Home Page:https://rubygems.org/gems/kaitai-struct

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow creating Kaitai::Struct::Stream from StringIO (not just String)

generalmimon opened this issue · comments

This code:

require 'stringio'
require_relative 'lib/kaitai/struct/struct'

io = Kaitai::Struct::Stream.new(StringIO.new("PK\x03\x04"))

currently fails with

$ ruby t.rb
C:/temp/kaitai_struct/runtime/ruby/lib/kaitai/struct/struct.rb:104:in `initialize': can be initialized with IO, SubIO or String only (TypeError)
        from t.rb:4:in `new'
        from t.rb:4:in `<main>'

because the Stream.new implementation expects to receive a plain String instead:

io = Kaitai::Struct::Stream.new("PK\x03\x04")

and it will create a StringIO itself:

def initialize(arg)
if arg.is_a?(String)
@_io = StringIO.new(arg)
elsif arg.is_a?(IO) or arg.is_a?(SubIO)
@_io = arg
else
raise TypeError.new('can be initialized with IO, SubIO or String only')
end

I think rejecting the accepted StringIO and insisting on creating it "automatically" is an unnecessary restriction, and initialization with StringIO should be allowed as well to make it foolproof.

Interesting... I've never realized that StringIO is not derived from IO in Ruby. I've tried to fix it.