lib/readbytes.rb


DEFINITIONS

This source file includes following functions.


   1  # readbytes.rb
   2  #
   3  # add IO#readbytes, which reads fixed sized data.
   4  # it guarantees read data size.
   5  
   6  class TruncatedDataError<IOError
   7    def initialize(mesg, data)
   8      @data = data
   9      super(mesg)
  10    end
  11    attr_reader :data
  12  end
  13  
  14  class IO
  15    def readbytes(n)
  16      str = read(n)
  17      if str == nil
  18        raise EOFError, "End of file reached"
  19      end
  20      if str.size < n
  21        raise TruncatedDataError.new("data truncated", str) 
  22      end
  23      str
  24    end
  25  end
  26  
  27  if __FILE__ == $0
  28    begin
  29      loop do
  30        print STDIN.readbytes(6)
  31      end
  32    rescue TruncatedDataError
  33      p $!.data
  34      raise
  35    end
  36  end