PageRenderTime 108ms CodeModel.GetById 103ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/Ruby/lib/ruby/1.8/readbytes.rb

http://github.com/agross/netopenspace
Ruby | 41 lines | 29 code | 4 blank | 8 comment | 5 complexity | fb5aac253fd8332686741879c4070338 MD5 | raw file
 1# TruncatedDataError is raised when IO#readbytes fails to read enough data.
 2
 3class TruncatedDataError<IOError
 4  def initialize(mesg, data) # :nodoc:
 5    @data = data
 6    super(mesg)
 7  end
 8
 9  # The read portion of an IO#readbytes attempt.
10  attr_reader :data
11end
12
13class IO
14  # Reads exactly +n+ bytes.
15  #
16  # If the data read is nil an EOFError is raised.
17  #
18  # If the data read is too short a TruncatedDataError is raised and the read
19  # data is obtainable via its #data method.
20  def readbytes(n)
21    str = read(n)
22    if str == nil
23      raise EOFError, "End of file reached"
24    end
25    if str.size < n
26      raise TruncatedDataError.new("data truncated", str) 
27    end
28    str
29  end
30end
31
32if __FILE__ == $0
33  begin
34    loop do
35      print STDIN.readbytes(6)
36    end
37  rescue TruncatedDataError
38    p $!.data
39    raise
40  end
41end