Created
August 23, 2011 15:32
-
-
Save murachue/1165456 to your computer and use it in GitHub Desktop.
looks like disposable script, but I think this reusable...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'stringio' | |
module IOExtend | |
def readq; self.read(8).unpack("Q")[0]; end | |
def readd; self.read(4).unpack("V")[0]; end | |
def readw; self.read(2).unpack("v")[0]; end | |
end | |
class IO; include IOExtend; end | |
class StringIO; include IOExtend; end | |
class String | |
include IOExtend; | |
# IO compat layer (incomplete) | |
def read(n); io().read(n); end | |
def eof(); io().eof(); end | |
# Transparent IO layer | |
def io(&block); @io ||= StringIO.open(self, "rb", &block); end | |
def close(); if @io; @io.close; @io = nil; end; end | |
end | |
### example | |
# prepare file by... | |
# ruby -rzlib -e "d=['Hello','World-','Bye!'].map{|e|[e.size,e].pack('Va*')}.join;d=Zlib::Deflate.deflate d;$>.binmode.write [d.size,d].pack('Va*')" > test.bin | |
require 'zlib' | |
open("test.bin", "rb") do |f| | |
len = f.readd | |
dat = Zlib::Inflate.inflate(f.read(len)) | |
# usable type | |
while !dat.eof | |
dlen = dat.readd | |
ddat = dat.read(dlen) | |
puts "data = #{ddat}" | |
end | |
# another type | |
dat.close # reset... | |
dat.io { |f| | |
while !f.eof | |
dlen = f.readd | |
ddat = f.read(dlen) | |
puts "data = #{ddat}" | |
end | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment